@securecall/client-component
Version:
SecureCall Core Web Component
2 lines • 43.2 kB
JavaScript
import{r as e,c as t,h as s,H as i}from"./p-KxdoBBDC.js";import{L as r,C as n,s as a}from"./p-By6Qn8nU.js";function o(...e){const t=e=>e&&typeof e==="object";return e.reduce(((e,s)=>{Object.keys(s).forEach((i=>{const r=e[i];const n=s[i];if(n===undefined){return}if(Array.isArray(r)&&Array.isArray(n)){e[i]=r.concat(n)}else if(t(r)&&t(n)){e[i]=o(r,n)}else{e[i]=n}}));return e}),{})}class h{order;value;readOnly;hidden;valid;possibleValues;mapping;externalMapping;label;component;min;max;active;placeholder;hideRelatedFields;secure;optional;_name;_owner;constructor(e,t){this._name=t;this._owner=e;return new Proxy(this,{set(e,t,s,i){const r=t.toString();if(!r.startsWith("_")&&r in e){if(e._owner&&typeof e._owner.propagate==="function"){e._owner.propagate(e._name,r,s)}}return Reflect.set(e,t,s,i)}})}toJSON(){return{[this._name]:this.calculatedValue()}}calculatedValue(){const e={};for(const t in this){if(this.hasOwnProperty(t)&&!t.startsWith("_")&&this[t]!==undefined){e[t]=this[t]}}return e}}class l{_name;_value;constructor(){this._name="metadata";this._value={};return new Proxy(this,{get(e,t,s){const i=t.toString();const r=Object.getOwnPropertyNames(Object.getPrototypeOf(e)).concat(Object.getOwnPropertyNames(e));if(r.includes(i)){return Reflect.get(e,t,s)}else{return e.rawValue[i]}},set(e,t,s,i){const r=t.toString();const n=Object.getOwnPropertyNames(Object.getPrototypeOf(e)).concat(Object.getOwnPropertyNames(e));if(n.includes(r)){return Reflect.set(e,t,s,i)}else{e.rawValue[r]=s;return true}}})}toJSON(){return{[this._name]:this.calculatedValue()}}calculatedValue(){return{value:this._value}}get rawValue(){return this._value}}class c{_fields;_uiFields;_level;constructor(e,t=u.Instance){this._uiFields=e;this._level=t;this._fields={metadata:new l};return new Proxy(this,{get(e,t,s){const i=t.toString();if(e.parent.fieldNames.includes(i)){if(!e.rawFields[i]){e.rawFields[i]=new h(e,i)}return e.rawFields[i]}return Reflect.get(e,t,s)}})}toJSON(){const e={...this};delete e._uiFields;return e}get parent(){return this._uiFields}get rawFields(){return this._fields}addNewField(e,t){if(!this.parent.fieldNames.includes(e)){this.parent.fieldNames.push(e);Object.entries(t).forEach((([t,s])=>{this[e][t]=s}))}else{throw new Error(`Field ${e} already exists in the request fields list`)}}addOrUpdateField(e,t){if(!this.parent.fieldNames.includes(e)){this.parent.fieldNames.push(e)}Object.entries(t).forEach((([t,s])=>{this[e][t]=s}))}propagate(e,t,s){if(this.parent.fieldNames.includes(e)){if(this._level===u.Instance){this.propagateValue(this.parent.session,e,t,s)}else if(this._level===u.Session){this.propagateValue(this.parent.transaction,e,t,s)}}}propagateValue(e,t,s,i){if(e.rawFields[t]){e[t][s]=i}}calculatedFields(){return Object.fromEntries(Object.entries(this._fields).filter((([e])=>this.parent.fieldNames.includes(e))).map((([e,t])=>[e,t.calculatedValue()])))}}var u;(function(e){e["Instance"]="instance";e["Session"]="session";e["Transaction"]="transaction"})(u||(u={}));class d{_defaults;_instance;_session;_transaction;_fieldNames;constructor(e){this._defaults=JSON.parse(JSON.stringify(e));this._fieldNames=Object.keys(e);this._instance=new c(this,u.Instance);this._session=new c(this,u.Session);this._transaction=new c(this,u.Transaction);return new Proxy(this,{get(e,t,s){const i=t.toString();if(e.fieldNames.includes(i)){return e.instance[i]}return Reflect.get(e,t,s)}})}get fieldNames(){return this._fieldNames}get instance(){return this._instance}get session(){return this._session}get transaction(){return this._transaction}addNewField(e,t){this._instance.addNewField(e,t)}addOrUpdateField(e,t){this._instance.addOrUpdateField(e,t)}processSecureData(e){const t=this.calculatedFields();this._fieldNames.forEach((e=>{if(t[e].secure)this._transaction[e].active=undefined}));Object.entries(e).forEach((([e,t])=>{let s=this._transaction[e];Object.entries(t).forEach((([e,t])=>{s[e]=t}))}))}clearNonSecureFields(){const e=this.calculatedFields();this._fieldNames.forEach((t=>{if(!e[t].secure)this._transaction[t].value=undefined}))}resetInstance(){this._instance=new c(this,u.Instance)}resetSession(){this._session=new c(this,u.Session)}resetTransaction(){this._transaction=new c(this,u.Transaction)}calculatedFields(){return o(this._defaults,this._instance.calculatedFields(),this._session.calculatedFields(),this._transaction.calculatedFields())}asComponentChildren(){return Object.entries(this.calculatedFields()).filter((([e,t])=>!t.hidden)).sort((([e,t],[s,i])=>{const r=t.order===undefined?1e3:t.order;const n=i.order===undefined?1e3:i.order;return r-n})).map((([e,t])=>{const{component:s,...i}=t;return{name:e,component:s||"string",config:i}}))}asAPITransaction(){let e={metadata:{}};Object.entries(this.calculatedFields()).filter((([e,t])=>!t.secure)).filter((([e,t])=>!(t.optional&&(!t.value||t.value.trim()==="")))).forEach((([t,s])=>{if(s.mapping){let t=s.mapping.split(".");if(t[0]==="metadata"){e.metadata[t[1]]=s.value}else{e[t[0]]=s.value}}else{if(t==="metadata"){e[t]={...e.metadata,...s.value}}else{e[t]=s.value}}}));return e}}const f={transactionType:{order:10,mapping:"transaction_type",label:"Transaction Type",placeholder:"Select Transaction Type",component:"radio",valid:true,value:"pay",readOnly:false,hidden:false,possibleValues:{pay:"Pay",pay_and_tokenise:"Pay and Tokenise",tokenise:"Tokenise"},hideRelatedFields:{pay:{amount:false,paymentReference:false,tokenReference:true},pay_and_tokenise:{amount:false,paymentReference:false,tokenReference:false},tokenise:{amount:true,paymentReference:true,tokenReference:false}}},amount:{order:20,label:"Amount",placeholder:"Enter amount",component:"currency",valid:false,readOnly:false,hidden:false,min:.01,max:999999.99},paymentReference:{order:30,mapping:"payment_reference",label:"Payment Ref",placeholder:"Payment Reference",component:"string",valid:false,readOnly:false,hidden:false},tokenReference:{order:40,mapping:"token_reference",label:"Customer Ref",placeholder:"Customer ID or Reference",component:"string",valid:false,readOnly:false,hidden:false},nameOnCard:{order:50,mapping:"name_on_card",label:"Name On Card",component:"string",valid:false,readOnly:false,hidden:false},gatewayName:{order:60,mapping:"metadata.gateway_name",label:"Gateway",component:"select",valid:false,readOnly:false,hidden:true,possibleValues:{default:"Default Gateway"}},pan:{order:100,label:"Card Number",component:"secure-pan",valid:false,secure:true,readOnly:false,hidden:false},expiry:{order:110,label:"Expiry Date",component:"secure",valid:false,secure:true,readOnly:false,hidden:false},cvv:{order:120,label:"CVV",component:"secure",secure:true,valid:false,readOnly:false,hidden:false},metadata:{order:1e3,label:"Metadata",component:"metadata",valid:true,readOnly:false,hidden:true}};var p;(function(e){e["NotAuthenticated"]="NotAuthenticated";e["Idle"]="Idle";e["Securing"]="Securing";e["Secured"]="Secured";e["Submitting"]="Submitting";e["Success"]="Success";e["Failure"]="Failure"})(p||(p={}));var m=Object.defineProperty;var v=Object.defineProperties;var g=Object.getOwnPropertyDescriptors;var b=Object.getOwnPropertySymbols;var w=Object.prototype.hasOwnProperty;var y=Object.prototype.propertyIsEnumerable;var k=(e,t,s)=>t in e?m(e,t,{enumerable:true,configurable:true,writable:true,value:s}):e[t]=s;var S=(e,t)=>{for(var s in t||(t={}))if(w.call(t,s))k(e,s,t[s]);if(b)for(var s of b(t)){if(y.call(t,s))k(e,s,t[s])}return e};var E=(e,t)=>v(e,g(t));var O=(e,t)=>{var s={};for(var i in e)if(w.call(e,i)&&t.indexOf(i)<0)s[i]=e[i];if(e!=null&&b)for(var i of b(e)){if(t.indexOf(i)<0&&y.call(e,i))s[i]=e[i]}return s};var x=(e,t,s)=>new Promise(((i,r)=>{var n=e=>{try{o(s.next(e))}catch(e){r(e)}};var a=e=>{try{o(s.throw(e))}catch(e){r(e)}};var o=e=>e.done?i(e.value):Promise.resolve(e.value).then(n,a);o((s=s.apply(e,t)).next())}));function T(e,t){return x(this,null,(function*(){const s=e.getReader();let i;while(!(i=yield s.read()).done){t(i.value)}s.releaseLock()}))}function C(e,t,s=3e4){let i;let r;let n;let a=false;let o;let h=false;const l=()=>{if(o){clearTimeout(o)}if(t&&!h){o=setTimeout((()=>{t()}),s)}};const c=()=>{if(o){clearTimeout(o);o=void 0}};l();return function t(s){if(i===void 0){i=s;r=0;n=-1;h=false;l()}else{i=A(i,s)}const o=i.length;let u=0;while(r<o){if(a){if(i[r]===10){u=++r}a=false}let t=-1;for(;r<o&&t===-1;++r){switch(i[r]){case 58:if(n===-1){n=r-u;h=true;c()}break;case 13:a=true;case 10:t=r;break}}if(t===-1){break}e(i.subarray(u,t),n);u=r;n=-1;h=false;l()}if(u===o){i=void 0}else if(u!==0){i=i.subarray(u);r-=u}}}function R(e,t,s){let i=F();const r=new TextDecoder;return function n(a,o){if(a.length===0){s==null?void 0:s(i);i=F()}else if(o>0){const s=r.decode(a.subarray(0,o));const n=o+(a[o+1]===32?2:1);const h=r.decode(a.subarray(n));switch(s){case"data":i.data=i.data?i.data+"\n"+h:h;break;case"event":i.event=h;break;case"id":e(i.id=h);break;case"retry":const s=parseInt(h,10);if(!isNaN(s)){t(i.retry=s)}break}}}}function A(e,t){const s=new Uint8Array(e.length+t.length);s.set(e);s.set(t,e.length);return s}function F(){return{data:"",event:"",id:"",retry:void 0}}var _=class extends Error{constructor(e){super(e);this.name="RetriableError"}};var P=class extends Error{constructor(e,t){super(t);this.name="HTTPError";this.code=e}};var N=class extends P{constructor(e,t){super(e,t);this.name="HTTPClientError"}};var j=class extends Error{constructor(e){super(e);this.name="FailedRetriesError"}};var M=class extends Error{constructor(e){super(e);this.name="NotConnectedError"}};var I="text/event-stream";var L=1e3;var D="last-event-id";var V=0;function H(e,t){var s=t,{signal:i,headers:r,onopen:n,onmessage:a,onclose:o,onerror:h,fetch:l,heartbeat:c}=s,u=O(s,["signal","headers","onopen","onmessage","onclose","onerror","fetch","heartbeat"]);return new Promise(((t,s)=>{const d=S({},r);if(!d.accept){d.accept=I}let f;let p=L;let m=0;function v(){window.clearTimeout(m);f.abort()}i==null?void 0:i.addEventListener("abort",(()=>{v();t()}));const g=c!=null?c:V;const b=l!=null?l:window.fetch;const w=n!=null?n:J;function y(){return x(this,null,(function*(){var i,r;f=new AbortController;try{const s=yield b(e,E(S({},u),{headers:d,signal:f.signal}));yield w(s);yield T(s.body,C(R((e=>{if(e){d[D]=e}else{delete d[D]}}),(e=>{p=e}),a),g>0?()=>{f.abort("timeout")}:void 0,g));o==null?void 0:o();v();t()}catch(e){if(!f.signal.aborted){try{const t=(i=h==null?void 0:h(e))!=null?i:p;window.clearTimeout(m);m=window.setTimeout(y,t)}catch(e){v();s(e)}}else if(f.signal.reason==="timeout"){try{const e=new _(`Timeout: No traffic received within ${g}ms`);const t=(r=h==null?void 0:h(e))!=null?r:p;window.clearTimeout(m);m=window.setTimeout(y,t)}catch(e){v();s(e)}}}}))}y()}))}function J(e){const t=e.headers.get("content-type");if(!(t==null?void 0:t.startsWith(I))){throw new Error(`Expected content-type to be ${I}, Actual: ${t}`)}}var B="/v1/login";var $="/v1/secure";var z="/v1/release";var U="/v1/events";var q="/v1/reset";var W="/v1/submit";var G="/v1/logout";var K="/v1/telephony";var Q={"Content-Type":"application/json"};var X=2;var Y=45e3;var Z={400:"Bad Request",403:"Forbidden",404:"Not Found",408:"Request Timeout",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable"};var ee=class extends Event{constructor(e,t,s){super("authentication");this.success=e;this.reason=t;this.code=s;if(t===void 0&&this.code!==void 0){this.reason=s==null?void 0:s.toString()}}};var te=class e extends Event{static createEvent(t,s){let i;switch(t){case"configuration":i=new se(s);break;case"status":i=new ie(s);break;case"telephony":i=new re(s);break;default:i=new e(t,s);break}return i}constructor(e,t){super(e);this.detail=t}};var se=class extends te{constructor(e){super("configuration",e)}get settings(){return this.detail.settings}get gateways(){return this.detail.gateways}};var ie=class extends te{constructor(e){super("session",e)}get call_data(){return this.detail.call_data}get secure_data(){return this.detail.secure_data}get transaction_data(){return this.detail.transaction_data}get state(){return this.detail.state}get timestamp(){return this.detail.timestamp}get session(){return this.detail.session}};var re=class extends te{constructor(e){super("telephony",e)}get command(){return this.detail.command}get dnis(){return this.detail.dnis}get timestamp(){return this.detail.timestamp}get session(){return this.detail.session}};var ne="1.1.0";var ae=class extends EventTarget{constructor(e,t){super();this.useCookie=false;this.connected=false;this.instanceId=Math.floor(Math.random()*1e8);this.popupWindow=null;this.webexFlag=false;this.retryCount=0;this.logOutput=console;this.isDebugActive=false;this.apiLocation=e;this.logPrefix=`SecureCallClientAPI(${ne}/${this.instanceId})`;if(t){this.logPrefix=`${this.logPrefix}->${t}`}this.debug=true}get version(){return ne}get isConnected(){return this.connected}set debug(e){this.isDebugActive=e;if(e){const e=function(){};e.toString=function(){return(new Date).toISOString()};if(this.logOutput===console)this.log=this.logOutput.debug.bind(this.logOutput,e.toString(),this.logPrefix);else this.log=this.logOutput.debug.bind(this.logOutput,this.logPrefix)}else{this.log=function(){}}}get debug(){return this.isDebugActive}set logger(e){this.logOutput=e;this.debug=this.isDebugActive}authenticate(e,t,s){return x(this,null,(function*(){this.log("authenticate");this.email=e!=null?e:this.email;this.password=t!=null?t:this.password;if(typeof s!="undefined"){this.useCookie=s}return this.connect()}))}login(){return x(this,null,(function*(){let e;try{this.log("login");e=yield fetch(this.apiLocation+B,{method:"POST",credentials:"include",headers:this.clientAPIHeaders()});this.log("login","response",e);if(e.redirected){return this.handleRedirect(e)}else if(e.ok){return this.connectEventStream()}}catch(t){this.log("login","error",t.message);e=new Response(null,{status:400,statusText:t.message})}this.asyncDispatchEvent(new ee(false,e.statusText,e.status));this.throwHTTPError(e.status,e.statusText)}))}logout(){return x(this,null,(function*(){this.log("logout");if(!this.connected){throw new M}this.disconnect();let e;try{e=yield fetch(this.apiLocation+G,{method:"POST",credentials:"include",headers:this.clientAPIHeaders()});this.log("logout","response",e);if(e.redirected){return this.handleRedirect(e)}else if(e.ok){return}}catch(t){this.log("logout","error",t.message);e=new Response(null,{status:400,statusText:t.message})}this.throwHTTPError(e.status,e.statusText)}))}secure(e){return x(this,null,(function*(){this.log("secure");if(!this.connected){throw new M}let t;try{t=yield fetch(this.apiLocation+$,{method:"POST",credentials:"include",headers:this.clientAPIHeaders(),body:JSON.stringify(e!=null?e:{})});this.log("secure","response","",t);if(t.redirected){this.handleRedirect(t);return}else if(t.ok){return}else if(t.status===401||t.status===403){this.asyncDispatchEvent(new ee(false,t.statusText,t.status))}}catch(e){this.log("secure","error",e.message);t=new Response(null,{status:400,statusText:e.message})}this.throwHTTPError(t.status,t.statusText)}))}release(){return x(this,null,(function*(){this.log("release");if(!this.connected){throw new M}let e;try{e=yield fetch(this.apiLocation+z,{method:"POST",credentials:"include",headers:this.clientAPIHeaders()});this.log("release","response","",e);if(e.redirected){this.handleRedirect(e);return}else if(e.ok){return}else if(e.status===401||e.status===403){this.asyncDispatchEvent(new ee(false,e.statusText,e.status))}}catch(t){this.log("release","error",t.message);e=new Response(null,{status:400,statusText:t.message})}this.throwHTTPError(e.status,e.statusText)}))}reset(e){return x(this,null,(function*(){let t;this.log("reset");if(!this.connected){throw new M}if(e===void 0){t=["all"]}else if(typeof e==="string"){t=[e]}else{t=e}let s;try{s=yield fetch(this.apiLocation+q,{method:"POST",credentials:"include",headers:this.clientAPIHeaders(),body:JSON.stringify({fields:t})});this.log("reset","response",s);if(s.redirected){return this.handleRedirect(s)}else if(s.ok){return}else if(s.status===401||s.status===403){this.asyncDispatchEvent(new ee(false,s.statusText,s.status))}}catch(e){this.log("reset","error",e.message);s=new Response(null,{status:400,statusText:e.message})}this.throwHTTPError(s.status,s.statusText)}))}submit(e){return x(this,null,(function*(){this.log("submit");if(!this.connected){throw new M}if(e===void 0){throw new Error("no parameter")}let t;try{this.log("submit",e);t=yield fetch(this.apiLocation+W,{method:"POST",credentials:"include",headers:this.clientAPIHeaders(),body:JSON.stringify(e)});this.log("submit","response","",t);if(t.redirected){return this.handleRedirect(t)}else if(t.ok){return}else if(t.status===401||t.status===403){this.asyncDispatchEvent(new ee(false,t.statusText,t.status))}}catch(e){this.log("submit","error",e.message);t=new Response(null,{status:400,statusText:e.message})}this.throwHTTPError(t.status,t.statusText)}))}telephony(e){return x(this,null,(function*(){this.log("telephony");if(!this.connected){throw new M}if(e===void 0){throw new Error("no parameter")}let t;try{t=yield fetch(this.apiLocation+K,{method:"POST",credentials:"include",headers:this.clientAPIHeaders(),body:JSON.stringify(e)});this.log("telephony","response","",t);if(t.redirected){return this.handleRedirect(t)}else if(t.ok){return}else if(t.status===401||t.status===403){this.asyncDispatchEvent(new ee(false,t.statusText,t.status))}}catch(e){this.log("telephony","error",e.message);t=new Response(null,{status:400,statusText:e.message})}this.throwHTTPError(t.status,t.statusText)}))}connect(){if(!this.useCookie&&!this.email&&!this.password){throw new Error("email and password need to be set for useCookie to be false")}if(this.email&&!this.password){throw new Error("password needs to be set")}if(this.useCookie){return this.login()}else{return this.connectEventStream()}}disconnect(){var e;this.log("disconnect");(e=this.abortController)==null?void 0:e.abort()}handleAPIResponse(e){this.log("handleAPIResponse");if(e.redirected){this.handleRedirect(e)}else if(e.ok){this.log("handleAPIResponse","doLogin was successful",e);return this.connectEventStream()}else{this.throwHTTPError(e.status,e.statusText)}}handleRedirect(e){this.log("handleRedirect",e.url);this.popupWindow=window.open(e.url,"popup","width=600,height=600");if(this.popupWindow){let e=setInterval((()=>{var t;if((t=this.popupWindow)==null?void 0:t.closed){clearInterval(e);this.log("handleRedirect","detected popup window was closed");this.asyncDispatchEvent(new ee(false,"popup window closed"))}}),500);window.addEventListener("message",(t=>{if(t.data==="webexLoginSuccess"){clearInterval(e);this.log("handleRedirect","window eventListener","Webex login was successful");this.connectEventStream()}}),{once:true})}}connectEventStream(){return x(this,null,(function*(){var e;this.log("connectEventStream");(e=this.abortController)==null?void 0:e.abort();this.abortController=new AbortController;const t=this.abortController.signal;yield H(this.apiLocation+U,{method:"GET",credentials:this.shouldSendCredentials()?"same-origin":"include",headers:this.eventSourceHeaders(),signal:t,onopen:this.onEventStreamOpen.bind(this),onmessage:this.onEventStreamMessage.bind(this),onclose:this.onEventStreamClose.bind(this),onerror:this.onEventStreamError.bind(this),heartbeat:Y})}))}onEventStreamOpen(e){return x(this,null,(function*(){var t;this.log("onEventStreamOpen","status=",e.status);if(e.redirected){this.log("onEventStreamOpen","response.redirected",e);this.webexFlag=true;return this.handleRedirect(e)}else if(e.ok){if((t=e.headers.get("content-type"))==null?void 0:t.startsWith(I)){this.dispatchEvent(new ee(true));this.connected=true;this.log("onEventStreamOpen","text/event-stream response.ok",e)}else{this.log("onEventStreamOpen","text/html response.ok",e);throw new Error("Received an unexpected text/html page")}}else if(e.status>=400&&e.status<=499)throw new N(e.status,e.statusText);else throw new _("onopen retriable")}))}onEventStreamMessage(e){this.log("onEventStreamMessage","event",e.event,e);this.asyncDispatchEvent(te.createEvent(e.event,JSON.parse(e.data)))}onEventStreamClose(){this.connected=false;if(this.webexFlag){this.log("onEventStreamClose","doing_popup so ignore");this.webexFlag=false}else{this.log("onEventStreamClose");throw new _("close")}}onEventStreamError(e){this.log("onEventStreamError",e);if(e instanceof _){if(this.retryCount<X){const e=Math.pow(2,this.retryCount)*1e3;this.retryCount++;this.log(`Retrying in ${e} milliseconds...`);return e}else{this.asyncDispatchEvent(new ee(false,"no more retries"));this.retryCount=0;throw new j}}else{this.asyncDispatchEvent(new ee(false,e.message,e==null?void 0:e.code));this.retryCount=0;throw e}}asyncDispatchEvent(e){return x(this,null,(function*(){this.dispatchEvent(e)}))}shouldSendCredentials(){return this.email&&this.password}authenticationHeader(){if(this.email&&this.password){return{Authorization:"Basic "+btoa(this.email+":"+this.password)}}else{return{}}}eventSourceHeaders(){return S(E(S({},this.authenticationHeader()),{Accept:"text/event-stream, text/html"}),this.logHeaders())}clientAPIHeaders(){return S(S(S({},Q),this.authenticationHeader()),this.logHeaders())}logHeaders(){return{"X-SecureCall-Client-Identifier":this.logPrefix}}throwHTTPError(e,t){if(!t){t=this.lookupHTTPText(e)}if(e>=400&&e<=499)throw new N(e,t);else throw new P(e,t)}lookupHTTPText(e){return Z[e]||"Unknown"}};class oe{_defaults;_result;_fieldNames;constructor(e){this._defaults=JSON.parse(JSON.stringify(e));this._fieldNames=Object.keys(e);this._result={}}get defaults(){return this._defaults}toJSON(){return this.calculatedFields()}processResponse(e){if(e===undefined||e===null){return}this._fieldNames.forEach((t=>{const s=this._defaults[t].mapping||`response.${t}`;let i=s.split(".");const r=i.reduce(((e,t)=>e?.[t]),e);if(r!==undefined){this._result[t]={value:r}}}))}get fieldNames(){return this._fieldNames}asComponentChildren(e){return Object.entries(this.calculatedFields()).filter((([t,s])=>e?s.showOnSuccess:s.showOnFailure)).filter((([e,t])=>!(t.ignoreIfEmpty&&(t.value===null||t.value===undefined||t.value==="")))).sort((([e,t],[s,i])=>{const r=t.order===undefined?1e3:t.order;const n=i.order===undefined?1e3:i.order;return r-n})).map((([e,t])=>({name:e,label:t.label,value:t.value,action:t.action,component:t.component||"field"})))}calculatedFields(){return o(this._defaults,this._result)}}const he={transactionId:{order:10,label:"Transaction ID",mapping:"response.transaction_id",showOnSuccess:true},receipt:{order:20,label:"Receipt",showOnSuccess:true},token:{order:30,label:"Token",showOnSuccess:false},errorCode:{order:100,label:"Error Code",mapping:"response.error_code",showOnFailure:true},errorMessage:{order:110,label:"Error Message",mapping:"response.error_message",showOnFailure:true},anotherTransaction:{order:200,label:"Another Transaction",action:"retryClearCVV",showOnSuccess:true,showOnFailure:true,component:"button"}};const le=35e3;const ce=6e4;const ue=3;const de=':host{display:flex;flex-direction:column;align-items:center;width:fit-content;min-width:300px;margin:auto;--theme-background-color-dark:none;--theme-primary-color-dark:white;--theme-secondary-color-dark:#ccc;--theme-button-color-dark:rgba(4, 156, 196, 0.6);--theme-button-color-hover-dark:rgba(4, 156, 196, 1);--theme-button-color-disabled-dark:rgba(4, 156, 196, 0.3);--theme-text-disabled-color-dark:rgba(4, 156, 196, 1);--theme-border-color-dark:#ccc;--theme-border-color-disabled-dark:rgba(4, 156, 196, 0.3);--theme-input-active-background-dark:white;--theme-input-inactive-background-dark:#ccc;--theme-spinner-border-dark:rgba(255, 255, 255, 0.3);--theme-spinner-color-dark:rgba(4, 156, 196, 1);--theme-background-color-light:none;--theme-primary-color-light:#333;--theme-secondary-color-light:#ccc;--theme-button-color-light:rgba(4, 156, 196, 0.6);--theme-button-color-hover-light:rgba(4, 156, 196, 1);--theme-button-color-disabled-light:rgba(4, 156, 196, 0.3);--theme-text-disabled-color-light:rgba(4, 156, 196, 0.6);--theme-border-color-light:#ccc;--theme-border-color-disabled-light:rgba(4, 156, 196, 0.3);--theme-input-active-background-light:white;--theme-input-inactive-background-light:#ccc;--theme-spinner-border-light:rgba(0, 0, 0, 0.3);--theme-spinner-color-light:rgba(4, 156, 196, 1);--icon-valid:url(\'data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16"><path d="M8 15A7 7 0 1 1 8 1a7 7 0 0 1 0 14m0 1A8 8 0 1 0 8 0a8 8 0 0 0 0 16"/><path d="m10.97 4.97-.02.022-3.473 4.425-2.093-2.094a.75.75 0 0 0-1.06 1.06L6.97 11.03a.75.75 0 0 0 1.079-.02l3.992-4.99a.75.75 0 0 0-1.071-1.05"/></svg>\');--icon-invalid:url(\'data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16"><path d="M8 15A7 7 0 1 1 8 1a7 7 0 0 1 0 14m0 1A8 8 0 1 0 8 0a8 8 0 0 0 0 16"/><path d="M7.002 11a1 1 0 1 1 2 0 1 1 0 0 1-2 0M7.1 4.995a.905.905 0 1 1 1.8 0l-.35 3.507a.552.552 0 0 1-1.1 0z"/></svg>\');--icon-reset:url(\'data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16"><path fill-rule="evenodd" d="M8 3a5 5 0 1 1-4.546 2.914.5.5 0 0 0-.908-.417A6 6 0 1 0 8 2z"/><path d="M8 4.466V.534a.25.25 0 0 0-.41-.192L5.23 2.308a.25.25 0 0 0 0 .384l2.36 1.966A.25.25 0 0 0 8 4.466"/></svg>\')}.theme-dark{width:100%;background-color:var(--theme-background-color-dark);--theme-primary-color:var(--theme-primary-color-dark);--theme-secondary-color:var(--theme-secondary-color-dark);--theme-button-color:var(--theme-button-color-dark);--theme-button-color-hover:var(--theme-button-color-hover-dark);--theme-button-color-disabled:var(--theme-button-color-disabled-dark);--theme-text-disabled-color:var(--theme-text-disabled-color-dark);--theme-border-color:var(--theme-border-color-dark);--theme-border-color-disabled:var(--theme-border-color-disabled-dark);--theme-input-active-background:var(--theme-input-active-background-dark);--theme-input-inactive-background:var(--theme-input-inactive-background-dark);--theme-spinner-border:var(--theme-spinner-border-dark);--theme-spinner-color:var(--theme-spinner-color-dark)}.theme-light{width:100%;background-color:var(--theme-background-color-light);--theme-primary-color:var(--theme-primary-color-light);--theme-secondary-color:var(--theme-secondary-color-light);--theme-button-color:var(--theme-button-color-light);--theme-button-color-hover:var(--theme-button-color-hover-light);--theme-button-color-disabled:var(--theme-button-color-disabled-dark);--theme-text-disabled-color:var(--theme-text-disabled-color-light);--theme-border-color:var(--theme-border-color-light);--theme-border-color-disabled:var(--theme-border-color-disabled-light);--theme-input-active-background:var(--theme-input-active-background-light);--theme-input-inactive-background:var(--theme-input-inactive-background-light);--theme-spinner-border:var(--theme-spinner-border-light);--theme-spinner-color:var(--theme-spinner-color-light)}.component-button{width:fit-content;padding:10px 20px;font-size:16px;color:var(--theme-primary-color);background-color:var(--theme-button-color);border:1px solid var(--theme-secondary-color);border-radius:5px;transition:background-color 0.3s ease, border-color 0.3s ease;cursor:pointer}.component-button:hover{background-color:var(--theme-button-color-hover);border-color:var(--theme-button-color-hover)}.component-button:disabled{background-color:var(--theme-button-color-disabled);border-color:var(--theme-border-color-disabled);color:var(--theme-text-disabled-color);cursor:not-allowed;pointer-events:none}.secure-form{text-align:center}.response-result-container{text-align:center;font-size:1.2rem;font-weight:bold}.loading-spinner{display:flex;justify-content:center;align-items:center;height:var(--spinner-container-size, 50px)}.spinner{position:relative;width:var(--spinner-container-size, 50px);height:var(--spinner-container-size, 50px)}.spinner-circle{border:4px solid var(--theme-spinner-border);border-top:4px solid var(--theme-spinner-color);border-radius:50%;width:var(--spinner-circle-size, 20px);height:var(--spinner-circle-size, 20px);animation:spin 1s linear infinite}@keyframes spin{0%{transform:rotate(0deg)}100%{transform:rotate(360deg)}}';const fe=class{constructor(s){e(this,s);this.authenticationSuccess=t(this,"authenticationSuccess");this.authenticationFailure=t(this,"authenticationFailure");this.configurationChanged=t(this,"configurationChanged");this.callSecured=t(this,"callSecured");this.callEnded=t(this,"callEnded");this.transactionSubmitted=t(this,"transactionSubmitted");this.transactionSubmitting=t(this,"transactionSubmitting");this.transactionSuccess=t(this,"transactionSuccess");this.transactionFailure=t(this,"transactionFailure");this.loggedOut=t(this,"loggedOut");this.telephonyHold=t(this,"telephonyHold");this.telephonyRecover=t(this,"telephonyRecover");this.telephonyLegA=t(this,"telephonyLegA");this.telephonyLegB=t(this,"telephonyLegB");this.telephonyValidate=t(this,"telephonyValidate")}apiLocation=window.origin;awaitActiveCall=false;theme="light";displayTransactionResult=true;switchHint;hideSecureButton=false;customLogger;currentState=p.NotAuthenticated;errorMessage;transactionToggle=false;authenticationSuccess;authenticationFailure;configurationChanged;callSecured;callEnded;transactionSubmitted;transactionSubmitting;transactionSuccess;transactionFailure;loggedOut;telephonyHold;telephonyRecover;telephonyLegA;telephonyLegB;telephonyValidate;_requestFields=new d(f);_responseFields=new oe(he);client_api;timeoutId;instanceId=Math.floor(Math.random()*1e8);authenticationCount=0;secureData;currentSession;transactionElement=null;log;boundProcessAuthenticationEvent=this.processAuthenticationEvent.bind(this);boundProcessStatusEvent=this.processStatusEvent.bind(this);boundProcessConfigurationEvent=this.processConfigurationEvent.bind(this);boundProcessTelephonyEvent=this.processTelephonyEvent.bind(this);boundVisibilityEvent=this.processVisibilityEvent.bind(this);createLogger(){if(this.customLogger){console.debug("customLogger: ",this.customLogger);const e=["debug","info","warn","error"];const t=e.filter((e=>typeof this.customLogger[e]!=="function"));if(t.length===0){console.debug("settingGlobalLogger: ",this.customLogger);a(this.customLogger)}}console.debug("creating logger: ",this.customLogger);this.log=new r("SecurecallClient",this.instanceId)}connectedCallback(){this.createLogger();this.log.debug(": connectedCallback");document.addEventListener("visibilitychange",this.boundVisibilityEvent);this.client_api=new ae(this.apiLocation,`ClientComponent(${n}/${this.instanceId})`);this.client_api.logger=this.log;this.client_api.debug=true;this.client_api.addEventListener("authentication",this.boundProcessAuthenticationEvent);this.client_api.addEventListener("session",this.boundProcessStatusEvent);this.client_api.addEventListener("configuration",this.boundProcessConfigurationEvent);this.client_api.addEventListener("telephony",this.boundProcessTelephonyEvent);this.authenticationFailure.emit({count:this.authenticationCount,message:"initialising"})}disconnectedCallback(){this.log.debug(": disconnectedCallback");document.removeEventListener("visibilitychange",this.boundVisibilityEvent);this.client_api.removeEventListener("authentication",this.boundProcessAuthenticationEvent);this.client_api.removeEventListener("session",this.boundProcessStatusEvent);this.client_api.removeEventListener("configuration",this.boundProcessConfigurationEvent);this.client_api.removeEventListener("telephony",this.boundProcessTelephonyEvent);this.client_api.disconnect()}componentWillLoad(){this.log.debug(": componentWillLoad")}processVisibilityEvent(){this.log.debug(": processVisibilityEvent");this.transactionToggle=!this.transactionToggle}handleSecureFieldResetEvent(e){this.log.debug("secureFieldResetEvent: resetting ",e.detail);this.client_api.reset([e.detail]).then((()=>{this.log.debug("secureFieldResetEvent: reset ")})).catch((e=>{this.log.debug("secureFieldResetEvent: FAILED: ",e)}))}handleSubmitTransactionEvent(e){this.log.debug("submitTransactionEvent: ",e.detail);this.submitTransaction(e.detail)}handleResponseButtonEvent(e){this.log.debug("responseButtonEvent: ",e.detail);switch(e.detail){case"retryClearCVV":this.triggerAnotherTransaction(false,["cvv"]);break;case"retryClearSecure":this.triggerAnotherTransaction(false,["all"]);break;case"retryClearAll":this.triggerAnotherTransaction(true,["all"]);break;default:this.log.debug("responseButtonEvent: unknown action: ",e.detail)}}messageHandler(e){this.log.debug("messageHandler: popup return= ",e);if(e.origin!==window.origin)return;this.log.debug("messageHandler: origin matches")}currentStateWatcher(e,t){this.log.debug("currentStateWatcher",t," => ",e);if(e!==t){this.cancelTimeout();this.errorMessage=undefined}}watchAwaitActiveCall(e,t){this.log.debug("awaitActiveCall: ",t," => ",e)}watchCustomLogger(e,t){this.log.debug("customLogger: ",t," => ",e);if(e!==t){this.createLogger();this.client_api.logger=this.log}}async version(){return n}async triggerAnotherTransaction(e=true,t=["cvv"]){this.log.debug("Method: triggerAnotherTransaction resetTransactionDetails="+e+" resetCardFields="+JSON.stringify(t));if(this.currentState===p.Success||this.currentState===p.Failure){if(e){this._requestFields.clearNonSecureFields()}if(t&&t.length>0){await this.client_api.reset(t).catch((()=>{}))}this.currentState=p.Secured}else{this.log.debug("Method: triggerAnotherTransaction Incompatible state: ",this.currentState);throw new Error("Incompatible state: "+this.currentState)}}async submitAnotherTransaction(e){this.log.debug("submitAnotherTransaction: ");if(this.currentState===p.Success||this.currentState===p.Failure){this.submitTransaction(e);return true}else{this.log.debug("Method: submitAnotherTransaction Wrong state: ",this.currentState);return false}}async authenticate(e,t,s){this.log.debug("Method: authenticate");try{await this.client_api.authenticate(e,t,s)}catch(e){this.log.debug("Method: authenticate failed with error: ",e);throw e}}async logout(){this.log.debug("Method: logout");this.client_api.logout().then((()=>{this.log.debug("Method: logout success");this.currentState=p.NotAuthenticated;this.loggedOut.emit(true)})).catch((e=>{this.log.debug("Method: logout failed with error: "+e)}))}async secure(){this.log.debug("Method: secure");const e=this.switchHint?{switch_hint:this.switchHint}:{};await this.client_api.secure(e)}async release(){this.log.debug("Method: release");await this.client_api.release()}async updateTelephony(e){this.log.debug(": updateTelephony: ",e);return this.client_api.telephony(e)}async updateRequestFields(e){e(this._requestFields);this.generateConfigurationChangedEvent();this.transactionToggle=!this.transactionToggle}async updateSessionRequestFields(e){e(this._requestFields.session);this.generateConfigurationChangedEvent();this.transactionToggle=!this.transactionToggle}async updateTransactionRequestFields(e){e(this._requestFields.transaction);this.generateConfigurationChangedEvent();this.transactionToggle=!this.transactionToggle}async updateResponseFields(e){e(this._responseFields.defaults);this.generateConfigurationChangedEvent();this.transactionToggle=!this.transactionToggle}processAuthenticationEvent(e){if(e.success){this.log.debug("Authentication Success message: ",e);this.currentState=p.Idle;this.authenticationSuccess.emit()}else{this.log.debug("Authentication Failure message: ",JSON.stringify(e));this.handleAuthenticationFailure(e.reason,e.code)}}processConfigurationEvent(e){this.log.debug(": processConfigurationEvent: ",e);const t=e.detail.settings;if(typeof t?.show_gateways!=="undefined"){this._requestFields.instance.gatewayName.hidden=!(t.show_gateways===true)}if(e.detail.gateways){this._requestFields.instance.gatewayName.possibleValues={...e.detail.gateways}}if(t?.request_fields){const{_transactionUpdate:e,_sessionUpdate:s,...i}=t.request_fields;Object.entries(i).forEach((([t,i])=>{if(!this._requestFields.fieldNames.includes(t)){this._requestFields.fieldNames.push(t)}let r=this._requestFields.instance;if(s){r=this._requestFields.session}else if(e){r=this._requestFields.transaction}let n=r[t];if(n){Object.entries(i).forEach((([e,t])=>{n[e]=t}))}}))}if(t?.response_fields){this._responseFields=new oe(o(he,t.response_fields))}this.generateConfigurationChangedEvent();this.transactionToggle=!this.transactionToggle}generateConfigurationChangedEvent(){this.configurationChanged.emit({requestFields:this._requestFields.calculatedFields(),responseFields:this._responseFields.calculatedFields()})}processStatusEvent(e){this.log.debug(": processStatusEvent: ",e);switch(e.state){case"securing":if(this.currentState===p.Idle){this.currentState=p.Securing;this.startTimeout(le,"Timeout: Securing Call")}else if(this.currentState===p.Securing){this.log.debug(">>>> getting duplicate state: ",this.currentState)}else{this.log.error(">>>> ERROR: attempting to secure while in state: ",this.currentState)}break;case"collection":if(e.call_data.state==="secured"){if(this.currentState===p.Securing||this.currentState===p.Idle){this.currentState=p.Secured;this.callSecured.emit(true)}}this.secureData=e.secure_data;this.currentSession=e.session;this._requestFields.processSecureData(e.secure_data);this.transactionToggle=!this.transactionToggle;break;case"transaction":if(this.currentState!==p.Submitting&&this.currentState!==p.Success&&this.currentState!==p.Failure){this.currentState=p.Secured;this.callSecured.emit(true)}switch(e.transaction_data.state){case"submitting":this.transactionSubmitting.emit({...e.transaction_data,secureData:e.secure_data,session:e.session});this.currentState=p.Submitting;break;case"success":this.cancelTimeout();this._responseFields.processResponse(e.transaction_data);this.transactionSuccess.emit({...e.transaction_data,secureData:e.secure_data,session:e.session});this.currentState=p.Success;break;case"failure":this.cancelTimeout();this._responseFields.processResponse(e.transaction_data);this.transactionFailure.emit({...e.transaction_data,secureData:e.secure_data,session:e.session});this.currentState=p.Failure;break;default:this.log.debug(">>>> processStatusEvent: unknown transaction state:",e.transaction_data.state);break}break;case"ended":this.currentState=p.Idle;this._requestFields.resetSession();this._requestFields.resetTransaction();this.currentSession=undefined;this.secureData=undefined;this.callSecured.emit(false);if(e.call_data?.error){this.errorMessage=e.call_data.error;this.callEnded.emit(e.call_data.error)}else{this.callEnded.emit("call ended successfully")}break;default:this.log.debug("unknown state:"+e.state)}}processTelephonyEvent(e){this.cancelTimeout();this.log.debug(": processTelephonyEvent: ",e);switch(e.command){case"hold":this.telephonyHold.emit({session:e.session});break;case"recover":this.telephonyRecover.emit({session:e.session});break;case"leg_a":this.telephonyLegA.emit({session:e.session,dnis:e.dnis});break;case"leg_b":this.telephonyLegB.emit({session:e.session,dnis:e.dnis});break;case"validate":this.telephonyValidate.emit({session:e.session});break;default:this.log.debug(": processTelephonyEvent: unknown telephony command: ",e.command)}}handleAuthenticationFailure(e,t){this.log.debug(": intAuthenticationFailureHandler: Received the custom intAuthenticationFailure event: ",t,":",e);this.currentState=p.NotAuthenticated;switch(t){case 0:break;case 401:this.errorMessage="Unauthorised. Please attempt to log in again. Ensure that your browser is not in incognito mode";break;case 403:this.errorMessage="Configuration error. Please contact your administrator";break;default:this.errorMessage=t?t+":"+e:e}this.authenticationCount++;if(this.authenticationCount>ue){this.errorMessage="Unable to connect to the server. Please contact your administrator"}else{this.authenticationFailure.emit({count:this.authenticationCount,message:this.errorMessage})}this.log.debug(": intAuthenticationFailureHandler: ",this.errorMessage)}submitTransaction(e){this.log.debug("submitTransaction: eventData: "+JSON.stringify(e));this.startTimeout(ce,"Timeout: Processing Transaction");this.currentState=p.Submitting;this.client_api.submit(e).then((()=>{this.transactionSubmitted.emit(e)})).catch((t=>{this.log.debug("submitTransaction: error: "+t.message+"("+t.code+")");const s={state:"failure",request:e,response:{error_message:t.message,error_code:t.code},secureData:this.secureData,session:this.currentSession};this.currentState=p.Failure;this.transactionFailure.emit(s);this.errorMessage="Submit Response: "+t.message+" ("+t.code+")"}))}startTimeout(e,t){this.timeoutId=window.setTimeout((()=>{this.log.debug(">>>> Firing timeout : currentState:",this.currentState," destinationState:");this.errorMessage=t;this.client_api.connect()}),e);this.log.debug(">>>> Starting timeout id:",this.timeoutId," currentState:",this.currentState)}cancelTimeout(){if(this.timeoutId){this.log.debug(">>>> Canceling timeout id:",this.timeoutId," currentState:",this.currentState);clearTimeout(this.timeoutId);this.timeoutId=undefined}}renderResponseFields(e){const t=this._responseFields.asComponentChildren(e);if(!this.displayTransactionResult)return null;return s("form",{class:"response-form"},s("div",{class:"response-result-container"},s("p",null,e?"Transaction Accepted":"Transaction Declined")),s("div",{class:"response-field-container"},t.map((e=>{const t="securecall-response-"+e.component;return s(t,{id:e.name,"field-name":e.name,label:e.label,value:e.value})}))))}currentStateRender(){switch(this.currentState){case p.NotAuthenticated:return null;case p.Idle:if(this.hideSecureButton)return null;else return s("div",{class:"secure-form"},s("p",{class:"component-text"}," "),this.awaitActiveCall?s("button",{type:"button",class:"component-button",disabled:true},"Awaiting Active Call"):s("button",{type:"button",class:"component-button",onClick:()=>this.secure()},"Press to Secure"));case p.Securing:return s("form",null,s("div",{class:"component-field-container"},s("div",{class:"loading-spinner"},s("div",{class:"spinner-circle"}))));case p.Secured:return s("securecall-transaction",{id:"transaction",transactionToggle:this.transactionToggle,fieldData:this._requestFields,ref:e=>this.transactionElement=e});case p.Submitting:return s("div",{class:"component-field-container"},s("div",{class:"loading-spinner"},s("div",{class:"spinner-circle"})));case p.Failure:return this.renderResponseFields(false);case p.Success:return this.renderResponseFields(true);default:return s("form",null,s("div",{class:"component-field-container"},s("p",null," ",this.currentState)))}}renderErrorMessage(){if(this.errorMessage){const e=this.errorMessage;return s("div",{class:"component-field-container"},s("p",null,e))}return null}render(){return this.currentState!==p.NotAuthenticated?s(i,null,s("div",{class:`theme-${this.theme}`},this.currentStateRender(),this.renderErrorMessage())):null}static get watchers(){return{currentState:["currentStateWatcher"],awaitActiveCall:["watchAwaitActiveCall"],customLogger:["watchCustomLogger"]}}};fe.style=de;export{fe as securecall_client};
//# sourceMappingURL=p-efec3bde.entry.js.map