@munchi_oy/payments 1.10.1 → 1.10.4

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 k=Object.defineProperty;var Y=Object.getOwnPropertyDescriptor;var B=Object.getOwnPropertyNames;var $=Object.prototype.hasOwnProperty;var Q=(a,e)=>{for(var n in e)k(a,n,{get:e[n],enumerable:!0})},j=(a,e,n,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of B(e))!$.call(a,r)&&r!==n&&k(a,r,{get:()=>e[r],enumerable:!(t=Y(e,r))||t.enumerable});return a};var z=a=>j(k({},"__esModule",{value:!0}),a);var ue={};Q(ue,{AppReaderStatus:()=>q,MunchiPaymentSDK:()=>U,PaymentInteractionState:()=>E,SdkPaymentStatus:()=>T});module.exports=z(ue);var h=require("@munchi_oy/core");var V="1.10.1";var l=class a extends Error{code;rawError;constructor(e,n,t){super(n),this.name="PaymentSDKError",this.code=e,this.rawError=t,Object.setPrototypeOf(this,a.prototype)}};var A=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||{}),E=(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))(E||{});var I=require("@munchi_oy/core");function H(a){throw new l("UNKNOWN",`Unhandled payment session status: ${String(a)}`)}function w(a){return{success:!1,status:"PENDING",orderId:a,errorCode:"",errorMessage:""}}function D(a,e){switch(a.status){case I.PaymentSessionStatus.Initiated:case I.PaymentSessionStatus.Processing:case I.PaymentSessionStatus.Voiding:case I.PaymentSessionStatus.Refunding:return w(e);case I.PaymentSessionStatus.Success:case I.PaymentSessionStatus.Closed:{let n={success:!0,status:"SUCCESS",orderId:e,errorCode:"",errorMessage:""};return a.providerTransactionId&&(n.transactionId=a.providerTransactionId),n}case I.PaymentSessionStatus.VoidFailed:case I.PaymentSessionStatus.Failed:{let n={success:!1,status:"FAILED",orderId:e,errorCode:a.errorCode||I.PaymentFailureCode.SystemUnknown,errorMessage:a.errorMessage||"Transaction failed without error details"};return a.providerTransactionId&&(n.transactionId=a.providerTransactionId),n}case I.PaymentSessionStatus.Cancelled:case I.PaymentSessionStatus.Voided:case I.PaymentSessionStatus.Refunded:{let n={success:!1,status:"CANCELLED",orderId:e};return a.errorCode&&(n.errorCode=a.errorCode),a.errorMessage&&(n.errorMessage=a.errorMessage),a.providerTransactionId&&(n.transactionId=a.providerTransactionId),n}default:return H(a.status)}}var O=class{constructor(e,n){this.config=n;this.sessionApi=new A.PaymentSessionApi(void 0,"",e)}sessionApi;async recordPayment(e){try{let n={businessId:Number(this.config.storeId),orderId:e.orderRef,amount:e.amountCents,paymethod:e.paymethod,provider:this.config.provider};e.tipAmount!==void 0&&(n.tipAmount=e.tipAmount),e.splitContext!==void 0&&(n.splitContext=e.splitContext),e.metadata!==void 0&&(n.metadata=e.metadata);let{data:t}=await this.sessionApi.recordManualPayment(n);return D(t,e.orderRef)}catch(n){throw new l("NETWORK_ERROR","Failed to record manual payment",n)}}async voidPayment(e){try{let{data:n}=await this.sessionApi.voidManualPayment({sessionId:e.sessionId}),t=n.status===A.PaymentSessionStatus.Voided||n.status===A.PaymentSessionStatus.Voiding,r={success:t,status:t?"SUCCESS":"FAILED",orderId:e.orderRef,transactionId:n.providerTransactionId??n.sessionId};return t||(n.errorCode&&(r.errorCode=n.errorCode),n.errorMessage&&(r.errorMessage=n.errorMessage)),r}catch(n){throw new l("NETWORK_ERROR","Failed to void manual payment",n)}}};var g=require("@munchi_oy/core");var _=class{constructor(e,n,t){this.messaging=n;this.config=t;this.api=new g.PaymentApi(void 0,"",e)}api;abortController=null;currentRequestId=null;paymentProvider=g.PaymentProviderEnum.Nets;async processPayment(e,n){this.abortController=new AbortController,n("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:r}=await this.api.initiateNetsTerminalTransaction(t),s=r.connectCloudRequestId;if(!s)throw new Error("connectCloudRequestId is missing from response.");if(this.currentRequestId=s,this.abortController.signal.aborted)throw new Error("Aborted");n("REQUIRES_INPUT",{sessionId:s});let i=await this.waitForPaymentCompletion(s,e.orderRef,this.abortController.signal);return this.currentRequestId=null,i}catch(r){throw this.currentRequestId=null,r instanceof l?r:new l("TERMINAL_BUSY","Failed to create Nets Intent",r)}}async waitForPaymentCompletion(e,n,t){let r=`nets.requests.${e}`,s=g.PaymentEventType.StatusChanged;return new Promise((i,o)=>{let c=!1,u=()=>{c=!0,typeof m=="function"&&m(),clearTimeout(f)},d=()=>{u(),o(new l("CANCELLED","Transaction cancelled"))};t.addEventListener("abort",d);let m=this.messaging.subscribe(r,s,p=>{c||p.status===g.SimplePaymentStatus.Pending||(u(),t.removeEventListener("abort",d),i(this.handleSuccess(p)))}),f=setTimeout(async()=>{if(!(c||t.aborted))try{let p=await this.pollOrderStatus(e,n,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,n,t,r){let c=Date.now()+12e4;for(;Date.now()<c;){if(r.aborted)throw new Error("Aborted");try{let{data:u}=await this.api.getPaymentStatus({businessId:Number(t),orderId:n,provider:this.paymentProvider,referenceId:e});if(r.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)};r.addEventListener("abort",d,{once:!0});let m=setTimeout(()=>{r.removeEventListener("abort",d),u(void 0)},2e3)})}throw new Error("Payment verification timed out.")}async cancelTransaction(e){if(!this.currentRequestId)return!1;let n={requestId:this.currentRequestId,businessId:Number(this.config.storeId)};try{return await this.api.cancelNetsTerminalTransaction(n),this.abortController?.abort(),this.currentRequestId=null,!0}catch{return!1}}async refundTransaction(e,n){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:r}=await this.api.initiateNetsTerminalTransaction(t),s=r.connectCloudRequestId;if(!s)throw new Error("connectCloudRequestId is missing from response.");if(this.currentRequestId=s,this.abortController.signal.aborted)throw new Error("Aborted");n("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,n){try{let{data:t}=await this.api.getPaymentStatus({businessId:Number(this.config.storeId),orderId:e.orderRef,provider:this.paymentProvider,referenceId:n});return this.handleSuccess(t)}catch(t){throw new l("NETWORK_ERROR","Failed to verify final Nets status",t)}}handleSuccess(e){let n=e.status===g.SimplePaymentStatus.Success,t=e.status===g.SimplePaymentStatus.Pending,r={success:n,status:n?"SUCCESS":t?"PENDING":"FAILED",orderId:e.orderId,transaction:e.transaction};return e.transactionId&&(r.transactionId=e.transactionId),e.error?.code&&(r.errorCode=e.error.code),e.error?.message&&(r.errorMessage=e.error.message),r}abort(){this.abortController?.abort()}};var y=require("@munchi_oy/core");var L=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 Z="vivapayclient://pay/v1",ee="abort",te="cancel",ne="sale",G="transactionDetails",re=4e3,se="534287",ie="38",oe="493591",ae="497439",ce=[oe,ae],le=["CREDIT","PREPAID","CORPORATE"],x=class{constructor(e,n,t,r){this.config=t;this.appToAppConfig=r;this.api=new y.VivaApi(void 0,"",e),this.paymentApi=new y.PaymentApi(void 0,"",e),this.paymentApiWithReference=this.paymentApi}api;paymentApi;abortController=null;currentClientTransactionId=null;currentIsvClientTransactionId=null;currentCurrency=null;currentOrderRef=null;currentSourceTerminalId=null;latestResult=null;paymentApiWithReference;wasCancelled=!1;getExecutionMode(){return"callback_driven"}async processPayment(e,n){if(!this.appToAppConfig.enabled)throw new l("STRATEGY_ERROR","Viva app-to-app is not enabled");n("CONNECTING");try{let{data:t}=await this.api.createVivaAppToAppPayment(this.buildCreatePaymentPayload(e));return await this.runAction(ne,this.buildLaunchParams(t),e,n)}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 n=await this.lookupTransactionDetails();if(n)return this.latestResult=n,this.wasCancelled=n.status==="CANCELLED",this.abortController?.abort(),!0;try{await this.appToAppConfig.adapter.openUrl(this.buildActionUrl(ee,{}))}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,n){n("CONNECTING");let t=await this.fetchPaymentReference(e),r=this.buildRefundLaunchParams(e,t);return this.runAction(te,r,e,n)}async verifyFinalStatus(e,n){return this.latestResult?this.latestResult:this.wasCancelled?{success:!1,status:"CANCELLED",orderId:this.currentOrderRef??n,errorCode:y.PaymentFailureCode.PaymentCancelledByUser,errorMessage:"Transaction was cancelled",transactionId:n}:{success:!1,status:"PENDING",orderId:this.currentOrderRef??n,transactionId:n}}abort(){this.abortController?.abort()}async runAction(e,n,t,r){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=n.sourceTerminalId??n.tid??null,this.currentClientTransactionId=n.clientTransactionId??null,this.currentIsvClientTransactionId=n.ISV_clientTransactionId??null;let s=this.currentClientTransactionId?{sessionId:this.currentClientTransactionId}:void 0;return new Promise((i,o)=>{let c=(m,f)=>{m?.(),this.abortController?.signal.removeEventListener("abort",f)},u=()=>{c(d,u),o(new Error("Aborted"))},d=this.appToAppConfig.adapter.subscribe(m=>{if(this.abortController?.signal.aborted)return;let f=this.parseCallbackUrl(m);f&&this.matchesKnownTransactionId(f.rawParams)&&(this.latestResult=f.result,this.wasCancelled=f.result.status==="CANCELLED",this.currentClientTransactionId=null,this.currentIsvClientTransactionId=null,this.currentCurrency=null,this.currentOrderRef=null,this.currentSourceTerminalId=null,c(d,u),i(f.result))});this.abortController?.signal.addEventListener("abort",u),r("REQUIRES_INPUT",s),this.appToAppConfig.adapter.openUrl(this.buildActionUrl(e,n)).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 n=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 n.tipAmount!==void 0&&(t.tipAmount=n.tipAmount),t}buildLaunchParams(e){let n={};return Object.entries(e).forEach(([t,r])=>{r!==void 0&&(n[t]=String(r))}),n}buildRefundLaunchParams(e,n){let t=e.options??{},r=n?.originalTransactionId?.trim()||e.originalTransactionId.trim(),s={amount:String(e.amountCents),clientTransactionId:r,show_receipt:"false",show_transaction_result:"false"};if(t.sourceCode&&(s.sourceCode=t.sourceCode),n?.referenceCode&&(s.orderCode=n.referenceCode),n?.shortReferenceCode&&(s.shortOrderCode=n.shortReferenceCode),n?.receiptNumber&&(s.referenceNumber=n.receiptNumber),n?.terminalId&&(s.tid=n.terminalId),n?.referenceCode||n?.shortReferenceCode||n?.receiptNumber)return s;let i=r;return/^\d+$/.test(i)&&(i.length===16?s.orderCode=i:i.length===10?s.shortOrderCode=i:s.referenceNumber=i),s}async fetchPaymentReference(e){try{let n={orderId:e.orderRef,provider:y.PaymentProvider.Viva,transactionId:e.originalTransactionId,businessId:e.businessId},{data:t}=await this.paymentApiWithReference.getPaymentReference(n);return this.extractPaymentReferenceContext(t)}catch{return}}extractPaymentReferenceContext(e){if(!e)return;let n=e.references;if(!n||typeof n!="object"||Array.isArray(n))return{originalTransactionId:e.originalTransactionId};let t=n,r={originalTransactionId:this.readReferenceValue(t.originalTransactionId)??this.readReferenceValue(t.clientTransactionId)??e.originalTransactionId},s=this.readReferenceValue(t.receiptNumber)??this.readReferenceValue(t.referenceNumber),i=this.readReferenceValue(t.referenceCode)??this.readReferenceValue(t.orderCode),o=this.readReferenceValue(t.shortReferenceCode)??this.readReferenceValue(t.shortOrderCode),c=this.readReferenceValue(t.terminalId)??this.readReferenceValue(t.tid);return s&&(r.receiptNumber=s),i&&(r.referenceCode=i),o&&(r.shortReferenceCode=o),c&&(r.terminalId=c),r}readReferenceValue(e){if(typeof e!="string")return;let n=e.trim();return n.length>0?n:void 0}buildActionUrl(e,n){let t=new URLSearchParams({action:e,appId:this.appToAppConfig.appId,callback:this.resolveCallbackQueryParam()});return Object.entries(n).forEach(([r,s])=>{t.set(r,s)}),`${Z}?${t.toString()}`}parseCallbackUrl(e){if(!this.matchesCallbackBase(e))return null;let n=new URL(e),t=Object.fromEntries(n.searchParams.entries()),r=this.isSuccessfulCallback(t),s=this.isCancelledCallback(t),i=this.resolveFailureCode(t,s),o={success:r,status:r?"SUCCESS":s?"CANCELLED":"FAILED",orderId:this.currentOrderRef??t.clientTransactionId??"unknown",errorCode:r?"":i,errorMessage:r?"":t.message??"Transaction failed without error details"};r&&(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 n=new URL(e),t=this.appToAppConfig.callbackUrl;if(!t.includes("://")){let s=t.replace(/:$/,"");return n.protocol===`${s}:`}let r=new URL(t);return n.protocol===r.protocol&&n.hostname===r.hostname&&n.pathname===r.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 n=[this.currentClientTransactionId,this.currentIsvClientTransactionId].filter(r=>!!r);if(n.length===0)return!0;let t=[e.clientTransactionId,e.ISV_clientTransactionId].filter(r=>!!r);return t.length===0?!0:t.some(r=>n.includes(r))}resolveFailureCode(e,n){if(n)return y.PaymentFailureCode.PaymentCancelledByUser;let t=e.errorCode;if(t?.includes("."))return t;if(this.isTransactionDetailsAction(e)&&(e.transactionType??"").toLowerCase().includes("abort"))return y.PaymentFailureCode.SystemUnknown;let r=(e.message??"").toLowerCase(),s=(e.status??"").toLowerCase();return r.includes("declined")||s==="declined"||s==="fail"||s==="failed"||s==="failure"?y.PaymentFailureCode.PaymentDeclined:y.PaymentFailureCode.SystemUnknown}isSuccessfulCallback(e){let n=(e.status??"").toLowerCase();return this.isTransactionDetailsAction(e)?n!=="success"?!1:!(e.transactionType??"").toLowerCase().includes("abort"):n==="success"}isTransactionDetailsAction(e){return(e.action??"").toLowerCase()===G.toLowerCase()}isCancelledCallback(e){let n=(e.status??"").toLowerCase(),t=(e.message??"").toLowerCase(),r=(e.errorCode??"").toLowerCase();return n==="cancelled"||n==="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")||r.includes("user_cancel")||r.includes("user cancel")||r==="1000"&&(t.includes("cancelled by user")||t.includes("canceled by user"))}extractErrorReferenceFromMessage(e){return e?e.match(/\((-?\d+)\)/)?.[1]:void 0}mapCallbackToTransaction(e){let n=e.transactionId??e.orderCode??e.clientTransactionId??"unknown",t=W(e.transactionDate),r=L(e.tipAmount),s=L(e.surchargeAmount);return{amount:L(e.amount)-r-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:n},createdAt:t,fees:this.buildFees(r,s),id:n,label:null,provider:y.PaymentProvider.Viva,rawData:e,referenceId:e.clientTransactionId??null,roundingDifference:0,type:this.getVivaPaymentMethodType(e)}}getVivaPaymentMethodType(e){let n=(e.applicationLabel??"").toUpperCase().trim(),r=(e.accountNumber??"").substring(0,6),s=(e.bankId??"").trim();return r===se||s===ie?y.PaymentMethod.Edenred:ce.includes(r)?y.PaymentMethod.WoltBenefit:le.some(i=>n.includes(i))?y.PaymentMethod.Credit:y.PaymentMethod.Debit}buildFees(e,n){if(!this.currentCurrency)return null;let t=[];return e>0&&t.push({taxAmount:0,total:{amount:e,currency:this.currentCurrency},type:y.FeeType.TipAmount,vatPercentage:0}),n>0&&t.push({taxAmount:0,total:{amount:n,currency:this.currentCurrency},type:y.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(n=>{let t=!1,r=setTimeout(()=>{t||(t=!0,s(),n(null))},re),s=this.appToAppConfig.adapter.subscribe(i=>{if(t)return;let o=this.parseCallbackUrl(i);o&&this.matchesKnownTransactionId(o.rawParams)&&(t=!0,clearTimeout(r),s(),n(o.result))});this.appToAppConfig.adapter.openUrl(this.buildActionUrl(G,e)).catch(()=>{t||(t=!0,clearTimeout(r),s(),n(null))})})}};var S=require("@munchi_oy/core");var F=class a{constructor(e,n,t){this.messaging=n;this.config=t;this.sessionApi=new S.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,n){this.abortController=new AbortController,(this.idempotencyKey===null||this.idempotencyOrderRef!==e.orderRef)&&(this.idempotencyKey=this.generateIdempotencyKey(),this.idempotencyOrderRef=e.orderRef),this.currentClientToken=null,n("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:r}=await this.sessionApi.initiateVivaSession(t,this.idempotencyKey);this.currentClientToken=r.clientToken;let s=this.abortController.signal;if(s.aborted)throw new Error("Aborted");n("REQUIRES_INPUT",{sessionId:r.sessionId});let i=await this.waitForCompletion(r.clientToken,r.sessionId,e,s);return i?this.finalize(i):(await this.armCancel(r.clientToken),w(e.orderRef))}catch(r){throw r instanceof l?r:new l("NETWORK_ERROR","Failed to create Viva payment session",r)}}async verifyFinalStatus(e,n){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??w(e.orderRef))}async cancelTransaction(e){if(!this.currentClientToken)return!1;try{await this.sessionApi.cancelVivaSession(this.currentClientToken)}catch(n){throw new l("NETWORK_ERROR","Failed to cancel Viva payment session",n)}return this.abortController?.abort(),!0}async refundTransaction(e,n){try{let t={sessionId:e.originalTransactionId,amount:e.amountCents},{data:r}=await this.sessionApi.refundVivaSession(t),s=r.status===S.PaymentSessionStatus.Refunded||r.status===S.PaymentSessionStatus.Refunding,i={success:s,status:s?"SUCCESS":"FAILED",orderId:e.orderRef,transactionId:r.providerTransactionId??r.sessionId};return s||(r.errorCode&&(i.errorCode=r.errorCode),r.errorMessage&&(i.errorMessage=r.errorMessage)),i}catch(t){throw new l("NETWORK_ERROR","Failed to refund Viva transaction",t)}}async revertTransaction(e){try{let n={sessionId:e.originalTransactionId},{data:t}=await this.sessionApi.revertVivaSession(n),r=t.status===S.PaymentSessionStatus.Refunded||t.status===S.PaymentSessionStatus.Refunding,s={success:r,status:r?"SUCCESS":"FAILED",orderId:e.orderRef,transactionId:t.providerTransactionId??t.sessionId};return r||(t.errorCode&&(s.errorCode=t.errorCode),t.errorMessage&&(s.errorMessage=t.errorMessage)),s}catch(n){throw new l("NETWORK_ERROR","Failed to revert Viva transaction",n)}}abort(){this.abortController?.abort()}async pollUntilTerminal(e,n,t,r){let s=Date.now()+r;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=D(i,n.orderRef);if(o.status!=="PENDING")return o}await this.delay(a.POLLING_INTERVAL_MS,t)}}waitForCompletion(e,n,t,r){let s=`viva.${this.config.channel.toLowerCase()}.requests.${n}`;return new Promise((i,o)=>{let c=!1,u=()=>{c=!0,typeof m=="function"&&m(),clearTimeout(f),r.removeEventListener("abort",d)},d=()=>{u(),o(new Error("Aborted"))};r.addEventListener("abort",d);let m=this.messaging.subscribe(s,"payment:status-changed",p=>{c||p.status!==S.SimplePaymentStatus.Pending&&(u(),i(this.mapStatusDto(p,t)))}),f=setTimeout(()=>{c||this.pollUntilTerminal(e,t,r,a.POLLING_DURATION_MS).then(p=>{c||(u(),i(p))},p=>{c||(u(),o(p))})},a.INITIAL_POLL_DELAY_MS)})}mapStatusDto(e,n){let t=e.status===S.SimplePaymentStatus.Success,r={success:t,status:t?"SUCCESS":"FAILED",orderId:n.orderRef,errorCode:e.error?.code||(t?"":S.PaymentFailureCode.SystemUnknown),errorMessage:e.error?.message||(t?"":"Transaction failed without error details")};return e.transactionId&&(r.transactionId=e.transactionId),e.error?.referenceError&&(r.errorReference=e.error.referenceError),e.transaction&&(r.transaction=e.transaction),r}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,n=>{let t=Math.random()*16|0;return(n==="x"?t:t&3|8).toString(16)})}delay(e,n){return new Promise(t=>{let r=()=>{clearTimeout(s),t()};n&&n.addEventListener("abort",r,{once:!0});let s=setTimeout(()=>{n&&n.removeEventListener("abort",r),t()},e)})}};var P=require("@munchi_oy/core");var N=class a{constructor(e,n,t){this.messaging=n;this.config=t;this.api=new P.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=P.PaymentProviderEnum.Viva;async processPayment(e,n){this.abortController=new AbortController,n("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:r}=await this.api.initiateTerminalTransaction(t);if(this.currentSessionId=r.sessionId,this.abortController.signal.aborted)throw new Error("Aborted");n("REQUIRES_INPUT",{sessionId:r.sessionId});let s=await this.waitForPaymentCompletion(r.sessionId,e,this.abortController.signal);return this.currentSessionId=null,s}catch(r){throw this.currentSessionId=null,r instanceof l?r:new l("NETWORK_ERROR","Failed to create Viva Intent",r)}}async waitForPaymentCompletion(e,n,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 f=="function"&&f(),clearTimeout(p)},m=()=>{d(),c(new Error("Aborted"))};t.addEventListener("abort",m);let f=this.messaging.subscribe(s,i,C=>{u||C.status!==P.SimplePaymentStatus.Pending&&(d(),t.removeEventListener("abort",m),o(this.handleSuccess(C)))}),p=setTimeout(async()=>{if(!(u||t.aborted))try{let C=await this.pollOrderStatus(e,n.orderRef,this.config.storeId,t);if(u)return;o(this.handleSuccess(C))}catch(C){if(u)return;if(C instanceof Error&&C.message==="Aborted"){c(C);return}try{let v=await this.recoverAfterPollingTimeout(n,e);o(v)}catch(v){c(v instanceof l?v:new l("TIMEOUT","Payment timed out and polling failed",v))}}finally{t.removeEventListener("abort",m),d()}},a.INITIAL_POLL_DELAY_MS)})}async pollOrderStatus(e,n,t,r){let i=Date.now()+a.POLLING_DURATION_MS;for(;Date.now()<i;){if(r.aborted)throw new Error("Aborted");try{let{data:o}=await this.api.getPaymentStatus({businessId:Number(t),orderId:n,provider:this.paymentProvider,referenceId:e});if(r.aborted)throw new Error("Aborted");if(o.status!==P.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)};r.addEventListener("abort",c,{once:!0});let u=setTimeout(()=>{r.removeEventListener("abort",c),o(void 0)},a.POLLING_INTERVAL_MS)})}throw new Error("Payment verification timed out.")}async recoverAfterPollingTimeout(e,n){return await this.cancelSessionWithTimeout(n),await this.verifyFinalStatusWithRetry(e,n)}async cancelSessionWithTimeout(e){let n;try{await Promise.race([this.cancelSession(e),new Promise((t,r)=>{n=setTimeout(()=>{r(new Error("Viva timeout cancellation timed out"))},a.TIMEOUT_CANCEL_TIMEOUT_MS)})])}catch{}finally{n&&clearTimeout(n)}}async cancelSession(e){return await this.api.cancelVivaTransactionV2({cashRegisterId:this.config.storeId,sessionId:e}),this.currentSessionId===e&&(this.currentSessionId=null),!0}async verifyFinalStatusWithRetry(e,n){let t;for(let s=1;s<=a.VERIFY_MAX_RETRIES;s++)try{let i=await Promise.race([this.verifyFinalStatus(e,n),new Promise((o,c)=>setTimeout(()=>c(new Error("Verify timed out")),a.VERIFY_TIMEOUT_MS))]);if(i.status==="PENDING"){t=new Error("Verify returned pending status"),s<a.VERIFY_MAX_RETRIES&&await new Promise(o=>setTimeout(o,a.VERIFY_RETRY_DELAY_MS));continue}return i}catch(i){t=i,s<a.VERIFY_MAX_RETRIES&&await new Promise(o=>setTimeout(o,a.VERIFY_RETRY_DELAY_MS))}let r=t instanceof Error?t.message:"Verify retries exhausted";throw new l(P.PaymentFailureCode.PaymentTimeout,r)}handleSuccess(e){let n=e.status===P.SimplePaymentStatus.Success,t={success:n,status:n?"SUCCESS":"FAILED",orderId:e.orderId,errorCode:e.error?.code||(n?"":P.PaymentFailureCode.SystemUnknown),errorMessage:e.error?.message||(n?"":"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 n=this.currentSessionId;return this.currentSessionId=null,await this.api.cancelVivaTransactionV2({cashRegisterId:this.config.storeId,sessionId:n}),this.abortController?.abort(),!0}catch(n){throw this.currentSessionId=null,new l("NETWORK_ERROR","Failed to cancel Viva transaction",n)}}async verifyFinalStatus(e,n){try{let{data:t}=await this.api.getPaymentStatus({businessId:Number(this.config.storeId),orderId:e.orderRef,provider:this.paymentProvider,referenceId:n}),r=t.status===P.SimplePaymentStatus.Success,s=t.status===P.SimplePaymentStatus.Pending,i={success:r,status:r?"SUCCESS":s?"PENDING":"FAILED",orderId:t.orderId,errorCode:t.error?.code||(r||s?"":P.PaymentFailureCode.SystemUnknown),errorMessage:t.error?.message||(r||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,n){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:r}=await this.api.refundSingleVivaTransaction(t),s=r.success;return{success:s,status:s?"SUCCESS":"FAILED",orderId:e.orderRef,transactionId:r.sessionId}}catch(t){throw new l("NETWORK_ERROR","Failed to refund Viva transaction",t)}}abort(){this.abortController?.abort()}};var R=require("@munchi_oy/core"),K=require("axios");var M=class{constructor(e,n,t){this.messaging=n;this.config=t;this.paymentApi=new R.PaymentApi(void 0,"",e),this.worldlineApi=new R.WorldlineApi(void 0,"",e)}paymentApi;worldlineApi;abortController=null;currentOperationId=null;paymentProvider=R.PaymentProviderEnum.Worldline;async processPayment(e,n){this.abortController=new AbortController,n("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 r=await this.worldlineApi.createPayment(t),s=this.extractOperationId(r.data);if(this.currentOperationId=s,this.abortController.signal.aborted)throw new Error("Aborted");n("REQUIRES_INPUT",{sessionId:s});let i=await this.waitForPaymentCompletion(s,e.orderRef,R.PaymentEventType.StatusChanged,this.abortController.signal);return this.currentOperationId=null,i}catch(r){throw this.currentOperationId=null,r instanceof l?r:this.mapWorldlineRequestError(r,"Failed to create Worldline payment")}}async cancelTransaction(e){if(!this.currentOperationId)return!1;let n={businessId:Number(this.config.storeId),targetOperationId:this.currentOperationId};try{return await this.worldlineApi.cancelPayment(n),!0}catch(t){throw this.mapWorldlineRequestError(t,"Failed to cancel Worldline transaction")}}async refundTransaction(e,n){this.abortController=new AbortController,n("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 r=await this.worldlineApi.createRefund(t),s=this.extractOperationId(r.data);if(this.currentOperationId=s,this.abortController.signal.aborted)throw new Error("Aborted");n("REQUIRES_INPUT",{sessionId:s});let i=await this.waitForPaymentCompletion(s,e.orderRef,R.PaymentEventType.RefundStatusChanged,this.abortController.signal);return this.currentOperationId=null,i}catch(r){throw this.currentOperationId=null,r instanceof l?r:this.mapWorldlineRequestError(r,"Failed to refund Worldline transaction")}}async verifyFinalStatus(e,n){try{let{data:t}=await this.paymentApi.getPaymentStatus({businessId:Number(this.config.storeId),orderId:e.orderRef,provider:this.paymentProvider,referenceId:n});return this.handlePaymentStatus(t)}catch(t){throw this.mapWorldlineRequestError(t,"Failed to verify final Worldline status")}}abort(){this.abortController?.abort()}async waitForPaymentCompletion(e,n,t,r){let s=`worldline.requests.${e}`;return new Promise((i,o)=>{let c=!1,u=()=>{c=!0,typeof m=="function"&&m(),clearTimeout(f)},d=()=>{u(),o(new l("CANCELLED","Transaction cancelled"))};r.addEventListener("abort",d);let m=this.messaging.subscribe(s,t,p=>{c||p.status===R.SimplePaymentStatus.Pending||(u(),r.removeEventListener("abort",d),i(this.handlePaymentStatus(p)))}),f=setTimeout(async()=>{if(!(c||r.aborted))try{let p=await this.pollOrderStatus(e,n,this.config.storeId,r);i(this.handlePaymentStatus(p))}catch(p){o(new l("TIMEOUT","Payment timed out and polling failed",p))}finally{r.removeEventListener("abort",d),u()}},1e4)})}async pollOrderStatus(e,n,t,r){let o=Date.now()+12e4;for(;Date.now()<o;){if(r.aborted)throw new Error("Aborted");try{let{data:c}=await this.paymentApi.getPaymentStatus({businessId:Number(t),orderId:n,provider:this.paymentProvider,referenceId:e});if(r.aborted)throw new Error("Aborted");if(c.status!==R.SimplePaymentStatus.Pending)return c}catch(c){if(c instanceof Error&&c.message==="Aborted")throw c}await new Promise(c=>{let u=()=>{clearTimeout(d),c(void 0)};r.addEventListener("abort",u,{once:!0});let d=setTimeout(()=>{r.removeEventListener("abort",u),c(void 0)},2e3)})}throw new Error("Payment verification timed out.")}handlePaymentStatus(e){let n=e.status===R.SimplePaymentStatus.Success,t=e.status===R.SimplePaymentStatus.Pending,r={success:n,status:n?"SUCCESS":t?"PENDING":"FAILED",orderId:e.orderId,errorCode:e.error?.code||(n||t?"":R.PaymentFailureCode.SystemUnknown),errorMessage:e.error?.message||(n||t?"":"Transaction failed without error details")};return e.transactionId&&(r.transactionId=e.transactionId),e.error?.referenceError&&(r.errorReference=e.error.referenceError),e.transaction&&(r.transaction=e.transaction),r}extractOperationId(e){let n=typeof e=="object"&&e!==null&&"operationId"in e&&typeof e.operationId=="string"?e.operationId:null;if(!n)throw new Error("operationId is missing from response.");return n}mapWorldlineRequestError(e,n){if((0,K.isAxiosError)(e)){if(e.response?.status===400||e.response?.status===409)return new l("TERMINAL_BUSY",n,e);if(e.response?.status===404)return new l("TERMINAL_OFFLINE",n,e)}return new l("NETWORK_ERROR",n,e)}};var U=class a{strategy;axios;messaging;timeoutMs;logger;_currentState="IDLE";_listeners=[];_cancellationIntent=!1;_currentSessionId;_autoResetTimer;autoResetOptions;appToAppConfig;paymentSessionConfig;manualStrategy;static TERMINAL_STATES=["SUCCESS","FAILED","INTERNAL_ERROR"];static RESTING_STATES=["IDLE",...a.TERMINAL_STATES];constructor(e,n,t,r={},s){this.axios=e,this.messaging=n,this.logger=r.logger,this.timeoutMs=r.timeoutMs||3e4,this.autoResetOptions=r.autoResetOnPaymentComplete,this.appToAppConfig=r.appToApp,this.paymentSessionConfig=r.paymentSession,this.manualStrategy=new O(e,t),this.strategy=s??this.resolveStrategy(t)}get version(){return V}get currentState(){return this._currentState}generateErrorResult(e,n,t){return{success:!1,status:"ERROR",errorCode:this.normalizeErrorCode(n),errorMessage:t,orderId:e}}normalizeErrorCode(e){return e?e.includes(".")?e:{CANCELLED:h.PaymentFailureCode.PaymentCancelledByUser,DECLINED:h.PaymentFailureCode.PaymentDeclined,TERMINAL_BUSY:h.PaymentFailureCode.TerminalBusy,TERMINAL_OFFLINE:h.PaymentFailureCode.TerminalOffline,TIMEOUT:h.PaymentFailureCode.TerminalTimeout,NETWORK_ERROR:h.PaymentFailureCode.SystemProviderError,STRATEGY_ERROR:h.PaymentFailureCode.SystemProviderError,MISSING_CONFIG:h.PaymentFailureCode.SystemUnknown,INVALID_AMOUNT:h.PaymentFailureCode.SystemUnknown,UNKNOWN:h.PaymentFailureCode.SystemUnknown}[e]??h.PaymentFailureCode.SystemUnknown:h.PaymentFailureCode.SystemUnknown}subscribe=e=>(this._listeners.push(e),e(this._currentState),()=>{this._listeners=this._listeners.filter(n=>n!==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(r=>r(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 h.PaymentProvider.Nets:return new _(this.axios,this.messaging,e);case h.PaymentProvider.Worldline:return new M(this.axios,this.messaging,e);case h.PaymentProvider.Viva:return this.appToAppConfig?.enabled?new x(this.axios,this.messaging,e,this.appToAppConfig):this.paymentSessionConfig?.enabled?new F(this.axios,this.messaging,e):new N(this.axios,this.messaging,e);default:return new N(this.axios,this.messaging,e)}}initiateTransaction=async(e,n)=>{let t=n??{},r=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,f)=>{f?.sessionId&&(this._currentSessionId=f.sessionId),m!=="FAILED"&&(this.transitionTo(m),this.fireStateCallback(m,t,r))},c=this.strategy.processPayment(e,o),d=(this.strategy.getExecutionMode?.()??"managed")==="callback_driven"?await c:await Promise.race([c,new Promise((m,f)=>{setTimeout(()=>{f(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,n,t={}){let r=n instanceof l&&(n.code==="TIMEOUT"||n.code===h.PaymentFailureCode.PaymentTimeout);if(!this._cancellationIntent&&!r&&(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=r&&i.status==="PENDING"?this.buildErrorResultFromException(e.orderRef,n):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,n);return this.transitionTo("FAILED"),this.safeFireCallback(()=>t.onError?.(s)),s}buildErrorResultFromException(e,n){return n instanceof l?this.generateErrorResult(e,n.code,n.message):this.generateErrorResult(e,"UNKNOWN",n instanceof Error?n.message:"Unknown fatal error")}fireStateCallback(e,n,t){let r={orderRef:t,refPaymentId:this._currentSessionId};switch(e){case"CONNECTING":this.safeFireCallback(()=>n.onConnecting?.(r));break;case"REQUIRES_INPUT":this.safeFireCallback(()=>n.onRequiresInput?.(r));break;case"PROCESSING":this.safeFireCallback(()=>n.onProcessing?.(r));break}}safeFireCallback(e){try{e()}catch(n){this.logger?.warn("Callback execution failed",{error:n})}}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(n=>this.transitionTo(n))}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,n)=>{let t=n??{};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,n)=>{let t=n??{};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 r=this.strategy.revertTransaction?.bind(this.strategy);if(!r)return this.generateErrorResult(e.orderRef,"STRATEGY_ERROR","Revert is not supported by the active payment strategy");this.transitionTo("CONNECTING");try{let s=await r(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)}};recordManualPayment=async(e,n)=>{let t=n??{};if(this.logger?.info("Recording manual payment",{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("CONNECTING"),this.safeFireCallback(()=>t.onConnecting?.({orderRef:e.orderRef,refPaymentId:void 0}));try{let r=await this.manualStrategy.recordPayment(e);return this.settleSingleShot(r,e.orderRef,t),r}catch(r){return this.logger?.error("Manual payment failed",r),this.failSingleShot(e.orderRef,r,"Manual payment failed",t)}};voidManualPayment=async(e,n)=>{let t=n??{};if(this.logger?.info("Voiding manual payment",{orderRef:e.orderRef}),this._currentSessionId=e.sessionId,this._cancellationIntent=!1,!a.RESTING_STATES.includes(this._currentState))return this.generateErrorResult(e.orderRef,"UNKNOWN","A transaction is already in progress");this.transitionTo("CONNECTING");try{let r=await this.manualStrategy.voidPayment(e);return this.settleSingleShot(r,e.orderRef,t),r}catch(r){return this.logger?.error("Manual void failed",r),this.failSingleShot(e.orderRef,r,"Void failed",t)}};settleSingleShot(e,n,t){e.success?(this.transitionTo("SUCCESS"),this.safeFireCallback(()=>t.onSuccess?.(e))):e.status==="CANCELLED"?(this.transitionTo("FAILED"),this.safeFireCallback(()=>t.onCancelled?.({orderRef:n,refPaymentId:this._currentSessionId}))):(this.transitionTo("FAILED"),this.safeFireCallback(()=>t.onError?.(e)))}failSingleShot(e,n,t,r){let s=this.generateErrorResult(e,"NETWORK_ERROR",n instanceof Error?n.message:t);return this.transitionTo("FAILED"),this.safeFireCallback(()=>r.onError?.(s)),s}};var q=(r=>(r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r.OFFLINE="OFFLINE",r.DISCONNECTED="DISCONNECTED",r))(q||{});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.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});
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{PaymentFailureCode as y,PaymentProvider as k}from"@munchi_oy/core";var W="1.10.1";var l=class c extends Error{code;rawError;constructor(e,n,t){super(n),this.name="PaymentSDKError",this.code=e,this.rawError=t,Object.setPrototypeOf(this,c.prototype)}};import{PaymentSessionApi as J,PaymentSessionStatus as G}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=(a=>(a.IDLE="IDLE",a.CONNECTING="CONNECTING",a.REQUIRES_INPUT="REQUIRES_INPUT",a.PROCESSING="PROCESSING",a.SUCCESS="SUCCESS",a.FAILED="FAILED",a.INTERNAL_ERROR="INTERNAL_ERROR",a.VERIFYING="VERIFYING",a))(g||{});import{PaymentFailureCode as X,PaymentSessionStatus as h}from"@munchi_oy/core";function H(c){throw new l("UNKNOWN",`Unhandled payment session status: ${String(c)}`)}function b(c){return{success:!1,status:"PENDING",orderId:c,errorCode:"",errorMessage:""}}function v(c,e){switch(c.status){case h.Initiated:case h.Processing:case h.Voiding:case h.Refunding:return b(e);case h.Success:case h.Closed:{let n={success:!0,status:"SUCCESS",orderId:e,errorCode:"",errorMessage:""};return c.providerTransactionId&&(n.transactionId=c.providerTransactionId),n}case h.VoidFailed:case h.Failed:{let n={success:!1,status:"FAILED",orderId:e,errorCode:c.errorCode||X.SystemUnknown,errorMessage:c.errorMessage||"Transaction failed without error details"};return c.providerTransactionId&&(n.transactionId=c.providerTransactionId),n}case h.Cancelled:case h.Voided:case h.Refunded:{let n={success:!1,status:"CANCELLED",orderId:e};return c.errorCode&&(n.errorCode=c.errorCode),c.errorMessage&&(n.errorMessage=c.errorMessage),c.providerTransactionId&&(n.transactionId=c.providerTransactionId),n}default:return H(c.status)}}var A=class{constructor(e,n){this.config=n;this.sessionApi=new J(void 0,"",e)}sessionApi;async recordPayment(e){try{let n={businessId:Number(this.config.storeId),orderId:e.orderRef,amount:e.amountCents,paymethod:e.paymethod,provider:this.config.provider};e.tipAmount!==void 0&&(n.tipAmount=e.tipAmount),e.splitContext!==void 0&&(n.splitContext=e.splitContext),e.metadata!==void 0&&(n.metadata=e.metadata);let{data:t}=await this.sessionApi.recordManualPayment(n);return v(t,e.orderRef)}catch(n){throw new l("NETWORK_ERROR","Failed to record manual payment",n)}}async voidPayment(e){try{let{data:n}=await this.sessionApi.voidManualPayment({sessionId:e.sessionId}),t=n.status===G.Voided||n.status===G.Voiding,r={success:t,status:t?"SUCCESS":"FAILED",orderId:e.orderRef,transactionId:n.providerTransactionId??n.sessionId};return t||(n.errorCode&&(r.errorCode=n.errorCode),n.errorMessage&&(r.errorMessage=n.errorMessage)),r}catch(n){throw new l("NETWORK_ERROR","Failed to void manual payment",n)}}};import{PaymentApi as Z,PaymentEventType as ee,PaymentProviderEnum as te,SimplePaymentStatus as N,TransactionType as K}from"@munchi_oy/core";var w=class{constructor(e,n,t){this.messaging=n;this.config=t;this.api=new Z(void 0,"",e)}api;abortController=null;currentRequestId=null;paymentProvider=te.Nets;async processPayment(e,n){this.abortController=new AbortController,n("CONNECTING");let t={amount:e.amountCents,businessId:Number(this.config.storeId),referenceId:e.orderRef,currency:e.currency,displayId:e.displayId,options:{allowPinBypass:!0,transactionType:K.Purchase}};try{let{data:r}=await this.api.initiateNetsTerminalTransaction(t),s=r.connectCloudRequestId;if(!s)throw new Error("connectCloudRequestId is missing from response.");if(this.currentRequestId=s,this.abortController.signal.aborted)throw new Error("Aborted");n("REQUIRES_INPUT",{sessionId:s});let i=await this.waitForPaymentCompletion(s,e.orderRef,this.abortController.signal);return this.currentRequestId=null,i}catch(r){throw this.currentRequestId=null,r instanceof l?r:new l("TERMINAL_BUSY","Failed to create Nets Intent",r)}}async waitForPaymentCompletion(e,n,t){let r=`nets.requests.${e}`,s=ee.StatusChanged;return new Promise((i,o)=>{let a=!1,u=()=>{a=!0,typeof m=="function"&&m(),clearTimeout(f)},d=()=>{u(),o(new l("CANCELLED","Transaction cancelled"))};t.addEventListener("abort",d);let m=this.messaging.subscribe(r,s,p=>{a||p.status===N.Pending||(u(),t.removeEventListener("abort",d),i(this.handleSuccess(p)))}),f=setTimeout(async()=>{if(!(a||t.aborted))try{let p=await this.pollOrderStatus(e,n,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,n,t,r){let a=Date.now()+12e4;for(;Date.now()<a;){if(r.aborted)throw new Error("Aborted");try{let{data:u}=await this.api.getPaymentStatus({businessId:Number(t),orderId:n,provider:this.paymentProvider,referenceId:e});if(r.aborted)throw new Error("Aborted");if(u.status!==N.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)};r.addEventListener("abort",d,{once:!0});let m=setTimeout(()=>{r.removeEventListener("abort",d),u(void 0)},2e3)})}throw new Error("Payment verification timed out.")}async cancelTransaction(e){if(!this.currentRequestId)return!1;let n={requestId:this.currentRequestId,businessId:Number(this.config.storeId)};try{return await this.api.cancelNetsTerminalTransaction(n),this.abortController?.abort(),this.currentRequestId=null,!0}catch{return!1}}async refundTransaction(e,n){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:K.ReturnOfGoods}},{data:r}=await this.api.initiateNetsTerminalTransaction(t),s=r.connectCloudRequestId;if(!s)throw new Error("connectCloudRequestId is missing from response.");if(this.currentRequestId=s,this.abortController.signal.aborted)throw new Error("Aborted");n("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,n){try{let{data:t}=await this.api.getPaymentStatus({businessId:Number(this.config.storeId),orderId:e.orderRef,provider:this.paymentProvider,referenceId:n});return this.handleSuccess(t)}catch(t){throw new l("NETWORK_ERROR","Failed to verify final Nets status",t)}}handleSuccess(e){let n=e.status===N.Success,t=e.status===N.Pending,r={success:n,status:n?"SUCCESS":t?"PENDING":"FAILED",orderId:e.orderId,transaction:e.transaction};return e.transactionId&&(r.transactionId=e.transactionId),e.error?.code&&(r.errorCode=e.error.code),e.error?.message&&(r.errorMessage=e.error.message),r}abort(){this.abortController?.abort()}};import{FeeType as Y,PaymentApi as re,PaymentFailureCode as T,PaymentMethod as O,PaymentProvider as B,VivaApi as se}from"@munchi_oy/core";var D=c=>{if(!c)return 0;let e=Number.parseInt(c,10);return Number.isFinite(e)?e:0},q=c=>{if(!c)return new Date().toISOString();let e=new Date(c);return Number.isNaN(e.getTime())?new Date().toISOString():e.toISOString()};var ie="vivapayclient://pay/v1",oe="abort",ae="cancel",ce="sale",$="transactionDetails",le=4e3,ue="534287",de="38",me="493591",pe="497439",fe=[me,pe],ye=["CREDIT","PREPAID","CORPORATE"],_=class{constructor(e,n,t,r){this.config=t;this.appToAppConfig=r;this.api=new se(void 0,"",e),this.paymentApi=new re(void 0,"",e),this.paymentApiWithReference=this.paymentApi}api;paymentApi;abortController=null;currentClientTransactionId=null;currentIsvClientTransactionId=null;currentCurrency=null;currentOrderRef=null;currentSourceTerminalId=null;latestResult=null;paymentApiWithReference;wasCancelled=!1;getExecutionMode(){return"callback_driven"}async processPayment(e,n){if(!this.appToAppConfig.enabled)throw new l("STRATEGY_ERROR","Viva app-to-app is not enabled");n("CONNECTING");try{let{data:t}=await this.api.createVivaAppToAppPayment(this.buildCreatePaymentPayload(e));return await this.runAction(ce,this.buildLaunchParams(t),e,n)}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 n=await this.lookupTransactionDetails();if(n)return this.latestResult=n,this.wasCancelled=n.status==="CANCELLED",this.abortController?.abort(),!0;try{await this.appToAppConfig.adapter.openUrl(this.buildActionUrl(oe,{}))}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,n){n("CONNECTING");let t=await this.fetchPaymentReference(e),r=this.buildRefundLaunchParams(e,t);return this.runAction(ae,r,e,n)}async verifyFinalStatus(e,n){return this.latestResult?this.latestResult:this.wasCancelled?{success:!1,status:"CANCELLED",orderId:this.currentOrderRef??n,errorCode:T.PaymentCancelledByUser,errorMessage:"Transaction was cancelled",transactionId:n}:{success:!1,status:"PENDING",orderId:this.currentOrderRef??n,transactionId:n}}abort(){this.abortController?.abort()}async runAction(e,n,t,r){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=n.sourceTerminalId??n.tid??null,this.currentClientTransactionId=n.clientTransactionId??null,this.currentIsvClientTransactionId=n.ISV_clientTransactionId??null;let s=this.currentClientTransactionId?{sessionId:this.currentClientTransactionId}:void 0;return new Promise((i,o)=>{let a=(m,f)=>{m?.(),this.abortController?.signal.removeEventListener("abort",f)},u=()=>{a(d,u),o(new Error("Aborted"))},d=this.appToAppConfig.adapter.subscribe(m=>{if(this.abortController?.signal.aborted)return;let f=this.parseCallbackUrl(m);f&&this.matchesKnownTransactionId(f.rawParams)&&(this.latestResult=f.result,this.wasCancelled=f.result.status==="CANCELLED",this.currentClientTransactionId=null,this.currentIsvClientTransactionId=null,this.currentCurrency=null,this.currentOrderRef=null,this.currentSourceTerminalId=null,a(d,u),i(f.result))});this.abortController?.signal.addEventListener("abort",u),r("REQUIRES_INPUT",s),this.appToAppConfig.adapter.openUrl(this.buildActionUrl(e,n)).then(()=>{this.abortController?.signal.aborted}).catch(m=>{a(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 n=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 n.tipAmount!==void 0&&(t.tipAmount=n.tipAmount),t}buildLaunchParams(e){let n={};return Object.entries(e).forEach(([t,r])=>{r!==void 0&&(n[t]=String(r))}),n}buildRefundLaunchParams(e,n){let t=e.options??{},r=n?.originalTransactionId?.trim()||e.originalTransactionId.trim(),s={amount:String(e.amountCents),clientTransactionId:r,show_receipt:"false",show_transaction_result:"false"};if(t.sourceCode&&(s.sourceCode=t.sourceCode),n?.referenceCode&&(s.orderCode=n.referenceCode),n?.shortReferenceCode&&(s.shortOrderCode=n.shortReferenceCode),n?.receiptNumber&&(s.referenceNumber=n.receiptNumber),n?.terminalId&&(s.tid=n.terminalId),n?.referenceCode||n?.shortReferenceCode||n?.receiptNumber)return s;let i=r;return/^\d+$/.test(i)&&(i.length===16?s.orderCode=i:i.length===10?s.shortOrderCode=i:s.referenceNumber=i),s}async fetchPaymentReference(e){try{let n={orderId:e.orderRef,provider:B.Viva,transactionId:e.originalTransactionId,businessId:e.businessId},{data:t}=await this.paymentApiWithReference.getPaymentReference(n);return this.extractPaymentReferenceContext(t)}catch{return}}extractPaymentReferenceContext(e){if(!e)return;let n=e.references;if(!n||typeof n!="object"||Array.isArray(n))return{originalTransactionId:e.originalTransactionId};let t=n,r={originalTransactionId:this.readReferenceValue(t.originalTransactionId)??this.readReferenceValue(t.clientTransactionId)??e.originalTransactionId},s=this.readReferenceValue(t.receiptNumber)??this.readReferenceValue(t.referenceNumber),i=this.readReferenceValue(t.referenceCode)??this.readReferenceValue(t.orderCode),o=this.readReferenceValue(t.shortReferenceCode)??this.readReferenceValue(t.shortOrderCode),a=this.readReferenceValue(t.terminalId)??this.readReferenceValue(t.tid);return s&&(r.receiptNumber=s),i&&(r.referenceCode=i),o&&(r.shortReferenceCode=o),a&&(r.terminalId=a),r}readReferenceValue(e){if(typeof e!="string")return;let n=e.trim();return n.length>0?n:void 0}buildActionUrl(e,n){let t=new URLSearchParams({action:e,appId:this.appToAppConfig.appId,callback:this.resolveCallbackQueryParam()});return Object.entries(n).forEach(([r,s])=>{t.set(r,s)}),`${ie}?${t.toString()}`}parseCallbackUrl(e){if(!this.matchesCallbackBase(e))return null;let n=new URL(e),t=Object.fromEntries(n.searchParams.entries()),r=this.isSuccessfulCallback(t),s=this.isCancelledCallback(t),i=this.resolveFailureCode(t,s),o={success:r,status:r?"SUCCESS":s?"CANCELLED":"FAILED",orderId:this.currentOrderRef??t.clientTransactionId??"unknown",errorCode:r?"":i,errorMessage:r?"":t.message??"Transaction failed without error details"};r&&(o.transaction=this.mapCallbackToTransaction(t));let a=t.transactionId??t.orderCode??t.clientTransactionId,u=t.errorCode??this.extractErrorReferenceFromMessage(t.message)??t.referenceNumber??t.tid??t.rrn;return a&&(o.transactionId=a),u&&(o.errorReference=u),{rawParams:t,result:o}}matchesCallbackBase(e){let n=new URL(e),t=this.appToAppConfig.callbackUrl;if(!t.includes("://")){let s=t.replace(/:$/,"");return n.protocol===`${s}:`}let r=new URL(t);return n.protocol===r.protocol&&n.hostname===r.hostname&&n.pathname===r.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 n=[this.currentClientTransactionId,this.currentIsvClientTransactionId].filter(r=>!!r);if(n.length===0)return!0;let t=[e.clientTransactionId,e.ISV_clientTransactionId].filter(r=>!!r);return t.length===0?!0:t.some(r=>n.includes(r))}resolveFailureCode(e,n){if(n)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 r=(e.message??"").toLowerCase(),s=(e.status??"").toLowerCase();return r.includes("declined")||s==="declined"||s==="fail"||s==="failed"||s==="failure"?T.PaymentDeclined:T.SystemUnknown}isSuccessfulCallback(e){let n=(e.status??"").toLowerCase();return this.isTransactionDetailsAction(e)?n!=="success"?!1:!(e.transactionType??"").toLowerCase().includes("abort"):n==="success"}isTransactionDetailsAction(e){return(e.action??"").toLowerCase()===$.toLowerCase()}isCancelledCallback(e){let n=(e.status??"").toLowerCase(),t=(e.message??"").toLowerCase(),r=(e.errorCode??"").toLowerCase();return n==="cancelled"||n==="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")||r.includes("user_cancel")||r.includes("user cancel")||r==="1000"&&(t.includes("cancelled by user")||t.includes("canceled by user"))}extractErrorReferenceFromMessage(e){return e?e.match(/\((-?\d+)\)/)?.[1]:void 0}mapCallbackToTransaction(e){let n=e.transactionId??e.orderCode??e.clientTransactionId??"unknown",t=q(e.transactionDate),r=D(e.tipAmount),s=D(e.surchargeAmount);return{amount:D(e.amount)-r-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:n},createdAt:t,fees:this.buildFees(r,s),id:n,label:null,provider:B.Viva,rawData:e,referenceId:e.clientTransactionId??null,roundingDifference:0,type:this.getVivaPaymentMethodType(e)}}getVivaPaymentMethodType(e){let n=(e.applicationLabel??"").toUpperCase().trim(),r=(e.accountNumber??"").substring(0,6),s=(e.bankId??"").trim();return r===ue||s===de?O.Edenred:fe.includes(r)?O.WoltBenefit:ye.some(i=>n.includes(i))?O.Credit:O.Debit}buildFees(e,n){if(!this.currentCurrency)return null;let t=[];return e>0&&t.push({taxAmount:0,total:{amount:e,currency:this.currentCurrency},type:Y.TipAmount,vatPercentage:0}),n>0&&t.push({taxAmount:0,total:{amount:n,currency:this.currentCurrency},type:Y.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(n=>{let t=!1,r=setTimeout(()=>{t||(t=!0,s(),n(null))},le),s=this.appToAppConfig.adapter.subscribe(i=>{if(t)return;let o=this.parseCallbackUrl(i);o&&this.matchesKnownTransactionId(o.rawParams)&&(t=!0,clearTimeout(r),s(),n(o.result))});this.appToAppConfig.adapter.openUrl(this.buildActionUrl($,e)).catch(()=>{t||(t=!0,clearTimeout(r),s(),n(null))})})}};import{PaymentFailureCode as he,PaymentSessionApi as Re,PaymentSessionStatus as L,SimplePaymentStatus as Q}from"@munchi_oy/core";var x=class c{constructor(e,n,t){this.messaging=n;this.config=t;this.sessionApi=new Re(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,n){this.abortController=new AbortController,(this.idempotencyKey===null||this.idempotencyOrderRef!==e.orderRef)&&(this.idempotencyKey=this.generateIdempotencyKey(),this.idempotencyOrderRef=e.orderRef),this.currentClientToken=null,n("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:r}=await this.sessionApi.initiateVivaSession(t,this.idempotencyKey);this.currentClientToken=r.clientToken;let s=this.abortController.signal;if(s.aborted)throw new Error("Aborted");n("REQUIRES_INPUT",{sessionId:r.sessionId});let i=await this.waitForCompletion(r.clientToken,r.sessionId,e,s);return i?this.finalize(i):(await this.armCancel(r.clientToken),b(e.orderRef))}catch(r){throw r instanceof l?r:new l("NETWORK_ERROR","Failed to create Viva payment session",r)}}async verifyFinalStatus(e,n){if(!this.currentClientToken)throw new l("NETWORK_ERROR","No active payment session to verify");let t=await this.pollUntilTerminal(this.currentClientToken,e,void 0,c.VERIFY_DURATION_MS);return this.finalize(t??b(e.orderRef))}async cancelTransaction(e){if(!this.currentClientToken)return!1;try{await this.sessionApi.cancelVivaSession(this.currentClientToken)}catch(n){throw new l("NETWORK_ERROR","Failed to cancel Viva payment session",n)}return this.abortController?.abort(),!0}async refundTransaction(e,n){try{let t={sessionId:e.originalTransactionId,amount:e.amountCents},{data:r}=await this.sessionApi.refundVivaSession(t),s=r.status===L.Refunded||r.status===L.Refunding,i={success:s,status:s?"SUCCESS":"FAILED",orderId:e.orderRef,transactionId:r.providerTransactionId??r.sessionId};return s||(r.errorCode&&(i.errorCode=r.errorCode),r.errorMessage&&(i.errorMessage=r.errorMessage)),i}catch(t){throw new l("NETWORK_ERROR","Failed to refund Viva transaction",t)}}async revertTransaction(e){try{let n={sessionId:e.originalTransactionId},{data:t}=await this.sessionApi.revertVivaSession(n),r=t.status===L.Refunded||t.status===L.Refunding,s={success:r,status:r?"SUCCESS":"FAILED",orderId:e.orderRef,transactionId:t.providerTransactionId??t.sessionId};return r||(t.errorCode&&(s.errorCode=t.errorCode),t.errorMessage&&(s.errorMessage=t.errorMessage)),s}catch(n){throw new l("NETWORK_ERROR","Failed to revert Viva transaction",n)}}abort(){this.abortController?.abort()}async pollUntilTerminal(e,n,t,r){let s=Date.now()+r;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,n.orderRef);if(o.status!=="PENDING")return o}await this.delay(c.POLLING_INTERVAL_MS,t)}}waitForCompletion(e,n,t,r){let s=`viva.${this.config.channel.toLowerCase()}.requests.${n}`;return new Promise((i,o)=>{let a=!1,u=()=>{a=!0,typeof m=="function"&&m(),clearTimeout(f),r.removeEventListener("abort",d)},d=()=>{u(),o(new Error("Aborted"))};r.addEventListener("abort",d);let m=this.messaging.subscribe(s,"payment:status-changed",p=>{a||p.status!==Q.Pending&&(u(),i(this.mapStatusDto(p,t)))}),f=setTimeout(()=>{a||this.pollUntilTerminal(e,t,r,c.POLLING_DURATION_MS).then(p=>{a||(u(),i(p))},p=>{a||(u(),o(p))})},c.INITIAL_POLL_DELAY_MS)})}mapStatusDto(e,n){let t=e.status===Q.Success,r={success:t,status:t?"SUCCESS":"FAILED",orderId:n.orderRef,errorCode:e.error?.code||(t?"":he.SystemUnknown),errorMessage:e.error?.message||(t?"":"Transaction failed without error details")};return e.transactionId&&(r.transactionId=e.transactionId),e.error?.referenceError&&(r.errorReference=e.error.referenceError),e.transaction&&(r.transaction=e.transaction),r}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,n=>{let t=Math.random()*16|0;return(n==="x"?t:t&3|8).toString(16)})}delay(e,n){return new Promise(t=>{let r=()=>{clearTimeout(s),t()};n&&n.addEventListener("abort",r,{once:!0});let s=setTimeout(()=>{n&&n.removeEventListener("abort",r),t()},e)})}};import{PaymentApi as Ie,PaymentFailureCode as U,PaymentProviderEnum as ge,SimplePaymentStatus as C}from"@munchi_oy/core";var E=class c{constructor(e,n,t){this.messaging=n;this.config=t;this.api=new Ie(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=ge.Viva;async processPayment(e,n){this.abortController=new AbortController,n("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:r}=await this.api.initiateTerminalTransaction(t);if(this.currentSessionId=r.sessionId,this.abortController.signal.aborted)throw new Error("Aborted");n("REQUIRES_INPUT",{sessionId:r.sessionId});let s=await this.waitForPaymentCompletion(r.sessionId,e,this.abortController.signal);return this.currentSessionId=null,s}catch(r){throw this.currentSessionId=null,r instanceof l?r:new l("NETWORK_ERROR","Failed to create Viva Intent",r)}}async waitForPaymentCompletion(e,n,t){let s=`viva.${this.config.channel.toLowerCase()}.requests.${e}`,i="payment:status-changed";return new Promise((o,a)=>{let u=!1,d=()=>{u=!0,typeof f=="function"&&f(),clearTimeout(p)},m=()=>{d(),a(new Error("Aborted"))};t.addEventListener("abort",m);let f=this.messaging.subscribe(s,i,I=>{u||I.status!==C.Pending&&(d(),t.removeEventListener("abort",m),o(this.handleSuccess(I)))}),p=setTimeout(async()=>{if(!(u||t.aborted))try{let I=await this.pollOrderStatus(e,n.orderRef,this.config.storeId,t);if(u)return;o(this.handleSuccess(I))}catch(I){if(u)return;if(I instanceof Error&&I.message==="Aborted"){a(I);return}try{let S=await this.recoverAfterPollingTimeout(n,e);o(S)}catch(S){a(S instanceof l?S:new l("TIMEOUT","Payment timed out and polling failed",S))}}finally{t.removeEventListener("abort",m),d()}},c.INITIAL_POLL_DELAY_MS)})}async pollOrderStatus(e,n,t,r){let i=Date.now()+c.POLLING_DURATION_MS;for(;Date.now()<i;){if(r.aborted)throw new Error("Aborted");try{let{data:o}=await this.api.getPaymentStatus({businessId:Number(t),orderId:n,provider:this.paymentProvider,referenceId:e});if(r.aborted)throw new Error("Aborted");if(o.status!==C.Pending)return o}catch(o){if(o instanceof Error&&o.message==="Aborted")throw o}await new Promise(o=>{let a=()=>{clearTimeout(u),o(void 0)};r.addEventListener("abort",a,{once:!0});let u=setTimeout(()=>{r.removeEventListener("abort",a),o(void 0)},c.POLLING_INTERVAL_MS)})}throw new Error("Payment verification timed out.")}async recoverAfterPollingTimeout(e,n){return await this.cancelSessionWithTimeout(n),await this.verifyFinalStatusWithRetry(e,n)}async cancelSessionWithTimeout(e){let n;try{await Promise.race([this.cancelSession(e),new Promise((t,r)=>{n=setTimeout(()=>{r(new Error("Viva timeout cancellation timed out"))},c.TIMEOUT_CANCEL_TIMEOUT_MS)})])}catch{}finally{n&&clearTimeout(n)}}async cancelSession(e){return await this.api.cancelVivaTransactionV2({cashRegisterId:this.config.storeId,sessionId:e}),this.currentSessionId===e&&(this.currentSessionId=null),!0}async verifyFinalStatusWithRetry(e,n){let t;for(let s=1;s<=c.VERIFY_MAX_RETRIES;s++)try{let i=await Promise.race([this.verifyFinalStatus(e,n),new Promise((o,a)=>setTimeout(()=>a(new Error("Verify timed out")),c.VERIFY_TIMEOUT_MS))]);if(i.status==="PENDING"){t=new Error("Verify returned pending status"),s<c.VERIFY_MAX_RETRIES&&await new Promise(o=>setTimeout(o,c.VERIFY_RETRY_DELAY_MS));continue}return i}catch(i){t=i,s<c.VERIFY_MAX_RETRIES&&await new Promise(o=>setTimeout(o,c.VERIFY_RETRY_DELAY_MS))}let r=t instanceof Error?t.message:"Verify retries exhausted";throw new l(U.PaymentTimeout,r)}handleSuccess(e){let n=e.status===C.Success,t={success:n,status:n?"SUCCESS":"FAILED",orderId:e.orderId,errorCode:e.error?.code||(n?"":U.SystemUnknown),errorMessage:e.error?.message||(n?"":"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 n=this.currentSessionId;return this.currentSessionId=null,await this.api.cancelVivaTransactionV2({cashRegisterId:this.config.storeId,sessionId:n}),this.abortController?.abort(),!0}catch(n){throw this.currentSessionId=null,new l("NETWORK_ERROR","Failed to cancel Viva transaction",n)}}async verifyFinalStatus(e,n){try{let{data:t}=await this.api.getPaymentStatus({businessId:Number(this.config.storeId),orderId:e.orderRef,provider:this.paymentProvider,referenceId:n}),r=t.status===C.Success,s=t.status===C.Pending,i={success:r,status:r?"SUCCESS":s?"PENDING":"FAILED",orderId:t.orderId,errorCode:t.error?.code||(r||s?"":U.SystemUnknown),errorMessage:t.error?.message||(r||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,n){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:r}=await this.api.refundSingleVivaTransaction(t),s=r.success;return{success:s,status:s?"SUCCESS":"FAILED",orderId:e.orderRef,transactionId:r.sessionId}}catch(t){throw new l("NETWORK_ERROR","Failed to refund Viva transaction",t)}}abort(){this.abortController?.abort()}};import{PaymentApi as Pe,PaymentEventType as j,PaymentFailureCode as Se,PaymentProviderEnum as Te,SimplePaymentStatus as F,WorldlineApi as Ce}from"@munchi_oy/core";import{isAxiosError as Ee}from"axios";var M=class{constructor(e,n,t){this.messaging=n;this.config=t;this.paymentApi=new Pe(void 0,"",e),this.worldlineApi=new Ce(void 0,"",e)}paymentApi;worldlineApi;abortController=null;currentOperationId=null;paymentProvider=Te.Worldline;async processPayment(e,n){this.abortController=new AbortController,n("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 r=await this.worldlineApi.createPayment(t),s=this.extractOperationId(r.data);if(this.currentOperationId=s,this.abortController.signal.aborted)throw new Error("Aborted");n("REQUIRES_INPUT",{sessionId:s});let i=await this.waitForPaymentCompletion(s,e.orderRef,j.StatusChanged,this.abortController.signal);return this.currentOperationId=null,i}catch(r){throw this.currentOperationId=null,r instanceof l?r:this.mapWorldlineRequestError(r,"Failed to create Worldline payment")}}async cancelTransaction(e){if(!this.currentOperationId)return!1;let n={businessId:Number(this.config.storeId),targetOperationId:this.currentOperationId};try{return await this.worldlineApi.cancelPayment(n),!0}catch(t){throw this.mapWorldlineRequestError(t,"Failed to cancel Worldline transaction")}}async refundTransaction(e,n){this.abortController=new AbortController,n("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 r=await this.worldlineApi.createRefund(t),s=this.extractOperationId(r.data);if(this.currentOperationId=s,this.abortController.signal.aborted)throw new Error("Aborted");n("REQUIRES_INPUT",{sessionId:s});let i=await this.waitForPaymentCompletion(s,e.orderRef,j.RefundStatusChanged,this.abortController.signal);return this.currentOperationId=null,i}catch(r){throw this.currentOperationId=null,r instanceof l?r:this.mapWorldlineRequestError(r,"Failed to refund Worldline transaction")}}async verifyFinalStatus(e,n){try{let{data:t}=await this.paymentApi.getPaymentStatus({businessId:Number(this.config.storeId),orderId:e.orderRef,provider:this.paymentProvider,referenceId:n});return this.handlePaymentStatus(t)}catch(t){throw this.mapWorldlineRequestError(t,"Failed to verify final Worldline status")}}abort(){this.abortController?.abort()}async waitForPaymentCompletion(e,n,t,r){let s=`worldline.requests.${e}`;return new Promise((i,o)=>{let a=!1,u=()=>{a=!0,typeof m=="function"&&m(),clearTimeout(f)},d=()=>{u(),o(new l("CANCELLED","Transaction cancelled"))};r.addEventListener("abort",d);let m=this.messaging.subscribe(s,t,p=>{a||p.status===F.Pending||(u(),r.removeEventListener("abort",d),i(this.handlePaymentStatus(p)))}),f=setTimeout(async()=>{if(!(a||r.aborted))try{let p=await this.pollOrderStatus(e,n,this.config.storeId,r);i(this.handlePaymentStatus(p))}catch(p){o(new l("TIMEOUT","Payment timed out and polling failed",p))}finally{r.removeEventListener("abort",d),u()}},1e4)})}async pollOrderStatus(e,n,t,r){let o=Date.now()+12e4;for(;Date.now()<o;){if(r.aborted)throw new Error("Aborted");try{let{data:a}=await this.paymentApi.getPaymentStatus({businessId:Number(t),orderId:n,provider:this.paymentProvider,referenceId:e});if(r.aborted)throw new Error("Aborted");if(a.status!==F.Pending)return a}catch(a){if(a instanceof Error&&a.message==="Aborted")throw a}await new Promise(a=>{let u=()=>{clearTimeout(d),a(void 0)};r.addEventListener("abort",u,{once:!0});let d=setTimeout(()=>{r.removeEventListener("abort",u),a(void 0)},2e3)})}throw new Error("Payment verification timed out.")}handlePaymentStatus(e){let n=e.status===F.Success,t=e.status===F.Pending,r={success:n,status:n?"SUCCESS":t?"PENDING":"FAILED",orderId:e.orderId,errorCode:e.error?.code||(n||t?"":Se.SystemUnknown),errorMessage:e.error?.message||(n||t?"":"Transaction failed without error details")};return e.transactionId&&(r.transactionId=e.transactionId),e.error?.referenceError&&(r.errorReference=e.error.referenceError),e.transaction&&(r.transaction=e.transaction),r}extractOperationId(e){let n=typeof e=="object"&&e!==null&&"operationId"in e&&typeof e.operationId=="string"?e.operationId:null;if(!n)throw new Error("operationId is missing from response.");return n}mapWorldlineRequestError(e,n){if(Ee(e)){if(e.response?.status===400||e.response?.status===409)return new l("TERMINAL_BUSY",n,e);if(e.response?.status===404)return new l("TERMINAL_OFFLINE",n,e)}return new l("NETWORK_ERROR",n,e)}};var V=class c{strategy;axios;messaging;timeoutMs;logger;_currentState="IDLE";_listeners=[];_cancellationIntent=!1;_currentSessionId;_autoResetTimer;autoResetOptions;appToAppConfig;paymentSessionConfig;manualStrategy;static TERMINAL_STATES=["SUCCESS","FAILED","INTERNAL_ERROR"];static RESTING_STATES=["IDLE",...c.TERMINAL_STATES];constructor(e,n,t,r={},s){this.axios=e,this.messaging=n,this.logger=r.logger,this.timeoutMs=r.timeoutMs||3e4,this.autoResetOptions=r.autoResetOnPaymentComplete,this.appToAppConfig=r.appToApp,this.paymentSessionConfig=r.paymentSession,this.manualStrategy=new A(e,t),this.strategy=s??this.resolveStrategy(t)}get version(){return W}get currentState(){return this._currentState}generateErrorResult(e,n,t){return{success:!1,status:"ERROR",errorCode:this.normalizeErrorCode(n),errorMessage:t,orderId:e}}normalizeErrorCode(e){return e?e.includes(".")?e:{CANCELLED:y.PaymentCancelledByUser,DECLINED:y.PaymentDeclined,TERMINAL_BUSY:y.TerminalBusy,TERMINAL_OFFLINE:y.TerminalOffline,TIMEOUT:y.TerminalTimeout,NETWORK_ERROR:y.SystemProviderError,STRATEGY_ERROR:y.SystemProviderError,MISSING_CONFIG:y.SystemUnknown,INVALID_AMOUNT:y.SystemUnknown,UNKNOWN:y.SystemUnknown}[e]??y.SystemUnknown:y.SystemUnknown}subscribe=e=>(this._listeners.push(e),e(this._currentState),()=>{this._listeners=this._listeners.filter(n=>n!==e)});transitionTo(e){if(this._currentState===e)return;if(e==="IDLE"){this.cancelAutoReset(),this._currentState=e,this._listeners.forEach(t=>t(e));return}if(c.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(r=>r(this._currentState))),new l("UNKNOWN",t)}this._currentState=e,c.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 k.Nets:return new w(this.axios,this.messaging,e);case k.Worldline:return new M(this.axios,this.messaging,e);case k.Viva:return this.appToAppConfig?.enabled?new _(this.axios,this.messaging,e,this.appToAppConfig):this.paymentSessionConfig?.enabled?new x(this.axios,this.messaging,e):new E(this.axios,this.messaging,e);default:return new E(this.axios,this.messaging,e)}}initiateTransaction=async(e,n)=>{let t=n??{},r=e.orderRef;if(!c.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,f)=>{f?.sessionId&&(this._currentSessionId=f.sessionId),m!=="FAILED"&&(this.transitionTo(m),this.fireStateCallback(m,t,r))},a=this.strategy.processPayment(e,o),d=(this.strategy.getExecutionMode?.()??"managed")==="callback_driven"?await a:await Promise.race([a,new Promise((m,f)=>{setTimeout(()=>{f(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,n,t={}){let r=n instanceof l&&(n.code==="TIMEOUT"||n.code===y.PaymentTimeout);if(!this._cancellationIntent&&!r&&(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=r&&i.status==="PENDING"?this.buildErrorResultFromException(e.orderRef,n):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,n);return this.transitionTo("FAILED"),this.safeFireCallback(()=>t.onError?.(s)),s}buildErrorResultFromException(e,n){return n instanceof l?this.generateErrorResult(e,n.code,n.message):this.generateErrorResult(e,"UNKNOWN",n instanceof Error?n.message:"Unknown fatal error")}fireStateCallback(e,n,t){let r={orderRef:t,refPaymentId:this._currentSessionId};switch(e){case"CONNECTING":this.safeFireCallback(()=>n.onConnecting?.(r));break;case"REQUIRES_INPUT":this.safeFireCallback(()=>n.onRequiresInput?.(r));break;case"PROCESSING":this.safeFireCallback(()=>n.onProcessing?.(r));break}}safeFireCallback(e){try{e()}catch(n){this.logger?.warn("Callback execution failed",{error:n})}}cancel=async()=>{if(this.logger?.info("Attempting cancellation"),c.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(n=>this.transitionTo(n))}catch(e){return this.logger?.error("Cancellation command failed",e),!1}};reset=()=>{c.TERMINAL_STATES.includes(this._currentState)&&(this._currentSessionId=void 0,this._cancellationIntent=!1,this.transitionTo("IDLE"))};refund=async(e,n)=>{let t=n??{};if(this.logger?.info("Initiating refund",{orderRef:e.orderRef}),this._currentSessionId=void 0,this._cancellationIntent=!1,!c.RESTING_STATES.includes(this._currentState))return this.generateErrorResult(e.orderRef,"UNKNOWN","A transaction is already in progress");this.transitionTo("IDLE");try{let s=(o,a)=>{a?.sessionId&&(this._currentSessionId=a.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,n)=>{let t=n??{};if(this.logger?.info("Reverting payment",{orderRef:e.orderRef}),this._currentSessionId=e.originalTransactionId,this._cancellationIntent=!1,!c.RESTING_STATES.includes(this._currentState))return this.generateErrorResult(e.orderRef,"UNKNOWN","A transaction is already in progress");let r=this.strategy.revertTransaction?.bind(this.strategy);if(!r)return this.generateErrorResult(e.orderRef,"STRATEGY_ERROR","Revert is not supported by the active payment strategy");this.transitionTo("CONNECTING");try{let s=await r(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)}};recordManualPayment=async(e,n)=>{let t=n??{};if(this.logger?.info("Recording manual payment",{orderRef:e.orderRef}),this._currentSessionId=void 0,this._cancellationIntent=!1,!c.RESTING_STATES.includes(this._currentState))return this.generateErrorResult(e.orderRef,"UNKNOWN","A transaction is already in progress");this.transitionTo("CONNECTING"),this.safeFireCallback(()=>t.onConnecting?.({orderRef:e.orderRef,refPaymentId:void 0}));try{let r=await this.manualStrategy.recordPayment(e);return this.settleSingleShot(r,e.orderRef,t),r}catch(r){return this.logger?.error("Manual payment failed",r),this.failSingleShot(e.orderRef,r,"Manual payment failed",t)}};voidManualPayment=async(e,n)=>{let t=n??{};if(this.logger?.info("Voiding manual payment",{orderRef:e.orderRef}),this._currentSessionId=e.sessionId,this._cancellationIntent=!1,!c.RESTING_STATES.includes(this._currentState))return this.generateErrorResult(e.orderRef,"UNKNOWN","A transaction is already in progress");this.transitionTo("CONNECTING");try{let r=await this.manualStrategy.voidPayment(e);return this.settleSingleShot(r,e.orderRef,t),r}catch(r){return this.logger?.error("Manual void failed",r),this.failSingleShot(e.orderRef,r,"Void failed",t)}};settleSingleShot(e,n,t){e.success?(this.transitionTo("SUCCESS"),this.safeFireCallback(()=>t.onSuccess?.(e))):e.status==="CANCELLED"?(this.transitionTo("FAILED"),this.safeFireCallback(()=>t.onCancelled?.({orderRef:n,refPaymentId:this._currentSessionId}))):(this.transitionTo("FAILED"),this.safeFireCallback(()=>t.onError?.(e)))}failSingleShot(e,n,t,r){let s=this.generateErrorResult(e,"NETWORK_ERROR",n instanceof Error?n.message:t);return this.transitionTo("FAILED"),this.safeFireCallback(()=>r.onError?.(s)),s}};var be=(r=>(r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r.OFFLINE="OFFLINE",r.DISCONNECTED="DISCONNECTED",r))(be||{});export{be as AppReaderStatus,V as MunchiPaymentSDK,g as PaymentInteractionState,R as SdkPaymentStatus};
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,6 +1,6 @@
1
1
  import type { AxiosInstance } from "axios";
2
2
  import type { IPaymentStrategy } from "./strategies/IPaymentStrategy";
3
- import { type IMessagingAdapter, type IMunchiPaymentSDK, type ManualPaymentRequest, PaymentInteractionState, type PaymentResult, type PaymentTerminalConfig, type RefundRequest, type RevertRequest, type PaymentRequest as SdkPaymentRequest, type TransactionOptions, type VoidRequest } from "./types/payment";
3
+ import { type IMessagingAdapter, type IMunchiPaymentSDK, PaymentInteractionState, type PaymentResult, type PaymentTerminalConfig, type RefundRequest, type RevertRequest, type PaymentRequest as SdkPaymentRequest, type TransactionOptions } from "./types/payment";
4
4
  import type { SDKOptions } from "./types/sdk";
5
5
  type StateListener = (state: PaymentInteractionState) => void;
6
6
  export declare class MunchiPaymentSDK implements IMunchiPaymentSDK {
@@ -17,7 +17,6 @@ export declare class MunchiPaymentSDK implements IMunchiPaymentSDK {
17
17
  private autoResetOptions;
18
18
  private appToAppConfig;
19
19
  private paymentSessionConfig;
20
- private manualStrategy;
21
20
  private static readonly TERMINAL_STATES;
22
21
  private static readonly RESTING_STATES;
23
22
  constructor(axios: AxiosInstance, messaging: IMessagingAdapter, config: PaymentTerminalConfig, options?: SDKOptions, strategy?: IPaymentStrategy);
@@ -41,8 +40,6 @@ export declare class MunchiPaymentSDK implements IMunchiPaymentSDK {
41
40
  reset: () => void;
42
41
  refund: (params: RefundRequest, options?: TransactionOptions) => Promise<PaymentResult>;
43
42
  revert: (params: RevertRequest, options?: TransactionOptions) => Promise<PaymentResult>;
44
- recordManualPayment: (params: ManualPaymentRequest, options?: TransactionOptions) => Promise<PaymentResult>;
45
- voidManualPayment: (params: VoidRequest, options?: TransactionOptions) => Promise<PaymentResult>;
46
43
  private settleSingleShot;
47
44
  private failSingleShot;
48
45
  }
@@ -1 +1 @@
1
- {"version":3,"file":"MunchiPaymentSDK.d.ts","sourceRoot":"","sources":["../../src/MunchiPaymentSDK.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,OAAO,CAAC;AAG3C,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,+BAA+B,CAAC;AAQtE,OAAO,EACL,KAAK,iBAAiB,EACtB,KAAK,iBAAiB,EACtB,KAAK,oBAAoB,EACzB,uBAAuB,EACvB,KAAK,aAAa,EAClB,KAAK,qBAAqB,EAC1B,KAAK,aAAa,EAClB,KAAK,aAAa,EAClB,KAAK,cAAc,IAAI,iBAAiB,EAExC,KAAK,kBAAkB,EACvB,KAAK,WAAW,EACjB,MAAM,iBAAiB,CAAC;AACzB,OAAO,KAAK,EAIV,UAAU,EACX,MAAM,aAAa,CAAC;AAErB,KAAK,aAAa,GAAG,CAAC,KAAK,EAAE,uBAAuB,KAAK,IAAI,CAAC;AAE9D,qBAAa,gBAAiB,YAAW,iBAAiB;IACxD,OAAO,CAAC,QAAQ,CAAm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AkB,KAC3B,OAAO,CAAC,aAAa,CAAC,CAqIvB;IAEK,MAAM,GACX,QAAQ,aAAa,EACrB,UAAU,kBAAkB,KAC3B,OAAO,CAAC,aAAa,CAAC,CAwCvB;IAEF,OAAO,CAAC,gBAAgB;IAsBxB,OAAO,CAAC,cAAc;CAevB"}
@@ -5,8 +5,7 @@ import { type IPaymentStrategy, StrategyExecutionMode } from "./IPaymentStrategy
5
5
  export declare class VivaAppToAppStrategy implements IPaymentStrategy {
6
6
  private config;
7
7
  private appToAppConfig;
8
- private api;
9
- private paymentApi;
8
+ private sessionApi;
10
9
  private abortController;
11
10
  private currentClientTransactionId;
12
11
  private currentIsvClientTransactionId;
@@ -14,7 +13,6 @@ export declare class VivaAppToAppStrategy implements IPaymentStrategy {
14
13
  private currentOrderRef;
15
14
  private currentSourceTerminalId;
16
15
  private latestResult;
17
- private paymentApiWithReference;
18
16
  private wasCancelled;
19
17
  constructor(axios: AxiosInstance, _messaging: unknown, config: PaymentTerminalConfig, appToAppConfig: AppToAppConfig);
20
18
  getExecutionMode(): StrategyExecutionMode;
@@ -22,7 +20,7 @@ export declare class VivaAppToAppStrategy implements IPaymentStrategy {
22
20
  sessionId?: string;
23
21
  }) => void): Promise<PaymentResult>;
24
22
  cancelTransaction(_onStateChange: (state: PaymentInteractionState) => void): Promise<boolean>;
25
- refundTransaction(request: RefundRequest, onStateChange: (state: PaymentInteractionState, detail?: {
23
+ refundTransaction(request: RefundRequest, _onStateChange: (state: PaymentInteractionState, detail?: {
26
24
  sessionId?: string;
27
25
  }) => void): Promise<PaymentResult>;
28
26
  verifyFinalStatus(_request: PaymentRequest, sessionId: string): Promise<PaymentResult>;
@@ -30,10 +28,6 @@ export declare class VivaAppToAppStrategy implements IPaymentStrategy {
30
28
  private runAction;
31
29
  private buildCreatePaymentPayload;
32
30
  private buildLaunchParams;
33
- private buildRefundLaunchParams;
34
- private fetchPaymentReference;
35
- private extractPaymentReferenceContext;
36
- private readReferenceValue;
37
31
  private buildActionUrl;
38
32
  private parseCallbackUrl;
39
33
  private matchesCallbackBase;
@@ -1 +1 @@
1
- {"version":3,"file":"VivaAppToAppStrategy.d.ts","sourceRoot":"","sources":["../../../src/strategies/VivaAppToAppStrategy.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,OAAO,CAAC;AAG3C,OAAO,EACL,uBAAuB,EACvB,KAAK,cAAc,EACnB,KAAK,aAAa,EAClB,KAAK,qBAAqB,EAC1B,KAAK,aAAa,EAGnB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAEnD,OAAO,EACL,KAAK,gBAAgB,EACrB,qBAAqB,EACtB,MAAM,oBAAoB,CAAC;AAqC5B,qBAAa,oBAAqB,YAAW,gBAAgB;IAoBzD,OAAO,CAAC,MAAM;IACd,OAAO,CAAC,cAAc;IApBxB,OAAO,CAAC,GAAG,CAAU;IACrB,OAAO,CAAC,UAAU,CAAa;IAC/B,OAAO,CAAC,eAAe,CAAgC;IACvD,OAAO,CAAC,0BAA0B,CAAuB;IACzD,OAAO,CAAC,6BAA6B,CAAuB;IAC5D,OAAO,CAAC,eAAe,CAA2C;IAClE,OAAO,CAAC,eAAe,CAAuB;IAC9C,OAAO,CAAC,uBAAuB,CAAuB;IACtD,OAAO,CAAC,YAAY,CAA8B;IAClD,OAAO,CAAC,uBAAuB,CAI7B;IACF,OAAO,CAAC,YAAY,CAAS;gBAG3B,KAAK,EAAE,aAAa,EACpB,UAAU,EAAE,OAAO,EACX,MAAM,EAAE,qBAAqB,EAC7B,cAAc,EAAE,cAAc;IAWxC,gBAAgB;IAIV,cAAc,CAClB,OAAO,EAAE,cAAc,EACvB,aAAa,EAAE,CACb,KAAK,EAAE,uBAAuB,EAC9B,MAAM,CAAC,EAAE;QAAE,SAAS,CAAC,EAAE,MAAM,CAAA;KAAE,KAC5B,IAAI,GACR,OAAO,CAAC,aAAa,CAAC;IA8BnB,iBAA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AI,IAAI;YAIC,SAAS;IAqGvB,OAAO,CAAC,yBAAyB;IAyBjC,OAAO,CAAC,iBAAiB;IAqBzB,OAAO,CAAC,cAAc;IAiBtB,OAAO,CAAC,gBAAgB;IAyDxB,OAAO,CAAC,mBAAmB;IAkB3B,OAAO,CAAC,yBAAyB;IAajC,OAAO,CAAC,yBAAyB;IAwBjC,OAAO,CAAC,kBAAkB;IAoC1B,OAAO,CAAC,oBAAoB;IAc5B,OAAO,CAAC,0BAA0B;IASlC,OAAO,CAAC,mBAAmB;IAsB3B,OAAO,CAAC,gCAAgC;IAWxC,OAAO,CAAC,wBAAwB;IAqChC,OAAO,CAAC,wBAAwB;IAyBhC,OAAO,CAAC,SAAS;YA2CH,wBAAwB;CA6DvC"}
@@ -67,23 +67,6 @@ export interface RefundRequest {
67
67
  businessId: number;
68
68
  options?: VivaRefundOptions | NetsRefundOptions | WorldlineRefundOptions;
69
69
  }
70
- export interface ManualPaymentRequest {
71
- orderRef: string;
72
- amountCents: number;
73
- paymethod: string;
74
- tipAmount?: number;
75
- splitContext?: SplitContextDto;
76
- /**
77
- * Arbitrary client metadata persisted on the session (e.g. voucher code,
78
- * gift card id, employee id, external reference, notes). Surfaced to
79
- * reconciliation when building the order paymentEvent.
80
- */
81
- metadata?: Record<string, unknown>;
82
- }
83
- export interface VoidRequest {
84
- orderRef: string;
85
- sessionId: string;
86
- }
87
70
  export interface RevertRequest {
88
71
  orderRef: string;
89
72
  originalTransactionId: string;
@@ -140,8 +123,6 @@ export interface IMunchiPaymentSDK {
140
123
  cancel(): Promise<boolean>;
141
124
  refund(params: RefundRequest, options?: TransactionOptions): Promise<PaymentResult>;
142
125
  revert(params: RevertRequest, options?: TransactionOptions): Promise<PaymentResult>;
143
- recordManualPayment(params: ManualPaymentRequest, options?: TransactionOptions): Promise<PaymentResult>;
144
- voidManualPayment(params: VoidRequest, options?: TransactionOptions): Promise<PaymentResult>;
145
126
  reset(): void;
146
127
  }
147
128
  //# sourceMappingURL=payment.d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  "name": "@munchi_oy/payments",
3
- "version": "1.10.1",
3
+ "version": "1.10.4",
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.41"
35
+ "@munchi_oy/core": "1.9.46"
36
36
  },
37
37
  "scripts": {
38
38
  "test": "jest",
@@ -4,7 +4,6 @@ import { version } from "../package.json";
4
4
  import { PaymentErrorCode, PaymentSDKError } from "./error";
5
5
  import type { IPaymentStrategy } from "./strategies/IPaymentStrategy";
6
6
  import { StrategyExecutionMode } from "./strategies/IPaymentStrategy";
7
- import { ManualSessionStrategy } from "./strategies/ManualSessionStrategy";
8
7
  import { NetsStrategy } from "./strategies/NetsStrategy";
9
8
  import { VivaAppToAppStrategy } from "./strategies/VivaAppToAppStrategy";
10
9
  import { VivaSessionStrategy } from "./strategies/VivaSessionStrategy";
@@ -13,7 +12,6 @@ import { WorldlineStrategy } from "./strategies/WorldlineStrategy";
13
12
  import {
14
13
  type IMessagingAdapter,
15
14
  type IMunchiPaymentSDK,
16
- type ManualPaymentRequest,
17
15
  PaymentInteractionState,
18
16
  type PaymentResult,
19
17
  type PaymentTerminalConfig,
@@ -22,7 +20,6 @@ import {
22
20
  type PaymentRequest as SdkPaymentRequest,
23
21
  SdkPaymentStatus,
24
22
  type TransactionOptions,
25
- type VoidRequest,
26
23
  } from "./types/payment";
27
24
  import type {
28
25
  AppToAppConfig,
@@ -47,7 +44,6 @@ export class MunchiPaymentSDK implements IMunchiPaymentSDK {
47
44
  private autoResetOptions: SDKOptions["autoResetOnPaymentComplete"];
48
45
  private appToAppConfig: AppToAppConfig | undefined;
49
46
  private paymentSessionConfig: PaymentSessionConfig | undefined;
50
- private manualStrategy: ManualSessionStrategy;
51
47
 
52
48
  private static readonly TERMINAL_STATES = [
53
49
  PaymentInteractionState.SUCCESS,
@@ -74,7 +70,6 @@ export class MunchiPaymentSDK implements IMunchiPaymentSDK {
74
70
  this.autoResetOptions = options.autoResetOnPaymentComplete;
75
71
  this.appToAppConfig = options.appToApp;
76
72
  this.paymentSessionConfig = options.paymentSession;
77
- this.manualStrategy = new ManualSessionStrategy(axios, config);
78
73
  this.strategy = strategy ?? this.resolveStrategy(config);
79
74
  }
80
75
 
@@ -708,82 +703,6 @@ export class MunchiPaymentSDK implements IMunchiPaymentSDK {
708
703
  }
709
704
  };
710
705
 
711
- public recordManualPayment = async (
712
- params: ManualPaymentRequest,
713
- options?: TransactionOptions,
714
- ): Promise<PaymentResult> => {
715
- const callbacks = options ?? {};
716
- this.logger?.info("Recording manual payment", {
717
- orderRef: params.orderRef,
718
- });
719
- this._currentSessionId = undefined;
720
- this._cancellationIntent = false;
721
-
722
- if (!MunchiPaymentSDK.RESTING_STATES.includes(this._currentState)) {
723
- return this.generateErrorResult(
724
- params.orderRef,
725
- PaymentErrorCode.UNKNOWN,
726
- "A transaction is already in progress",
727
- );
728
- }
729
-
730
- this.transitionTo(PaymentInteractionState.CONNECTING);
731
- this.safeFireCallback(() =>
732
- callbacks.onConnecting?.({
733
- orderRef: params.orderRef,
734
- refPaymentId: undefined,
735
- }),
736
- );
737
-
738
- try {
739
- const result = await this.manualStrategy.recordPayment(params);
740
- this.settleSingleShot(result, params.orderRef, callbacks);
741
- return result;
742
- } catch (error) {
743
- this.logger?.error("Manual payment failed", error);
744
- return this.failSingleShot(
745
- params.orderRef,
746
- error,
747
- "Manual payment failed",
748
- callbacks,
749
- );
750
- }
751
- };
752
-
753
- public voidManualPayment = async (
754
- params: VoidRequest,
755
- options?: TransactionOptions,
756
- ): Promise<PaymentResult> => {
757
- const callbacks = options ?? {};
758
- this.logger?.info("Voiding manual payment", { orderRef: params.orderRef });
759
- this._currentSessionId = params.sessionId;
760
- this._cancellationIntent = false;
761
-
762
- if (!MunchiPaymentSDK.RESTING_STATES.includes(this._currentState)) {
763
- return this.generateErrorResult(
764
- params.orderRef,
765
- PaymentErrorCode.UNKNOWN,
766
- "A transaction is already in progress",
767
- );
768
- }
769
-
770
- this.transitionTo(PaymentInteractionState.CONNECTING);
771
-
772
- try {
773
- const result = await this.manualStrategy.voidPayment(params);
774
- this.settleSingleShot(result, params.orderRef, callbacks);
775
- return result;
776
- } catch (error) {
777
- this.logger?.error("Manual void failed", error);
778
- return this.failSingleShot(
779
- params.orderRef,
780
- error,
781
- "Void failed",
782
- callbacks,
783
- );
784
- }
785
- };
786
-
787
706
  private settleSingleShot(
788
707
  result: PaymentResult,
789
708
  orderRef: string,
@@ -1,15 +1,15 @@
1
1
  import {
2
- type CreateTerminalPaymentDto,
3
2
  FeeType,
4
- type GetPaymentReferenceDto,
5
- PaymentApi,
3
+ type InitiateVivaA2aSessionDto,
4
+ type InitiateVivaA2aSessionResponseDto,
6
5
  PaymentFailureCode,
7
6
  PaymentMethod,
8
7
  PaymentProvider,
8
+ PaymentSessionApi,
9
+ PaymentSessionStatus,
10
+ type ReverseSessionDto,
9
11
  type TransactionDto,
10
12
  type TransactionDtoFees,
11
- VivaApi,
12
- type VivaAppToAppInitResponseDto,
13
13
  } from "@munchi_oy/core";
14
14
  import type { AxiosInstance } from "axios";
15
15
 
@@ -32,7 +32,6 @@ import {
32
32
 
33
33
  const VIVA_APP_TO_APP_BASE_URL = "vivapayclient://pay/v1";
34
34
  const VIVA_ACTION_ABORT = "abort";
35
- const VIVA_ACTION_CANCEL = "cancel";
36
35
  const VIVA_ACTION_SALE = "sale";
37
36
  const VIVA_ACTION_TRANSACTION_DETAILS = "transactionDetails";
38
37
  const VIVA_TRANSACTION_DETAILS_TIMEOUT_MS = 4000;
@@ -48,26 +47,9 @@ const CREDIT_KEYWORDS = ["CREDIT", "PREPAID", "CORPORATE"];
48
47
 
49
48
  type VivaLaunchParams = Record<string, boolean | number | string | undefined>;
50
49
  type VivaCallbackParams = Record<string, string>;
51
- type PaymentReferenceLookupRequest = {
52
- orderId: string;
53
- provider: PaymentProvider;
54
- transactionId: string;
55
- };
56
- type PaymentReferenceResponse = {
57
- originalTransactionId: string;
58
- references: object | null;
59
- };
60
- type PaymentReferenceContext = {
61
- originalTransactionId?: string;
62
- receiptNumber?: string;
63
- referenceCode?: string;
64
- shortReferenceCode?: string;
65
- terminalId?: string;
66
- };
67
50
 
68
51
  export class VivaAppToAppStrategy implements IPaymentStrategy {
69
- private api: VivaApi;
70
- private paymentApi: PaymentApi;
52
+ private sessionApi: PaymentSessionApi;
71
53
  private abortController: AbortController | null = null;
72
54
  private currentClientTransactionId: string | null = null;
73
55
  private currentIsvClientTransactionId: string | null = null;
@@ -75,11 +57,6 @@ export class VivaAppToAppStrategy implements IPaymentStrategy {
75
57
  private currentOrderRef: string | null = null;
76
58
  private currentSourceTerminalId: string | null = null;
77
59
  private latestResult: PaymentResult | null = null;
78
- private paymentApiWithReference: PaymentApi & {
79
- getPaymentReference: (
80
- request: PaymentReferenceLookupRequest,
81
- ) => Promise<{ data: PaymentReferenceResponse }>;
82
- };
83
60
  private wasCancelled = false;
84
61
 
85
62
  constructor(
@@ -88,13 +65,7 @@ export class VivaAppToAppStrategy implements IPaymentStrategy {
88
65
  private config: PaymentTerminalConfig,
89
66
  private appToAppConfig: AppToAppConfig,
90
67
  ) {
91
- this.api = new VivaApi(undefined, "", axios);
92
- this.paymentApi = new PaymentApi(undefined, "", axios);
93
- this.paymentApiWithReference = this.paymentApi as PaymentApi & {
94
- getPaymentReference: (
95
- request: PaymentReferenceLookupRequest,
96
- ) => Promise<{ data: PaymentReferenceResponse }>;
97
- };
68
+ this.sessionApi = new PaymentSessionApi(undefined, "", axios);
98
69
  }
99
70
 
100
71
  getExecutionMode() {
@@ -118,7 +89,7 @@ export class VivaAppToAppStrategy implements IPaymentStrategy {
118
89
  onStateChange(PaymentInteractionState.CONNECTING);
119
90
 
120
91
  try {
121
- const { data } = await this.api.createVivaAppToAppPayment(
92
+ const { data } = await this.sessionApi.initiateVivaA2aSession(
122
93
  this.buildCreatePaymentPayload(request),
123
94
  );
124
95
 
@@ -173,21 +144,47 @@ export class VivaAppToAppStrategy implements IPaymentStrategy {
173
144
 
174
145
  async refundTransaction(
175
146
  request: RefundRequest,
176
- onStateChange: (
147
+ _onStateChange: (
177
148
  state: PaymentInteractionState,
178
149
  detail?: { sessionId?: string },
179
150
  ) => void,
180
151
  ): Promise<PaymentResult> {
181
- onStateChange(PaymentInteractionState.CONNECTING);
152
+ try {
153
+ const payload: ReverseSessionDto = {
154
+ sessionId: request.originalTransactionId,
155
+ amount: request.amountCents,
156
+ };
182
157
 
183
- const reference = await this.fetchPaymentReference(request);
184
- const launchParams = this.buildRefundLaunchParams(request, reference);
185
- return this.runAction(
186
- VIVA_ACTION_CANCEL,
187
- launchParams,
188
- request,
189
- onStateChange,
190
- );
158
+ const { data } = await this.sessionApi.refundVivaSession(payload);
159
+
160
+ const isRefunded =
161
+ data.status === PaymentSessionStatus.Refunded ||
162
+ data.status === PaymentSessionStatus.Refunding;
163
+
164
+ const result: PaymentResult = {
165
+ success: isRefunded,
166
+ status: isRefunded ? SdkPaymentStatus.SUCCESS : SdkPaymentStatus.FAILED,
167
+ orderId: request.orderRef,
168
+ transactionId: data.providerTransactionId ?? data.sessionId,
169
+ };
170
+
171
+ if (!isRefunded) {
172
+ if (data.errorCode) {
173
+ result.errorCode = data.errorCode;
174
+ }
175
+ if (data.errorMessage) {
176
+ result.errorMessage = data.errorMessage;
177
+ }
178
+ }
179
+
180
+ return result;
181
+ } catch (error) {
182
+ throw new PaymentSDKError(
183
+ PaymentErrorCode.NETWORK_ERROR,
184
+ "Failed to refund Viva transaction",
185
+ error,
186
+ );
187
+ }
191
188
  }
192
189
 
193
190
  async verifyFinalStatus(
@@ -324,9 +321,9 @@ export class VivaAppToAppStrategy implements IPaymentStrategy {
324
321
 
325
322
  private buildCreatePaymentPayload(
326
323
  request: PaymentRequest,
327
- ): CreateTerminalPaymentDto {
324
+ ): InitiateVivaA2aSessionDto {
328
325
  const vivaOptions = (request.options ?? {}) as VivaOptions;
329
- const payload: CreateTerminalPaymentDto = {
326
+ const payload: InitiateVivaA2aSessionDto = {
330
327
  amount: request.amountCents,
331
328
  referenceId: request.orderRef,
332
329
  businessId: Number(this.config.storeId),
@@ -340,166 +337,34 @@ export class VivaAppToAppStrategy implements IPaymentStrategy {
340
337
  payload.tipAmount = vivaOptions.tipAmount;
341
338
  }
342
339
 
340
+ if (request.splitContext !== undefined) {
341
+ payload.splitContext = request.splitContext;
342
+ }
343
+
343
344
  return payload;
344
345
  }
345
346
 
346
347
  private buildLaunchParams(
347
- payload: VivaLaunchParams | VivaAppToAppInitResponseDto,
348
+ payload: VivaLaunchParams | InitiateVivaA2aSessionResponseDto,
348
349
  ): Record<string, string> {
349
350
  const params: Record<string, string> = {};
350
351
 
351
352
  Object.entries(payload).forEach(([key, value]) => {
352
- if (value !== undefined) {
353
- params[key] = String(value);
353
+ if (value === undefined) {
354
+ return;
354
355
  }
355
- });
356
-
357
- return params;
358
- }
359
-
360
- private buildRefundLaunchParams(
361
- request: RefundRequest,
362
- reference?: PaymentReferenceContext,
363
- ): Record<string, string> {
364
- const vivaOptions = (request.options ?? {}) as VivaOptions;
365
- const originalTransactionId =
366
- reference?.originalTransactionId?.trim() ||
367
- request.originalTransactionId.trim();
368
- const params: Record<string, string> = {
369
- amount: String(request.amountCents),
370
- clientTransactionId: originalTransactionId,
371
- show_receipt: "false",
372
- show_transaction_result: "false",
373
- };
374
-
375
- if (vivaOptions.sourceCode) {
376
- params.sourceCode = vivaOptions.sourceCode;
377
- }
378
-
379
- if (reference?.referenceCode) {
380
- params.orderCode = reference.referenceCode;
381
- }
382
-
383
- if (reference?.shortReferenceCode) {
384
- params.shortOrderCode = reference.shortReferenceCode;
385
- }
386
-
387
- if (reference?.receiptNumber) {
388
- params.referenceNumber = reference.receiptNumber;
389
- }
390
-
391
- if (reference?.terminalId) {
392
- params.tid = reference.terminalId;
393
- }
394
-
395
- if (
396
- reference?.referenceCode ||
397
- reference?.shortReferenceCode ||
398
- reference?.receiptNumber
399
- ) {
400
- return params;
401
- }
402
-
403
- const originalId = originalTransactionId;
404
- if (/^\d+$/.test(originalId)) {
405
- if (originalId.length === 16) {
406
- params.orderCode = originalId;
407
- } else if (originalId.length === 10) {
408
- params.shortOrderCode = originalId;
409
- } else {
410
- params.referenceNumber = originalId;
356
+ // clientToken / sessionId are internal session identifiers used to
357
+ // poll/sync the payment session and must never be forwarded to the
358
+ // Viva app via the launch URL.
359
+ if (key === "clientToken" || key === "sessionId") {
360
+ return;
411
361
  }
412
- }
362
+ params[key] = String(value);
363
+ });
413
364
 
414
365
  return params;
415
366
  }
416
367
 
417
- private async fetchPaymentReference(
418
- request: RefundRequest,
419
- ): Promise<PaymentReferenceContext | undefined> {
420
- try {
421
- const payload = {
422
- orderId: request.orderRef,
423
- provider: PaymentProvider.Viva,
424
- transactionId: request.originalTransactionId,
425
- businessId: request.businessId,
426
- } satisfies GetPaymentReferenceDto;
427
-
428
- const { data } =
429
- await this.paymentApiWithReference.getPaymentReference(payload);
430
-
431
- return this.extractPaymentReferenceContext(data);
432
- } catch {
433
- return undefined;
434
- }
435
- }
436
-
437
- private extractPaymentReferenceContext(
438
- response?: PaymentReferenceResponse,
439
- ): PaymentReferenceContext | undefined {
440
- if (!response) {
441
- return undefined;
442
- }
443
-
444
- const references = response.references;
445
- if (
446
- !references ||
447
- typeof references !== "object" ||
448
- Array.isArray(references)
449
- ) {
450
- return {
451
- originalTransactionId: response.originalTransactionId,
452
- };
453
- }
454
-
455
- const context = references as Record<string, unknown>;
456
- const paymentReferenceContext: PaymentReferenceContext = {
457
- originalTransactionId:
458
- this.readReferenceValue(context.originalTransactionId) ??
459
- this.readReferenceValue(context.clientTransactionId) ??
460
- response.originalTransactionId,
461
- };
462
- const receiptNumber =
463
- this.readReferenceValue(context.receiptNumber) ??
464
- this.readReferenceValue(context.referenceNumber);
465
- const referenceCode =
466
- this.readReferenceValue(context.referenceCode) ??
467
- this.readReferenceValue(context.orderCode);
468
- const shortReferenceCode =
469
- this.readReferenceValue(context.shortReferenceCode) ??
470
- this.readReferenceValue(context.shortOrderCode);
471
- const terminalId =
472
- this.readReferenceValue(context.terminalId) ??
473
- this.readReferenceValue(context.tid);
474
-
475
- if (receiptNumber) {
476
- paymentReferenceContext.receiptNumber = receiptNumber;
477
- }
478
-
479
- if (referenceCode) {
480
- paymentReferenceContext.referenceCode = referenceCode;
481
- }
482
-
483
- if (shortReferenceCode) {
484
- paymentReferenceContext.shortReferenceCode = shortReferenceCode;
485
- }
486
-
487
- if (terminalId) {
488
- paymentReferenceContext.terminalId = terminalId;
489
- }
490
-
491
- return paymentReferenceContext;
492
- }
493
-
494
- private readReferenceValue(value: unknown): string | undefined {
495
- if (typeof value !== "string") {
496
- return undefined;
497
- }
498
-
499
- const trimmed = value.trim();
500
- return trimmed.length > 0 ? trimmed : undefined;
501
- }
502
-
503
368
  private buildActionUrl(
504
369
  action: string,
505
370
  params: Record<string, string>,
@@ -303,10 +303,10 @@ export class VivaStrategy implements IPaymentStrategy {
303
303
  }
304
304
  }
305
305
 
306
- const message = lastError instanceof Error ? lastError.message : "Verify retries exhausted";
307
306
  throw new PaymentSDKError(
308
307
  PaymentFailureCode.PaymentTimeout as unknown as PaymentErrorCode,
309
- message,
308
+ "Payment Failed",
309
+ lastError, // raw kept for debugging/logging only, not surfaced to user
310
310
  );
311
311
  }
312
312
 
@@ -90,25 +90,6 @@ export interface RefundRequest {
90
90
  options?: VivaRefundOptions | NetsRefundOptions | WorldlineRefundOptions;
91
91
  }
92
92
 
93
- export interface ManualPaymentRequest {
94
- orderRef: string;
95
- amountCents: number;
96
- paymethod: string;
97
- tipAmount?: number;
98
- splitContext?: SplitContextDto;
99
- /**
100
- * Arbitrary client metadata persisted on the session (e.g. voucher code,
101
- * gift card id, employee id, external reference, notes). Surfaced to
102
- * reconciliation when building the order paymentEvent.
103
- */
104
- metadata?: Record<string, unknown>;
105
- }
106
-
107
- export interface VoidRequest {
108
- orderRef: string;
109
- sessionId: string;
110
- }
111
-
112
93
  export interface RevertRequest {
113
94
  orderRef: string;
114
95
  originalTransactionId: string;
@@ -183,13 +164,5 @@ export interface IMunchiPaymentSDK {
183
164
  params: RevertRequest,
184
165
  options?: TransactionOptions,
185
166
  ): Promise<PaymentResult>;
186
- recordManualPayment(
187
- params: ManualPaymentRequest,
188
- options?: TransactionOptions,
189
- ): Promise<PaymentResult>;
190
- voidManualPayment(
191
- params: VoidRequest,
192
- options?: TransactionOptions,
193
- ): Promise<PaymentResult>;
194
167
  reset(): void;
195
168
  }
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.1";
3
+ export const VERSION = "1.10.4";
@@ -1,10 +0,0 @@
1
- import type { AxiosInstance } from "axios";
2
- import { type ManualPaymentRequest, type PaymentResult, type PaymentTerminalConfig, type VoidRequest } from "../types/payment";
3
- export declare class ManualSessionStrategy {
4
- private config;
5
- private sessionApi;
6
- constructor(axios: AxiosInstance, config: PaymentTerminalConfig);
7
- recordPayment(request: ManualPaymentRequest): Promise<PaymentResult>;
8
- voidPayment(request: VoidRequest): Promise<PaymentResult>;
9
- }
10
- //# sourceMappingURL=ManualSessionStrategy.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"ManualSessionStrategy.d.ts","sourceRoot":"","sources":["../../../src/strategies/ManualSessionStrategy.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,OAAO,CAAC;AAG3C,OAAO,EACL,KAAK,oBAAoB,EACzB,KAAK,aAAa,EAClB,KAAK,qBAAqB,EAE1B,KAAK,WAAW,EACjB,MAAM,kBAAkB,CAAC;AAG1B,qBAAa,qBAAqB;IAK9B,OAAO,CAAC,MAAM;IAJhB,OAAO,CAAC,UAAU,CAAoB;gBAGpC,KAAK,EAAE,aAAa,EACZ,MAAM,EAAE,qBAAqB;IAKjC,aAAa,CAAC,OAAO,EAAE,oBAAoB,GAAG,OAAO,CAAC,aAAa,CAAC;IA8BpE,WAAW,CAAC,OAAO,EAAE,WAAW,GAAG,OAAO,CAAC,aAAa,CAAC;CAmChE"}
@@ -1,93 +0,0 @@
1
- import {
2
- type CreateManualSessionDto,
3
- PaymentSessionApi,
4
- PaymentSessionStatus,
5
- } from "@munchi_oy/core";
6
- import type { AxiosInstance } from "axios";
7
-
8
- import { PaymentErrorCode, PaymentSDKError } from "../error";
9
- import {
10
- type ManualPaymentRequest,
11
- type PaymentResult,
12
- type PaymentTerminalConfig,
13
- SdkPaymentStatus,
14
- type VoidRequest,
15
- } from "../types/payment";
16
- import { mapSessionResult } from "./sessionResult";
17
-
18
- export class ManualSessionStrategy {
19
- private sessionApi: PaymentSessionApi;
20
-
21
- constructor(
22
- axios: AxiosInstance,
23
- private config: PaymentTerminalConfig,
24
- ) {
25
- this.sessionApi = new PaymentSessionApi(undefined, "", axios);
26
- }
27
-
28
- async recordPayment(request: ManualPaymentRequest): Promise<PaymentResult> {
29
- try {
30
- const payload: CreateManualSessionDto = {
31
- businessId: Number(this.config.storeId),
32
- orderId: request.orderRef,
33
- amount: request.amountCents,
34
- paymethod: request.paymethod,
35
- provider: this.config.provider,
36
- };
37
- if (request.tipAmount !== undefined) {
38
- payload.tipAmount = request.tipAmount;
39
- }
40
- if (request.splitContext !== undefined) {
41
- payload.splitContext = request.splitContext;
42
- }
43
- if (request.metadata !== undefined) {
44
- payload.metadata = request.metadata;
45
- }
46
-
47
- const { data } = await this.sessionApi.recordManualPayment(payload);
48
- return mapSessionResult(data, request.orderRef);
49
- } catch (error) {
50
- throw new PaymentSDKError(
51
- PaymentErrorCode.NETWORK_ERROR,
52
- "Failed to record manual payment",
53
- error,
54
- );
55
- }
56
- }
57
-
58
- async voidPayment(request: VoidRequest): Promise<PaymentResult> {
59
- try {
60
- const { data } = await this.sessionApi.voidManualPayment({
61
- sessionId: request.sessionId,
62
- });
63
-
64
- const isVoided =
65
- data.status === PaymentSessionStatus.Voided ||
66
- data.status === PaymentSessionStatus.Voiding;
67
-
68
- const result: PaymentResult = {
69
- success: isVoided,
70
- status: isVoided ? SdkPaymentStatus.SUCCESS : SdkPaymentStatus.FAILED,
71
- orderId: request.orderRef,
72
- transactionId: data.providerTransactionId ?? data.sessionId,
73
- };
74
-
75
- if (!isVoided) {
76
- if (data.errorCode) {
77
- result.errorCode = data.errorCode;
78
- }
79
- if (data.errorMessage) {
80
- result.errorMessage = data.errorMessage;
81
- }
82
- }
83
-
84
- return result;
85
- } catch (error) {
86
- throw new PaymentSDKError(
87
- PaymentErrorCode.NETWORK_ERROR,
88
- "Failed to void manual payment",
89
- error,
90
- );
91
- }
92
- }
93
- }