"use strict";(()=>{var Nd=Object.create;var yn=Object.defineProperty;var Cd=Object.getOwnPropertyDescriptor;var Pd=Object.getOwnPropertyNames;var wd=Object.getPrototypeOf,Rd=Object.prototype.hasOwnProperty;var fi=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var Sa=(t,e)=>()=>(t&&(e=t(t=0)),e);var z=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),hi=(t,e)=>{for(var r in e)yn(t,r,{get:e[r],enumerable:!0})},yi=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Pd(e))!Rd.call(t,i)&&i!==r&&yn(t,i,{get:()=>e[i],enumerable:!(n=Cd(e,i))||n.enumerable});return t};var ht=(t,e,r)=>(r=t!=null?Nd(wd(t)):{},yi(e||!t||!t.__esModule?yn(r,"default",{value:t,enumerable:!0}):r,t)),ke=t=>yi(yn({},"__esModule",{value:!0}),t);var Me={};hi(Me,{__addDisposableResource:()=>Mi,__assign:()=>mn,__asyncDelegator:()=>Ni,__asyncGenerator:()=>vi,__asyncValues:()=>Ci,__await:()=>sr,__awaiter:()=>Ti,__classPrivateFieldGet:()=>Li,__classPrivateFieldIn:()=>ki,__classPrivateFieldSet:()=>Di,__createBinding:()=>_n,__decorate:()=>_i,__disposeResources:()=>Ki,__esDecorate:()=>Ld,__exportStar:()=>Ai,__extends:()=>mi,__generator:()=>Si,__importDefault:()=>Ri,__importStar:()=>wi,__makeTemplateObject:()=>Pi,__metadata:()=>bi,__param:()=>Ei,__propKey:()=>kd,__read:()=>Oa,__rest:()=>gi,__runInitializers:()=>Dd,__setFunctionName:()=>Md,__spread:()=>Oi,__spreadArray:()=>Ii,__spreadArrays:()=>xi,__values:()=>gn,default:()=>Fd});function mi(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");Aa(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}function gi(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(t,n[i])&&(r[n[i]]=t[n[i]]);return r}function _i(t,e,r,n){var i=arguments.length,s=i<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,r):n,p;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(t,e,r,n);else for(var h=t.length-1;h>=0;h--)(p=t[h])&&(s=(i<3?p(s):i>3?p(e,r,s):p(e,r))||s);return i>3&&s&&Object.defineProperty(e,r,s),s}function Ei(t,e){return function(r,n){e(r,n,t)}}function Ld(t,e,r,n,i,s){function p(Ie){if(Ie!==void 0&&typeof Ie!="function")throw new TypeError("Function expected");return Ie}for(var h=n.kind,b=h==="getter"?"get":h==="setter"?"set":"value",x=!e&&t?n.static?t:t.prototype:null,R=e||(x?Object.getOwnPropertyDescriptor(x,n.name):{}),K,V=!1,H=r.length-1;H>=0;H--){var le={};for(var me in n)le[me]=me==="access"?{}:n[me];for(var me in n.access)le.access[me]=n.access[me];le.addInitializer=function(Ie){if(V)throw new TypeError("Cannot add initializers after decoration has completed");s.push(p(Ie||null))};var Ae=(0,r[H])(h==="accessor"?{get:R.get,set:R.set}:R[b],le);if(h==="accessor"){if(Ae===void 0)continue;if(Ae===null||typeof Ae!="object")throw new TypeError("Object expected");(K=p(Ae.get))&&(R.get=K),(K=p(Ae.set))&&(R.set=K),(K=p(Ae.init))&&i.unshift(K)}else(K=p(Ae))&&(h==="field"?i.unshift(K):R[b]=K)}x&&Object.defineProperty(x,n.name,R),V=!0}function Dd(t,e,r){for(var n=arguments.length>2,i=0;i<e.length;i++)r=n?e[i].call(t,r):e[i].call(t);return n?r:void 0}function kd(t){return typeof t=="symbol"?t:"".concat(t)}function Md(t,e,r){return typeof e=="symbol"&&(e=e.description?"[".concat(e.description,"]"):""),Object.defineProperty(t,"name",{configurable:!0,value:r?"".concat(r," ",e):e})}function bi(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function Ti(t,e,r,n){function i(s){return s instanceof r?s:new r(function(p){p(s)})}return new(r||(r=Promise))(function(s,p){function h(R){try{x(n.next(R))}catch(K){p(K)}}function b(R){try{x(n.throw(R))}catch(K){p(K)}}function x(R){R.done?s(R.value):i(R.value).then(h,b)}x((n=n.apply(t,e||[])).next())})}function Si(t,e){var r={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},n,i,s,p=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return p.next=h(0),p.throw=h(1),p.return=h(2),typeof Symbol=="function"&&(p[Symbol.iterator]=function(){return this}),p;function h(x){return function(R){return b([x,R])}}function b(x){if(n)throw new TypeError("Generator is already executing.");for(;p&&(p=0,x[0]&&(r=0)),r;)try{if(n=1,i&&(s=x[0]&2?i.return:x[0]?i.throw||((s=i.return)&&s.call(i),0):i.next)&&!(s=s.call(i,x[1])).done)return s;switch(i=0,s&&(x=[x[0]&2,s.value]),x[0]){case 0:case 1:s=x;break;case 4:return r.label++,{value:x[1],done:!1};case 5:r.label++,i=x[1],x=[0];continue;case 7:x=r.ops.pop(),r.trys.pop();continue;default:if(s=r.trys,!(s=s.length>0&&s[s.length-1])&&(x[0]===6||x[0]===2)){r=0;continue}if(x[0]===3&&(!s||x[1]>s[0]&&x[1]<s[3])){r.label=x[1];break}if(x[0]===6&&r.label<s[1]){r.label=s[1],s=x;break}if(s&&r.label<s[2]){r.label=s[2],r.ops.push(x);break}s[2]&&r.ops.pop(),r.trys.pop();continue}x=e.call(t,r)}catch(R){x=[6,R],i=0}finally{n=s=0}if(x[0]&5)throw x[1];return{value:x[0]?x[1]:void 0,done:!0}}}function Ai(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&_n(e,t,r)}function gn(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Oa(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),i,s=[],p;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)s.push(i.value)}catch(h){p={error:h}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(p)throw p.error}}return s}function Oi(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(Oa(arguments[e]));return t}function xi(){for(var t=0,e=0,r=arguments.length;e<r;e++)t+=arguments[e].length;for(var n=Array(t),i=0,e=0;e<r;e++)for(var s=arguments[e],p=0,h=s.length;p<h;p++,i++)n[i]=s[p];return n}function Ii(t,e,r){if(r||arguments.length===2)for(var n=0,i=e.length,s;n<i;n++)(s||!(n in e))&&(s||(s=Array.prototype.slice.call(e,0,n)),s[n]=e[n]);return t.concat(s||Array.prototype.slice.call(e))}function sr(t){return this instanceof sr?(this.v=t,this):new sr(t)}function vi(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=r.apply(t,e||[]),i,s=[];return i=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),h("next"),h("throw"),h("return",p),i[Symbol.asyncIterator]=function(){return this},i;function p(H){return function(le){return Promise.resolve(le).then(H,K)}}function h(H,le){n[H]&&(i[H]=function(me){return new Promise(function(Ae,Ie){s.push([H,me,Ae,Ie])>1||b(H,me)})},le&&(i[H]=le(i[H])))}function b(H,le){try{x(n[H](le))}catch(me){V(s[0][3],me)}}function x(H){H.value instanceof sr?Promise.resolve(H.value.v).then(R,K):V(s[0][2],H)}function R(H){b("next",H)}function K(H){b("throw",H)}function V(H,le){H(le),s.shift(),s.length&&b(s[0][0],s[0][1])}}function Ni(t){var e,r;return e={},n("next"),n("throw",function(i){throw i}),n("return"),e[Symbol.iterator]=function(){return this},e;function n(i,s){e[i]=t[i]?function(p){return(r=!r)?{value:sr(t[i](p)),done:!1}:s?s(p):p}:s}}function Ci(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof gn=="function"?gn(t):t[Symbol.iterator](),r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r);function n(s){r[s]=t[s]&&function(p){return new Promise(function(h,b){p=t[s](p),i(h,b,p.done,p.value)})}}function i(s,p,h,b){Promise.resolve(b).then(function(x){s({value:x,done:h})},p)}}function Pi(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function wi(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&_n(e,t,r);return Kd(e,t),e}function Ri(t){return t&&t.__esModule?t:{default:t}}function Li(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)}function Di(t,e,r,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!i:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(t,r):i?i.value=r:e.set(t,r),r}function ki(t,e){if(e===null||typeof e!="object"&&typeof e!="function")throw new TypeError("Cannot use 'in' operator on non-object");return typeof t=="function"?e===t:t.has(e)}function Mi(t,e,r){if(e!=null){if(typeof e!="object"&&typeof e!="function")throw new TypeError("Object expected.");var n,i;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=e[Symbol.asyncDispose]}if(n===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=e[Symbol.dispose],r&&(i=n)}if(typeof n!="function")throw new TypeError("Object not disposable.");i&&(n=function(){try{i.call(this)}catch(s){return Promise.reject(s)}}),t.stack.push({value:e,dispose:n,async:r})}else r&&t.stack.push({async:!0});return e}function Ki(t){function e(s){t.error=t.hasError?new Ud(s,t.error,"An error was suppressed during disposal."):s,t.hasError=!0}var r,n=0;function i(){for(;r=t.stack.pop();)try{if(!r.async&&n===1)return n=0,t.stack.push(r),Promise.resolve().then(i);if(r.dispose){var s=r.dispose.call(r.value);if(r.async)return n|=2,Promise.resolve(s).then(i,function(p){return e(p),i()})}else n|=1}catch(p){e(p)}if(n===1)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}return i()}var Aa,mn,_n,Kd,Ud,Fd,Ke=Sa(()=>{Aa=function(t,e){return Aa=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n}||function(r,n){for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(r[i]=n[i])},Aa(t,e)};mn=function(){return mn=Object.assign||function(e){for(var r,n=1,i=arguments.length;n<i;n++){r=arguments[n];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(e[s]=r[s])}return e},mn.apply(this,arguments)};_n=Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]});Kd=Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e};Ud=typeof SuppressedError=="function"?SuppressedError:function(t,e,r){var n=new Error(r);return n.name="SuppressedError",n.error=t,n.suppressed=e,n};Fd={__extends:mi,__assign:mn,__rest:gi,__decorate:_i,__param:Ei,__metadata:bi,__awaiter:Ti,__generator:Si,__createBinding:_n,__exportStar:Ai,__values:gn,__read:Oa,__spread:Oi,__spreadArrays:xi,__spreadArray:Ii,__await:sr,__asyncGenerator:vi,__asyncDelegator:Ni,__asyncValues:Ci,__makeTemplateObject:Pi,__importStar:wi,__importDefault:Ri,__classPrivateFieldGet:Li,__classPrivateFieldSet:Di,__classPrivateFieldIn:ki,__addDisposableResource:Mi,__disposeResources:Ki}});var xa=z(dr=>{"use strict";Object.defineProperty(dr,"__esModule",{value:!0});dr.HexToNumber=dr.NumberToHex=void 0;dr.NumberToHex={0:"00",1:"01",2:"02",3:"03",4:"04",5:"05",6:"06",7:"07",8:"08",9:"09",10:"0A",11:"0B",12:"0C",13:"0D",14:"0E",15:"0F",16:"10",17:"11",18:"12",19:"13",20:"14",21:"15",22:"16",23:"17",24:"18",25:"19",26:"1A",27:"1B",28:"1C",29:"1D",30:"1E",31:"1F",32:"20",33:"21",34:"22",35:"23",36:"24",37:"25",38:"26",39:"27",40:"28",41:"29",42:"2A",43:"2B",44:"2C",45:"2D",46:"2E",47:"2F",48:"30",49:"31",50:"32",51:"33",52:"34",53:"35",54:"36",55:"37",56:"38",57:"39",58:"3A",59:"3B",60:"3C",61:"3D",62:"3E",63:"3F",64:"40",65:"41",66:"42",67:"43",68:"44",69:"45",70:"46",71:"47",72:"48",73:"49",74:"4A",75:"4B",76:"4C",77:"4D",78:"4E",79:"4F",80:"50",81:"51",82:"52",83:"53",84:"54",85:"55",86:"56",87:"57",88:"58",89:"59",90:"5A",91:"5B",92:"5C",93:"5D",94:"5E",95:"5F",96:"60",97:"61",98:"62",99:"63",100:"64",101:"65",102:"66",103:"67",104:"68",105:"69",106:"6A",107:"6B",108:"6C",109:"6D",110:"6E",111:"6F",112:"70",113:"71",114:"72",115:"73",116:"74",117:"75",118:"76",119:"77",120:"78",121:"79",122:"7A",123:"7B",124:"7C",125:"7D",126:"7E",127:"7F",128:"80",129:"81",130:"82",131:"83",132:"84",133:"85",134:"86",135:"87",136:"88",137:"89",138:"8A",139:"8B",140:"8C",141:"8D",142:"8E",143:"8F",144:"90",145:"91",146:"92",147:"93",148:"94",149:"95",150:"96",151:"97",152:"98",153:"99",154:"9A",155:"9B",156:"9C",157:"9D",158:"9E",159:"9F",160:"A0",161:"A1",162:"A2",163:"A3",164:"A4",165:"A5",166:"A6",167:"A7",168:"A8",169:"A9",170:"AA",171:"AB",172:"AC",173:"AD",174:"AE",175:"AF",176:"B0",177:"B1",178:"B2",179:"B3",180:"B4",181:"B5",182:"B6",183:"B7",184:"B8",185:"B9",186:"BA",187:"BB",188:"BC",189:"BD",190:"BE",191:"BF",192:"C0",193:"C1",194:"C2",195:"C3",196:"C4",197:"C5",198:"C6",199:"C7",200:"C8",201:"C9",202:"CA",203:"CB",204:"CC",205:"CD",206:"CE",207:"CF",208:"D0",209:"D1",210:"D2",211:"D3",212:"D4",213:"D5",214:"D6",215:"D7",216:"D8",217:"D9",218:"DA",219:"DB",220:"DC",221:"DD",222:"DE",223:"DF",224:"E0",225:"E1",226:"E2",227:"E3",228:"E4",229:"E5",230:"E6",231:"E7",232:"E8",233:"E9",234:"EA",235:"EB",236:"EC",237:"ED",238:"EE",239:"EF",240:"F0",241:"F1",242:"F2",243:"F3",244:"F4",245:"F5",246:"F6",247:"F7",248:"F8",249:"F9",250:"FA",251:"FB",252:"FC",253:"FD",254:"FE",255:"FF"};dr.HexToNumber={"00":0,"01":1,"02":2,"03":3,"04":4,"05":5,"06":6,"07":7,"08":8,"09":9,"0A":10,"0B":11,"0C":12,"0D":13,"0E":14,"0F":15,10:16,11:17,12:18,13:19,14:20,15:21,16:22,17:23,18:24,19:25,"1A":26,"1B":27,"1C":28,"1D":29,"1E":30,"1F":31,20:32,21:33,22:34,23:35,24:36,25:37,26:38,27:39,28:40,29:41,"2A":42,"2B":43,"2C":44,"2D":45,"2E":46,"2F":47,30:48,31:49,32:50,33:51,34:52,35:53,36:54,37:55,38:56,39:57,"3A":58,"3B":59,"3C":60,"3D":61,"3E":62,"3F":63,40:64,41:65,42:66,43:67,44:68,45:69,46:70,47:71,48:72,49:73,"4A":74,"4B":75,"4C":76,"4D":77,"4E":78,"4F":79,50:80,51:81,52:82,53:83,54:84,55:85,56:86,57:87,58:88,59:89,"5A":90,"5B":91,"5C":92,"5D":93,"5E":94,"5F":95,60:96,61:97,62:98,63:99,64:100,65:101,66:102,67:103,68:104,69:105,"6A":106,"6B":107,"6C":108,"6D":109,"6E":110,"6F":111,70:112,71:113,72:114,73:115,74:116,75:117,76:118,77:119,78:120,79:121,"7A":122,"7B":123,"7C":124,"7D":125,"7E":126,"7F":127,80:128,81:129,82:130,83:131,84:132,85:133,86:134,87:135,88:136,89:137,"8A":138,"8B":139,"8C":140,"8D":141,"8E":142,"8F":143,90:144,91:145,92:146,93:147,94:148,95:149,96:150,97:151,98:152,99:153,"9A":154,"9B":155,"9C":156,"9D":157,"9E":158,"9F":159,A0:160,A1:161,A2:162,A3:163,A4:164,A5:165,A6:166,A7:167,A8:168,A9:169,AA:170,AB:171,AC:172,AD:173,AE:174,AF:175,B0:176,B1:177,B2:178,B3:179,B4:180,B5:181,B6:182,B7:183,B8:184,B9:185,BA:186,BB:187,BC:188,BD:189,BE:190,BF:191,C0:192,C1:193,C2:194,C3:195,C4:196,C5:197,C6:198,C7:199,C8:200,C9:201,CA:202,CB:203,CC:204,CD:205,CE:206,CF:207,D0:208,D1:209,D2:210,D3:211,D4:212,D5:213,D6:214,D7:215,D8:216,D9:217,DA:218,DB:219,DC:220,DD:221,DE:222,DF:223,E0:224,E1:225,E2:226,E3:227,E4:228,E5:229,E6:230,E7:231,E8:232,E9:233,EA:234,EB:235,EC:236,ED:237,EE:238,EF:239,F0:240,F1:241,F2:242,F3:243,F4:244,F5:245,F6:246,F7:247,F8:248,F9:249,FA:250,FB:251,FC:252,FD:253,FE:254,FF:255}});var Ur=z(()=>{});var qt=z((Ku,En)=>{(function(t){"use strict";var e=function(o){var l,d=new Float64Array(16);if(o)for(l=0;l<o.length;l++)d[l]=o[l];return d},r=function(){throw new Error("no PRNG")},n=new Uint8Array(16),i=new Uint8Array(32);i[0]=9;var s=e(),p=e([1]),h=e([56129,1]),b=e([30883,4953,19914,30187,55467,16705,2637,112,59544,30585,16505,36039,65139,11119,27886,20995]),x=e([61785,9906,39828,60374,45398,33411,5274,224,53552,61171,33010,6542,64743,22239,55772,9222]),R=e([54554,36645,11616,51542,42930,38181,51040,26924,56412,64982,57905,49316,21502,52590,14035,8553]),K=e([26200,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214]),V=e([41136,18958,6951,50414,58488,44335,6150,12099,55207,15867,153,11085,57099,20417,9344,11139]);function H(o,l,d,a){o[l]=d>>24&255,o[l+1]=d>>16&255,o[l+2]=d>>8&255,o[l+3]=d&255,o[l+4]=a>>24&255,o[l+5]=a>>16&255,o[l+6]=a>>8&255,o[l+7]=a&255}function le(o,l,d,a,c){var f,y=0;for(f=0;f<c;f++)y|=o[l+f]^d[a+f];return(1&y-1>>>8)-1}function me(o,l,d,a){return le(o,l,d,a,16)}function Ae(o,l,d,a){return le(o,l,d,a,32)}function Ie(o,l,d,a){for(var c=a[0]&255|(a[1]&255)<<8|(a[2]&255)<<16|(a[3]&255)<<24,f=d[0]&255|(d[1]&255)<<8|(d[2]&255)<<16|(d[3]&255)<<24,y=d[4]&255|(d[5]&255)<<8|(d[6]&255)<<16|(d[7]&255)<<24,S=d[8]&255|(d[9]&255)<<8|(d[10]&255)<<16|(d[11]&255)<<24,v=d[12]&255|(d[13]&255)<<8|(d[14]&255)<<16|(d[15]&255)<<24,M=a[4]&255|(a[5]&255)<<8|(a[6]&255)<<16|(a[7]&255)<<24,C=l[0]&255|(l[1]&255)<<8|(l[2]&255)<<16|(l[3]&255)<<24,oe=l[4]&255|(l[5]&255)<<8|(l[6]&255)<<16|(l[7]&255)<<24,w=l[8]&255|(l[9]&255)<<8|(l[10]&255)<<16|(l[11]&255)<<24,Y=l[12]&255|(l[13]&255)<<8|(l[14]&255)<<16|(l[15]&255)<<24,G=a[8]&255|(a[9]&255)<<8|(a[10]&255)<<16|(a[11]&255)<<24,J=d[16]&255|(d[17]&255)<<8|(d[18]&255)<<16|(d[19]&255)<<24,W=d[20]&255|(d[21]&255)<<8|(d[22]&255)<<16|(d[23]&255)<<24,$=d[24]&255|(d[25]&255)<<8|(d[26]&255)<<16|(d[27]&255)<<24,q=d[28]&255|(d[29]&255)<<8|(d[30]&255)<<16|(d[31]&255)<<24,j=a[12]&255|(a[13]&255)<<8|(a[14]&255)<<16|(a[15]&255)<<24,L=c,U=f,P=y,D=S,k=v,N=M,_=C,E=oe,O=w,T=Y,A=G,I=J,B=W,Z=$,X=q,Q=j,u,te=0;te<20;te+=2)u=L+B|0,k^=u<<7|u>>>25,u=k+L|0,O^=u<<9|u>>>23,u=O+k|0,B^=u<<13|u>>>19,u=B+O|0,L^=u<<18|u>>>14,u=N+U|0,T^=u<<7|u>>>25,u=T+N|0,Z^=u<<9|u>>>23,u=Z+T|0,U^=u<<13|u>>>19,u=U+Z|0,N^=u<<18|u>>>14,u=A+_|0,X^=u<<7|u>>>25,u=X+A|0,P^=u<<9|u>>>23,u=P+X|0,_^=u<<13|u>>>19,u=_+P|0,A^=u<<18|u>>>14,u=Q+I|0,D^=u<<7|u>>>25,u=D+Q|0,E^=u<<9|u>>>23,u=E+D|0,I^=u<<13|u>>>19,u=I+E|0,Q^=u<<18|u>>>14,u=L+D|0,U^=u<<7|u>>>25,u=U+L|0,P^=u<<9|u>>>23,u=P+U|0,D^=u<<13|u>>>19,u=D+P|0,L^=u<<18|u>>>14,u=N+k|0,_^=u<<7|u>>>25,u=_+N|0,E^=u<<9|u>>>23,u=E+_|0,k^=u<<13|u>>>19,u=k+E|0,N^=u<<18|u>>>14,u=A+T|0,I^=u<<7|u>>>25,u=I+A|0,O^=u<<9|u>>>23,u=O+I|0,T^=u<<13|u>>>19,u=T+O|0,A^=u<<18|u>>>14,u=Q+X|0,B^=u<<7|u>>>25,u=B+Q|0,Z^=u<<9|u>>>23,u=Z+B|0,X^=u<<13|u>>>19,u=X+Z|0,Q^=u<<18|u>>>14;L=L+c|0,U=U+f|0,P=P+y|0,D=D+S|0,k=k+v|0,N=N+M|0,_=_+C|0,E=E+oe|0,O=O+w|0,T=T+Y|0,A=A+G|0,I=I+J|0,B=B+W|0,Z=Z+$|0,X=X+q|0,Q=Q+j|0,o[0]=L>>>0&255,o[1]=L>>>8&255,o[2]=L>>>16&255,o[3]=L>>>24&255,o[4]=U>>>0&255,o[5]=U>>>8&255,o[6]=U>>>16&255,o[7]=U>>>24&255,o[8]=P>>>0&255,o[9]=P>>>8&255,o[10]=P>>>16&255,o[11]=P>>>24&255,o[12]=D>>>0&255,o[13]=D>>>8&255,o[14]=D>>>16&255,o[15]=D>>>24&255,o[16]=k>>>0&255,o[17]=k>>>8&255,o[18]=k>>>16&255,o[19]=k>>>24&255,o[20]=N>>>0&255,o[21]=N>>>8&255,o[22]=N>>>16&255,o[23]=N>>>24&255,o[24]=_>>>0&255,o[25]=_>>>8&255,o[26]=_>>>16&255,o[27]=_>>>24&255,o[28]=E>>>0&255,o[29]=E>>>8&255,o[30]=E>>>16&255,o[31]=E>>>24&255,o[32]=O>>>0&255,o[33]=O>>>8&255,o[34]=O>>>16&255,o[35]=O>>>24&255,o[36]=T>>>0&255,o[37]=T>>>8&255,o[38]=T>>>16&255,o[39]=T>>>24&255,o[40]=A>>>0&255,o[41]=A>>>8&255,o[42]=A>>>16&255,o[43]=A>>>24&255,o[44]=I>>>0&255,o[45]=I>>>8&255,o[46]=I>>>16&255,o[47]=I>>>24&255,o[48]=B>>>0&255,o[49]=B>>>8&255,o[50]=B>>>16&255,o[51]=B>>>24&255,o[52]=Z>>>0&255,o[53]=Z>>>8&255,o[54]=Z>>>16&255,o[55]=Z>>>24&255,o[56]=X>>>0&255,o[57]=X>>>8&255,o[58]=X>>>16&255,o[59]=X>>>24&255,o[60]=Q>>>0&255,o[61]=Q>>>8&255,o[62]=Q>>>16&255,o[63]=Q>>>24&255}function Pr(o,l,d,a){for(var c=a[0]&255|(a[1]&255)<<8|(a[2]&255)<<16|(a[3]&255)<<24,f=d[0]&255|(d[1]&255)<<8|(d[2]&255)<<16|(d[3]&255)<<24,y=d[4]&255|(d[5]&255)<<8|(d[6]&255)<<16|(d[7]&255)<<24,S=d[8]&255|(d[9]&255)<<8|(d[10]&255)<<16|(d[11]&255)<<24,v=d[12]&255|(d[13]&255)<<8|(d[14]&255)<<16|(d[15]&255)<<24,M=a[4]&255|(a[5]&255)<<8|(a[6]&255)<<16|(a[7]&255)<<24,C=l[0]&255|(l[1]&255)<<8|(l[2]&255)<<16|(l[3]&255)<<24,oe=l[4]&255|(l[5]&255)<<8|(l[6]&255)<<16|(l[7]&255)<<24,w=l[8]&255|(l[9]&255)<<8|(l[10]&255)<<16|(l[11]&255)<<24,Y=l[12]&255|(l[13]&255)<<8|(l[14]&255)<<16|(l[15]&255)<<24,G=a[8]&255|(a[9]&255)<<8|(a[10]&255)<<16|(a[11]&255)<<24,J=d[16]&255|(d[17]&255)<<8|(d[18]&255)<<16|(d[19]&255)<<24,W=d[20]&255|(d[21]&255)<<8|(d[22]&255)<<16|(d[23]&255)<<24,$=d[24]&255|(d[25]&255)<<8|(d[26]&255)<<16|(d[27]&255)<<24,q=d[28]&255|(d[29]&255)<<8|(d[30]&255)<<16|(d[31]&255)<<24,j=a[12]&255|(a[13]&255)<<8|(a[14]&255)<<16|(a[15]&255)<<24,L=c,U=f,P=y,D=S,k=v,N=M,_=C,E=oe,O=w,T=Y,A=G,I=J,B=W,Z=$,X=q,Q=j,u,te=0;te<20;te+=2)u=L+B|0,k^=u<<7|u>>>25,u=k+L|0,O^=u<<9|u>>>23,u=O+k|0,B^=u<<13|u>>>19,u=B+O|0,L^=u<<18|u>>>14,u=N+U|0,T^=u<<7|u>>>25,u=T+N|0,Z^=u<<9|u>>>23,u=Z+T|0,U^=u<<13|u>>>19,u=U+Z|0,N^=u<<18|u>>>14,u=A+_|0,X^=u<<7|u>>>25,u=X+A|0,P^=u<<9|u>>>23,u=P+X|0,_^=u<<13|u>>>19,u=_+P|0,A^=u<<18|u>>>14,u=Q+I|0,D^=u<<7|u>>>25,u=D+Q|0,E^=u<<9|u>>>23,u=E+D|0,I^=u<<13|u>>>19,u=I+E|0,Q^=u<<18|u>>>14,u=L+D|0,U^=u<<7|u>>>25,u=U+L|0,P^=u<<9|u>>>23,u=P+U|0,D^=u<<13|u>>>19,u=D+P|0,L^=u<<18|u>>>14,u=N+k|0,_^=u<<7|u>>>25,u=_+N|0,E^=u<<9|u>>>23,u=E+_|0,k^=u<<13|u>>>19,u=k+E|0,N^=u<<18|u>>>14,u=A+T|0,I^=u<<7|u>>>25,u=I+A|0,O^=u<<9|u>>>23,u=O+I|0,T^=u<<13|u>>>19,u=T+O|0,A^=u<<18|u>>>14,u=Q+X|0,B^=u<<7|u>>>25,u=B+Q|0,Z^=u<<9|u>>>23,u=Z+B|0,X^=u<<13|u>>>19,u=X+Z|0,Q^=u<<18|u>>>14;o[0]=L>>>0&255,o[1]=L>>>8&255,o[2]=L>>>16&255,o[3]=L>>>24&255,o[4]=N>>>0&255,o[5]=N>>>8&255,o[6]=N>>>16&255,o[7]=N>>>24&255,o[8]=A>>>0&255,o[9]=A>>>8&255,o[10]=A>>>16&255,o[11]=A>>>24&255,o[12]=Q>>>0&255,o[13]=Q>>>8&255,o[14]=Q>>>16&255,o[15]=Q>>>24&255,o[16]=_>>>0&255,o[17]=_>>>8&255,o[18]=_>>>16&255,o[19]=_>>>24&255,o[20]=E>>>0&255,o[21]=E>>>8&255,o[22]=E>>>16&255,o[23]=E>>>24&255,o[24]=O>>>0&255,o[25]=O>>>8&255,o[26]=O>>>16&255,o[27]=O>>>24&255,o[28]=T>>>0&255,o[29]=T>>>8&255,o[30]=T>>>16&255,o[31]=T>>>24&255}function Vt(o,l,d,a){Ie(o,l,d,a)}function Dt(o,l,d,a){Pr(o,l,d,a)}var $e=new Uint8Array([101,120,112,97,110,100,32,51,50,45,98,121,116,101,32,107]);function Gt(o,l,d,a,c,f,y){var S=new Uint8Array(16),v=new Uint8Array(64),M,C;for(C=0;C<16;C++)S[C]=0;for(C=0;C<8;C++)S[C]=f[C];for(;c>=64;){for(Vt(v,S,y,$e),C=0;C<64;C++)o[l+C]=d[a+C]^v[C];for(M=1,C=8;C<16;C++)M=M+(S[C]&255)|0,S[C]=M&255,M>>>=8;c-=64,l+=64,a+=64}if(c>0)for(Vt(v,S,y,$e),C=0;C<c;C++)o[l+C]=d[a+C]^v[C];return 0}function on(o,l,d,a,c){var f=new Uint8Array(16),y=new Uint8Array(64),S,v;for(v=0;v<16;v++)f[v]=0;for(v=0;v<8;v++)f[v]=a[v];for(;d>=64;){for(Vt(y,f,c,$e),v=0;v<64;v++)o[l+v]=y[v];for(S=1,v=8;v<16;v++)S=S+(f[v]&255)|0,f[v]=S&255,S>>>=8;d-=64,l+=64}if(d>0)for(Vt(y,f,c,$e),v=0;v<d;v++)o[l+v]=y[v];return 0}function wr(o,l,d,a,c){var f=new Uint8Array(32);Dt(f,a,c,$e);for(var y=new Uint8Array(8),S=0;S<8;S++)y[S]=a[S+16];return on(o,l,d,y,f)}function ar(o,l,d,a,c,f,y){var S=new Uint8Array(32);Dt(S,f,y,$e);for(var v=new Uint8Array(8),M=0;M<8;M++)v[M]=f[M+16];return Gt(o,l,d,a,c,v,S)}var kt=function(o){this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.leftover=0,this.fin=0;var l,d,a,c,f,y,S,v;l=o[0]&255|(o[1]&255)<<8,this.r[0]=l&8191,d=o[2]&255|(o[3]&255)<<8,this.r[1]=(l>>>13|d<<3)&8191,a=o[4]&255|(o[5]&255)<<8,this.r[2]=(d>>>10|a<<6)&7939,c=o[6]&255|(o[7]&255)<<8,this.r[3]=(a>>>7|c<<9)&8191,f=o[8]&255|(o[9]&255)<<8,this.r[4]=(c>>>4|f<<12)&255,this.r[5]=f>>>1&8190,y=o[10]&255|(o[11]&255)<<8,this.r[6]=(f>>>14|y<<2)&8191,S=o[12]&255|(o[13]&255)<<8,this.r[7]=(y>>>11|S<<5)&8065,v=o[14]&255|(o[15]&255)<<8,this.r[8]=(S>>>8|v<<8)&8191,this.r[9]=v>>>5&127,this.pad[0]=o[16]&255|(o[17]&255)<<8,this.pad[1]=o[18]&255|(o[19]&255)<<8,this.pad[2]=o[20]&255|(o[21]&255)<<8,this.pad[3]=o[22]&255|(o[23]&255)<<8,this.pad[4]=o[24]&255|(o[25]&255)<<8,this.pad[5]=o[26]&255|(o[27]&255)<<8,this.pad[6]=o[28]&255|(o[29]&255)<<8,this.pad[7]=o[30]&255|(o[31]&255)<<8};kt.prototype.blocks=function(o,l,d){for(var a=this.fin?0:2048,c,f,y,S,v,M,C,oe,w,Y,G,J,W,$,q,j,L,U,P,D=this.h[0],k=this.h[1],N=this.h[2],_=this.h[3],E=this.h[4],O=this.h[5],T=this.h[6],A=this.h[7],I=this.h[8],B=this.h[9],Z=this.r[0],X=this.r[1],Q=this.r[2],u=this.r[3],te=this.r[4],se=this.r[5],de=this.r[6],ee=this.r[7],ne=this.r[8],ae=this.r[9];d>=16;)c=o[l+0]&255|(o[l+1]&255)<<8,D+=c&8191,f=o[l+2]&255|(o[l+3]&255)<<8,k+=(c>>>13|f<<3)&8191,y=o[l+4]&255|(o[l+5]&255)<<8,N+=(f>>>10|y<<6)&8191,S=o[l+6]&255|(o[l+7]&255)<<8,_+=(y>>>7|S<<9)&8191,v=o[l+8]&255|(o[l+9]&255)<<8,E+=(S>>>4|v<<12)&8191,O+=v>>>1&8191,M=o[l+10]&255|(o[l+11]&255)<<8,T+=(v>>>14|M<<2)&8191,C=o[l+12]&255|(o[l+13]&255)<<8,A+=(M>>>11|C<<5)&8191,oe=o[l+14]&255|(o[l+15]&255)<<8,I+=(C>>>8|oe<<8)&8191,B+=oe>>>5|a,w=0,Y=w,Y+=D*Z,Y+=k*(5*ae),Y+=N*(5*ne),Y+=_*(5*ee),Y+=E*(5*de),w=Y>>>13,Y&=8191,Y+=O*(5*se),Y+=T*(5*te),Y+=A*(5*u),Y+=I*(5*Q),Y+=B*(5*X),w+=Y>>>13,Y&=8191,G=w,G+=D*X,G+=k*Z,G+=N*(5*ae),G+=_*(5*ne),G+=E*(5*ee),w=G>>>13,G&=8191,G+=O*(5*de),G+=T*(5*se),G+=A*(5*te),G+=I*(5*u),G+=B*(5*Q),w+=G>>>13,G&=8191,J=w,J+=D*Q,J+=k*X,J+=N*Z,J+=_*(5*ae),J+=E*(5*ne),w=J>>>13,J&=8191,J+=O*(5*ee),J+=T*(5*de),J+=A*(5*se),J+=I*(5*te),J+=B*(5*u),w+=J>>>13,J&=8191,W=w,W+=D*u,W+=k*Q,W+=N*X,W+=_*Z,W+=E*(5*ae),w=W>>>13,W&=8191,W+=O*(5*ne),W+=T*(5*ee),W+=A*(5*de),W+=I*(5*se),W+=B*(5*te),w+=W>>>13,W&=8191,$=w,$+=D*te,$+=k*u,$+=N*Q,$+=_*X,$+=E*Z,w=$>>>13,$&=8191,$+=O*(5*ae),$+=T*(5*ne),$+=A*(5*ee),$+=I*(5*de),$+=B*(5*se),w+=$>>>13,$&=8191,q=w,q+=D*se,q+=k*te,q+=N*u,q+=_*Q,q+=E*X,w=q>>>13,q&=8191,q+=O*Z,q+=T*(5*ae),q+=A*(5*ne),q+=I*(5*ee),q+=B*(5*de),w+=q>>>13,q&=8191,j=w,j+=D*de,j+=k*se,j+=N*te,j+=_*u,j+=E*Q,w=j>>>13,j&=8191,j+=O*X,j+=T*Z,j+=A*(5*ae),j+=I*(5*ne),j+=B*(5*ee),w+=j>>>13,j&=8191,L=w,L+=D*ee,L+=k*de,L+=N*se,L+=_*te,L+=E*u,w=L>>>13,L&=8191,L+=O*Q,L+=T*X,L+=A*Z,L+=I*(5*ae),L+=B*(5*ne),w+=L>>>13,L&=8191,U=w,U+=D*ne,U+=k*ee,U+=N*de,U+=_*se,U+=E*te,w=U>>>13,U&=8191,U+=O*u,U+=T*Q,U+=A*X,U+=I*Z,U+=B*(5*ae),w+=U>>>13,U&=8191,P=w,P+=D*ae,P+=k*ne,P+=N*ee,P+=_*de,P+=E*se,w=P>>>13,P&=8191,P+=O*te,P+=T*u,P+=A*Q,P+=I*X,P+=B*Z,w+=P>>>13,P&=8191,w=(w<<2)+w|0,w=w+Y|0,Y=w&8191,w=w>>>13,G+=w,D=Y,k=G,N=J,_=W,E=$,O=q,T=j,A=L,I=U,B=P,l+=16,d-=16;this.h[0]=D,this.h[1]=k,this.h[2]=N,this.h[3]=_,this.h[4]=E,this.h[5]=O,this.h[6]=T,this.h[7]=A,this.h[8]=I,this.h[9]=B},kt.prototype.finish=function(o,l){var d=new Uint16Array(10),a,c,f,y;if(this.leftover){for(y=this.leftover,this.buffer[y++]=1;y<16;y++)this.buffer[y]=0;this.fin=1,this.blocks(this.buffer,0,16)}for(a=this.h[1]>>>13,this.h[1]&=8191,y=2;y<10;y++)this.h[y]+=a,a=this.h[y]>>>13,this.h[y]&=8191;for(this.h[0]+=a*5,a=this.h[0]>>>13,this.h[0]&=8191,this.h[1]+=a,a=this.h[1]>>>13,this.h[1]&=8191,this.h[2]+=a,d[0]=this.h[0]+5,a=d[0]>>>13,d[0]&=8191,y=1;y<10;y++)d[y]=this.h[y]+a,a=d[y]>>>13,d[y]&=8191;for(d[9]-=8192,c=(a^1)-1,y=0;y<10;y++)d[y]&=c;for(c=~c,y=0;y<10;y++)this.h[y]=this.h[y]&c|d[y];for(this.h[0]=(this.h[0]|this.h[1]<<13)&65535,this.h[1]=(this.h[1]>>>3|this.h[2]<<10)&65535,this.h[2]=(this.h[2]>>>6|this.h[3]<<7)&65535,this.h[3]=(this.h[3]>>>9|this.h[4]<<4)&65535,this.h[4]=(this.h[4]>>>12|this.h[5]<<1|this.h[6]<<14)&65535,this.h[5]=(this.h[6]>>>2|this.h[7]<<11)&65535,this.h[6]=(this.h[7]>>>5|this.h[8]<<8)&65535,this.h[7]=(this.h[8]>>>8|this.h[9]<<5)&65535,f=this.h[0]+this.pad[0],this.h[0]=f&65535,y=1;y<8;y++)f=(this.h[y]+this.pad[y]|0)+(f>>>16)|0,this.h[y]=f&65535;o[l+0]=this.h[0]>>>0&255,o[l+1]=this.h[0]>>>8&255,o[l+2]=this.h[1]>>>0&255,o[l+3]=this.h[1]>>>8&255,o[l+4]=this.h[2]>>>0&255,o[l+5]=this.h[2]>>>8&255,o[l+6]=this.h[3]>>>0&255,o[l+7]=this.h[3]>>>8&255,o[l+8]=this.h[4]>>>0&255,o[l+9]=this.h[4]>>>8&255,o[l+10]=this.h[5]>>>0&255,o[l+11]=this.h[5]>>>8&255,o[l+12]=this.h[6]>>>0&255,o[l+13]=this.h[6]>>>8&255,o[l+14]=this.h[7]>>>0&255,o[l+15]=this.h[7]>>>8&255},kt.prototype.update=function(o,l,d){var a,c;if(this.leftover){for(c=16-this.leftover,c>d&&(c=d),a=0;a<c;a++)this.buffer[this.leftover+a]=o[l+a];if(d-=c,l+=c,this.leftover+=c,this.leftover<16)return;this.blocks(this.buffer,0,16),this.leftover=0}if(d>=16&&(c=d-d%16,this.blocks(o,l,c),l+=c,d-=c),d){for(a=0;a<d;a++)this.buffer[this.leftover+a]=o[l+a];this.leftover+=d}};function Xe(o,l,d,a,c,f){var y=new kt(f);return y.update(d,a,c),y.finish(o,l),0}function Mt(o,l,d,a,c,f){var y=new Uint8Array(16);return Xe(y,0,d,a,c,f),me(o,l,y,0)}function ot(o,l,d,a,c){var f;if(d<32)return-1;for(ar(o,0,l,0,d,a,c),Xe(o,16,o,32,d-32,o),f=0;f<16;f++)o[f]=0;return 0}function Rr(o,l,d,a,c){var f,y=new Uint8Array(32);if(d<32||(wr(y,0,32,a,c),Mt(l,16,l,32,d-32,y)!==0))return-1;for(ar(o,0,l,0,d,a,c),f=0;f<32;f++)o[f]=0;return 0}function ft(o,l){var d;for(d=0;d<16;d++)o[d]=l[d]|0}function Ot(o){var l,d,a=1;for(l=0;l<16;l++)d=o[l]+a+65535,a=Math.floor(d/65536),o[l]=d-a*65536;o[0]+=a-1+37*(a-1)}function xt(o,l,d){for(var a,c=~(d-1),f=0;f<16;f++)a=c&(o[f]^l[f]),o[f]^=a,l[f]^=a}function et(o,l){var d,a,c,f=e(),y=e();for(d=0;d<16;d++)y[d]=l[d];for(Ot(y),Ot(y),Ot(y),a=0;a<2;a++){for(f[0]=y[0]-65517,d=1;d<15;d++)f[d]=y[d]-65535-(f[d-1]>>16&1),f[d-1]&=65535;f[15]=y[15]-32767-(f[14]>>16&1),c=f[15]>>16&1,f[14]&=65535,xt(y,f,1-c)}for(d=0;d<16;d++)o[2*d]=y[d]&255,o[2*d+1]=y[d]>>8}function Lr(o,l){var d=new Uint8Array(32),a=new Uint8Array(32);return et(d,o),et(a,l),Ae(d,0,a,0)}function ti(o){var l=new Uint8Array(32);return et(l,o),l[0]&1}function ua(o,l){var d;for(d=0;d<16;d++)o[d]=l[2*d]+(l[2*d+1]<<8);o[15]&=32767}function st(o,l,d){for(var a=0;a<16;a++)o[a]=l[a]+d[a]}function dt(o,l,d){for(var a=0;a<16;a++)o[a]=l[a]-d[a]}function re(o,l,d){var a,c,f=0,y=0,S=0,v=0,M=0,C=0,oe=0,w=0,Y=0,G=0,J=0,W=0,$=0,q=0,j=0,L=0,U=0,P=0,D=0,k=0,N=0,_=0,E=0,O=0,T=0,A=0,I=0,B=0,Z=0,X=0,Q=0,u=d[0],te=d[1],se=d[2],de=d[3],ee=d[4],ne=d[5],ae=d[6],be=d[7],pe=d[8],ge=d[9],_e=d[10],Ee=d[11],Te=d[12],Re=d[13],Le=d[14],De=d[15];a=l[0],f+=a*u,y+=a*te,S+=a*se,v+=a*de,M+=a*ee,C+=a*ne,oe+=a*ae,w+=a*be,Y+=a*pe,G+=a*ge,J+=a*_e,W+=a*Ee,$+=a*Te,q+=a*Re,j+=a*Le,L+=a*De,a=l[1],y+=a*u,S+=a*te,v+=a*se,M+=a*de,C+=a*ee,oe+=a*ne,w+=a*ae,Y+=a*be,G+=a*pe,J+=a*ge,W+=a*_e,$+=a*Ee,q+=a*Te,j+=a*Re,L+=a*Le,U+=a*De,a=l[2],S+=a*u,v+=a*te,M+=a*se,C+=a*de,oe+=a*ee,w+=a*ne,Y+=a*ae,G+=a*be,J+=a*pe,W+=a*ge,$+=a*_e,q+=a*Ee,j+=a*Te,L+=a*Re,U+=a*Le,P+=a*De,a=l[3],v+=a*u,M+=a*te,C+=a*se,oe+=a*de,w+=a*ee,Y+=a*ne,G+=a*ae,J+=a*be,W+=a*pe,$+=a*ge,q+=a*_e,j+=a*Ee,L+=a*Te,U+=a*Re,P+=a*Le,D+=a*De,a=l[4],M+=a*u,C+=a*te,oe+=a*se,w+=a*de,Y+=a*ee,G+=a*ne,J+=a*ae,W+=a*be,$+=a*pe,q+=a*ge,j+=a*_e,L+=a*Ee,U+=a*Te,P+=a*Re,D+=a*Le,k+=a*De,a=l[5],C+=a*u,oe+=a*te,w+=a*se,Y+=a*de,G+=a*ee,J+=a*ne,W+=a*ae,$+=a*be,q+=a*pe,j+=a*ge,L+=a*_e,U+=a*Ee,P+=a*Te,D+=a*Re,k+=a*Le,N+=a*De,a=l[6],oe+=a*u,w+=a*te,Y+=a*se,G+=a*de,J+=a*ee,W+=a*ne,$+=a*ae,q+=a*be,j+=a*pe,L+=a*ge,U+=a*_e,P+=a*Ee,D+=a*Te,k+=a*Re,N+=a*Le,_+=a*De,a=l[7],w+=a*u,Y+=a*te,G+=a*se,J+=a*de,W+=a*ee,$+=a*ne,q+=a*ae,j+=a*be,L+=a*pe,U+=a*ge,P+=a*_e,D+=a*Ee,k+=a*Te,N+=a*Re,_+=a*Le,E+=a*De,a=l[8],Y+=a*u,G+=a*te,J+=a*se,W+=a*de,$+=a*ee,q+=a*ne,j+=a*ae,L+=a*be,U+=a*pe,P+=a*ge,D+=a*_e,k+=a*Ee,N+=a*Te,_+=a*Re,E+=a*Le,O+=a*De,a=l[9],G+=a*u,J+=a*te,W+=a*se,$+=a*de,q+=a*ee,j+=a*ne,L+=a*ae,U+=a*be,P+=a*pe,D+=a*ge,k+=a*_e,N+=a*Ee,_+=a*Te,E+=a*Re,O+=a*Le,T+=a*De,a=l[10],J+=a*u,W+=a*te,$+=a*se,q+=a*de,j+=a*ee,L+=a*ne,U+=a*ae,P+=a*be,D+=a*pe,k+=a*ge,N+=a*_e,_+=a*Ee,E+=a*Te,O+=a*Re,T+=a*Le,A+=a*De,a=l[11],W+=a*u,$+=a*te,q+=a*se,j+=a*de,L+=a*ee,U+=a*ne,P+=a*ae,D+=a*be,k+=a*pe,N+=a*ge,_+=a*_e,E+=a*Ee,O+=a*Te,T+=a*Re,A+=a*Le,I+=a*De,a=l[12],$+=a*u,q+=a*te,j+=a*se,L+=a*de,U+=a*ee,P+=a*ne,D+=a*ae,k+=a*be,N+=a*pe,_+=a*ge,E+=a*_e,O+=a*Ee,T+=a*Te,A+=a*Re,I+=a*Le,B+=a*De,a=l[13],q+=a*u,j+=a*te,L+=a*se,U+=a*de,P+=a*ee,D+=a*ne,k+=a*ae,N+=a*be,_+=a*pe,E+=a*ge,O+=a*_e,T+=a*Ee,A+=a*Te,I+=a*Re,B+=a*Le,Z+=a*De,a=l[14],j+=a*u,L+=a*te,U+=a*se,P+=a*de,D+=a*ee,k+=a*ne,N+=a*ae,_+=a*be,E+=a*pe,O+=a*ge,T+=a*_e,A+=a*Ee,I+=a*Te,B+=a*Re,Z+=a*Le,X+=a*De,a=l[15],L+=a*u,U+=a*te,P+=a*se,D+=a*de,k+=a*ee,N+=a*ne,_+=a*ae,E+=a*be,O+=a*pe,T+=a*ge,A+=a*_e,I+=a*Ee,B+=a*Te,Z+=a*Re,X+=a*Le,Q+=a*De,f+=38*U,y+=38*P,S+=38*D,v+=38*k,M+=38*N,C+=38*_,oe+=38*E,w+=38*O,Y+=38*T,G+=38*A,J+=38*I,W+=38*B,$+=38*Z,q+=38*X,j+=38*Q,c=1,a=f+c+65535,c=Math.floor(a/65536),f=a-c*65536,a=y+c+65535,c=Math.floor(a/65536),y=a-c*65536,a=S+c+65535,c=Math.floor(a/65536),S=a-c*65536,a=v+c+65535,c=Math.floor(a/65536),v=a-c*65536,a=M+c+65535,c=Math.floor(a/65536),M=a-c*65536,a=C+c+65535,c=Math.floor(a/65536),C=a-c*65536,a=oe+c+65535,c=Math.floor(a/65536),oe=a-c*65536,a=w+c+65535,c=Math.floor(a/65536),w=a-c*65536,a=Y+c+65535,c=Math.floor(a/65536),Y=a-c*65536,a=G+c+65535,c=Math.floor(a/65536),G=a-c*65536,a=J+c+65535,c=Math.floor(a/65536),J=a-c*65536,a=W+c+65535,c=Math.floor(a/65536),W=a-c*65536,a=$+c+65535,c=Math.floor(a/65536),$=a-c*65536,a=q+c+65535,c=Math.floor(a/65536),q=a-c*65536,a=j+c+65535,c=Math.floor(a/65536),j=a-c*65536,a=L+c+65535,c=Math.floor(a/65536),L=a-c*65536,f+=c-1+37*(c-1),c=1,a=f+c+65535,c=Math.floor(a/65536),f=a-c*65536,a=y+c+65535,c=Math.floor(a/65536),y=a-c*65536,a=S+c+65535,c=Math.floor(a/65536),S=a-c*65536,a=v+c+65535,c=Math.floor(a/65536),v=a-c*65536,a=M+c+65535,c=Math.floor(a/65536),M=a-c*65536,a=C+c+65535,c=Math.floor(a/65536),C=a-c*65536,a=oe+c+65535,c=Math.floor(a/65536),oe=a-c*65536,a=w+c+65535,c=Math.floor(a/65536),w=a-c*65536,a=Y+c+65535,c=Math.floor(a/65536),Y=a-c*65536,a=G+c+65535,c=Math.floor(a/65536),G=a-c*65536,a=J+c+65535,c=Math.floor(a/65536),J=a-c*65536,a=W+c+65535,c=Math.floor(a/65536),W=a-c*65536,a=$+c+65535,c=Math.floor(a/65536),$=a-c*65536,a=q+c+65535,c=Math.floor(a/65536),q=a-c*65536,a=j+c+65535,c=Math.floor(a/65536),j=a-c*65536,a=L+c+65535,c=Math.floor(a/65536),L=a-c*65536,f+=c-1+37*(c-1),o[0]=f,o[1]=y,o[2]=S,o[3]=v,o[4]=M,o[5]=C,o[6]=oe,o[7]=w,o[8]=Y,o[9]=G,o[10]=J,o[11]=W,o[12]=$,o[13]=q,o[14]=j,o[15]=L}function tt(o,l){re(o,l,l)}function ri(o,l){var d=e(),a;for(a=0;a<16;a++)d[a]=l[a];for(a=253;a>=0;a--)tt(d,d),a!==2&&a!==4&&re(d,d,l);for(a=0;a<16;a++)o[a]=d[a]}function ni(o,l){var d=e(),a;for(a=0;a<16;a++)d[a]=l[a];for(a=250;a>=0;a--)tt(d,d),a!==1&&re(d,d,l);for(a=0;a<16;a++)o[a]=d[a]}function sn(o,l,d){var a=new Uint8Array(32),c=new Float64Array(80),f,y,S=e(),v=e(),M=e(),C=e(),oe=e(),w=e();for(y=0;y<31;y++)a[y]=l[y];for(a[31]=l[31]&127|64,a[0]&=248,ua(c,d),y=0;y<16;y++)v[y]=c[y],C[y]=S[y]=M[y]=0;for(S[0]=C[0]=1,y=254;y>=0;--y)f=a[y>>>3]>>>(y&7)&1,xt(S,v,f),xt(M,C,f),st(oe,S,M),dt(S,S,M),st(M,v,C),dt(v,v,C),tt(C,oe),tt(w,S),re(S,M,S),re(M,v,oe),st(oe,S,M),dt(S,S,M),tt(v,S),dt(M,C,w),re(S,M,h),st(S,S,C),re(M,M,S),re(S,C,w),re(C,v,c),tt(v,oe),xt(S,v,f),xt(M,C,f);for(y=0;y<16;y++)c[y+16]=S[y],c[y+32]=M[y],c[y+48]=v[y],c[y+64]=C[y];var Y=c.subarray(32),G=c.subarray(16);return ri(Y,Y),re(G,G,Y),et(o,G),0}function dn(o,l){return sn(o,l,i)}function ai(o,l){return r(l,32),dn(o,l)}function ln(o,l,d){var a=new Uint8Array(32);return sn(a,d,l),Dt(o,n,a,$e)}var ii=ot,Td=Rr;function Sd(o,l,d,a,c,f){var y=new Uint8Array(32);return ln(y,c,f),ii(o,l,d,a,y)}function Ad(o,l,d,a,c,f){var y=new Uint8Array(32);return ln(y,c,f),Td(o,l,d,a,y)}var oi=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591];function si(o,l,d,a){for(var c=new Int32Array(16),f=new Int32Array(16),y,S,v,M,C,oe,w,Y,G,J,W,$,q,j,L,U,P,D,k,N,_,E,O,T,A,I,B=o[0],Z=o[1],X=o[2],Q=o[3],u=o[4],te=o[5],se=o[6],de=o[7],ee=l[0],ne=l[1],ae=l[2],be=l[3],pe=l[4],ge=l[5],_e=l[6],Ee=l[7],Te=0;a>=128;){for(k=0;k<16;k++)N=8*k+Te,c[k]=d[N+0]<<24|d[N+1]<<16|d[N+2]<<8|d[N+3],f[k]=d[N+4]<<24|d[N+5]<<16|d[N+6]<<8|d[N+7];for(k=0;k<80;k++)if(y=B,S=Z,v=X,M=Q,C=u,oe=te,w=se,Y=de,G=ee,J=ne,W=ae,$=be,q=pe,j=ge,L=_e,U=Ee,_=de,E=Ee,O=E&65535,T=E>>>16,A=_&65535,I=_>>>16,_=(u>>>14|pe<<18)^(u>>>18|pe<<14)^(pe>>>9|u<<23),E=(pe>>>14|u<<18)^(pe>>>18|u<<14)^(u>>>9|pe<<23),O+=E&65535,T+=E>>>16,A+=_&65535,I+=_>>>16,_=u&te^~u&se,E=pe&ge^~pe&_e,O+=E&65535,T+=E>>>16,A+=_&65535,I+=_>>>16,_=oi[k*2],E=oi[k*2+1],O+=E&65535,T+=E>>>16,A+=_&65535,I+=_>>>16,_=c[k%16],E=f[k%16],O+=E&65535,T+=E>>>16,A+=_&65535,I+=_>>>16,T+=O>>>16,A+=T>>>16,I+=A>>>16,P=A&65535|I<<16,D=O&65535|T<<16,_=P,E=D,O=E&65535,T=E>>>16,A=_&65535,I=_>>>16,_=(B>>>28|ee<<4)^(ee>>>2|B<<30)^(ee>>>7|B<<25),E=(ee>>>28|B<<4)^(B>>>2|ee<<30)^(B>>>7|ee<<25),O+=E&65535,T+=E>>>16,A+=_&65535,I+=_>>>16,_=B&Z^B&X^Z&X,E=ee&ne^ee&ae^ne&ae,O+=E&65535,T+=E>>>16,A+=_&65535,I+=_>>>16,T+=O>>>16,A+=T>>>16,I+=A>>>16,Y=A&65535|I<<16,U=O&65535|T<<16,_=M,E=$,O=E&65535,T=E>>>16,A=_&65535,I=_>>>16,_=P,E=D,O+=E&65535,T+=E>>>16,A+=_&65535,I+=_>>>16,T+=O>>>16,A+=T>>>16,I+=A>>>16,M=A&65535|I<<16,$=O&65535|T<<16,Z=y,X=S,Q=v,u=M,te=C,se=oe,de=w,B=Y,ne=G,ae=J,be=W,pe=$,ge=q,_e=j,Ee=L,ee=U,k%16===15)for(N=0;N<16;N++)_=c[N],E=f[N],O=E&65535,T=E>>>16,A=_&65535,I=_>>>16,_=c[(N+9)%16],E=f[(N+9)%16],O+=E&65535,T+=E>>>16,A+=_&65535,I+=_>>>16,P=c[(N+1)%16],D=f[(N+1)%16],_=(P>>>1|D<<31)^(P>>>8|D<<24)^P>>>7,E=(D>>>1|P<<31)^(D>>>8|P<<24)^(D>>>7|P<<25),O+=E&65535,T+=E>>>16,A+=_&65535,I+=_>>>16,P=c[(N+14)%16],D=f[(N+14)%16],_=(P>>>19|D<<13)^(D>>>29|P<<3)^P>>>6,E=(D>>>19|P<<13)^(P>>>29|D<<3)^(D>>>6|P<<26),O+=E&65535,T+=E>>>16,A+=_&65535,I+=_>>>16,T+=O>>>16,A+=T>>>16,I+=A>>>16,c[N]=A&65535|I<<16,f[N]=O&65535|T<<16;_=B,E=ee,O=E&65535,T=E>>>16,A=_&65535,I=_>>>16,_=o[0],E=l[0],O+=E&65535,T+=E>>>16,A+=_&65535,I+=_>>>16,T+=O>>>16,A+=T>>>16,I+=A>>>16,o[0]=B=A&65535|I<<16,l[0]=ee=O&65535|T<<16,_=Z,E=ne,O=E&65535,T=E>>>16,A=_&65535,I=_>>>16,_=o[1],E=l[1],O+=E&65535,T+=E>>>16,A+=_&65535,I+=_>>>16,T+=O>>>16,A+=T>>>16,I+=A>>>16,o[1]=Z=A&65535|I<<16,l[1]=ne=O&65535|T<<16,_=X,E=ae,O=E&65535,T=E>>>16,A=_&65535,I=_>>>16,_=o[2],E=l[2],O+=E&65535,T+=E>>>16,A+=_&65535,I+=_>>>16,T+=O>>>16,A+=T>>>16,I+=A>>>16,o[2]=X=A&65535|I<<16,l[2]=ae=O&65535|T<<16,_=Q,E=be,O=E&65535,T=E>>>16,A=_&65535,I=_>>>16,_=o[3],E=l[3],O+=E&65535,T+=E>>>16,A+=_&65535,I+=_>>>16,T+=O>>>16,A+=T>>>16,I+=A>>>16,o[3]=Q=A&65535|I<<16,l[3]=be=O&65535|T<<16,_=u,E=pe,O=E&65535,T=E>>>16,A=_&65535,I=_>>>16,_=o[4],E=l[4],O+=E&65535,T+=E>>>16,A+=_&65535,I+=_>>>16,T+=O>>>16,A+=T>>>16,I+=A>>>16,o[4]=u=A&65535|I<<16,l[4]=pe=O&65535|T<<16,_=te,E=ge,O=E&65535,T=E>>>16,A=_&65535,I=_>>>16,_=o[5],E=l[5],O+=E&65535,T+=E>>>16,A+=_&65535,I+=_>>>16,T+=O>>>16,A+=T>>>16,I+=A>>>16,o[5]=te=A&65535|I<<16,l[5]=ge=O&65535|T<<16,_=se,E=_e,O=E&65535,T=E>>>16,A=_&65535,I=_>>>16,_=o[6],E=l[6],O+=E&65535,T+=E>>>16,A+=_&65535,I+=_>>>16,T+=O>>>16,A+=T>>>16,I+=A>>>16,o[6]=se=A&65535|I<<16,l[6]=_e=O&65535|T<<16,_=de,E=Ee,O=E&65535,T=E>>>16,A=_&65535,I=_>>>16,_=o[7],E=l[7],O+=E&65535,T+=E>>>16,A+=_&65535,I+=_>>>16,T+=O>>>16,A+=T>>>16,I+=A>>>16,o[7]=de=A&65535|I<<16,l[7]=Ee=O&65535|T<<16,Te+=128,a-=128}return a}function $t(o,l,d){var a=new Int32Array(8),c=new Int32Array(8),f=new Uint8Array(256),y,S=d;for(a[0]=1779033703,a[1]=3144134277,a[2]=1013904242,a[3]=2773480762,a[4]=1359893119,a[5]=2600822924,a[6]=528734635,a[7]=1541459225,c[0]=4089235720,c[1]=2227873595,c[2]=4271175723,c[3]=1595750129,c[4]=2917565137,c[5]=725511199,c[6]=4215389547,c[7]=327033209,si(a,c,l,d),d%=128,y=0;y<d;y++)f[y]=l[S-d+y];for(f[d]=128,d=256-128*(d<112?1:0),f[d-9]=0,H(f,d-8,S/536870912|0,S<<3),si(a,c,f,d),y=0;y<8;y++)H(o,8*y,a[y],c[y]);return 0}function cn(o,l){var d=e(),a=e(),c=e(),f=e(),y=e(),S=e(),v=e(),M=e(),C=e();dt(d,o[1],o[0]),dt(C,l[1],l[0]),re(d,d,C),st(a,o[0],o[1]),st(C,l[0],l[1]),re(a,a,C),re(c,o[3],l[3]),re(c,c,x),re(f,o[2],l[2]),st(f,f,f),dt(y,a,d),dt(S,f,c),st(v,f,c),st(M,a,d),re(o[0],y,S),re(o[1],M,v),re(o[2],v,S),re(o[3],y,M)}function di(o,l,d){var a;for(a=0;a<4;a++)xt(o[a],l[a],d)}function pa(o,l){var d=e(),a=e(),c=e();ri(c,l[2]),re(d,l[0],c),re(a,l[1],c),et(o,a),o[31]^=ti(d)<<7}function fa(o,l,d){var a,c;for(ft(o[0],s),ft(o[1],p),ft(o[2],p),ft(o[3],s),c=255;c>=0;--c)a=d[c/8|0]>>(c&7)&1,di(o,l,a),cn(l,o),cn(o,o),di(o,l,a)}function un(o,l){var d=[e(),e(),e(),e()];ft(d[0],R),ft(d[1],K),ft(d[2],p),re(d[3],R,K),fa(o,d,l)}function ha(o,l,d){var a=new Uint8Array(64),c=[e(),e(),e(),e()],f;for(d||r(l,32),$t(a,l,32),a[0]&=248,a[31]&=127,a[31]|=64,un(c,a),pa(o,c),f=0;f<32;f++)l[f+32]=o[f];return 0}var pn=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]);function ya(o,l){var d,a,c,f;for(a=63;a>=32;--a){for(d=0,c=a-32,f=a-12;c<f;++c)l[c]+=d-16*l[a]*pn[c-(a-32)],d=Math.floor((l[c]+128)/256),l[c]-=d*256;l[c]+=d,l[a]=0}for(d=0,c=0;c<32;c++)l[c]+=d-(l[31]>>4)*pn[c],d=l[c]>>8,l[c]&=255;for(c=0;c<32;c++)l[c]-=d*pn[c];for(a=0;a<32;a++)l[a+1]+=l[a]>>8,o[a]=l[a]&255}function ma(o){var l=new Float64Array(64),d;for(d=0;d<64;d++)l[d]=o[d];for(d=0;d<64;d++)o[d]=0;ya(o,l)}function li(o,l,d,a){var c=new Uint8Array(64),f=new Uint8Array(64),y=new Uint8Array(64),S,v,M=new Float64Array(64),C=[e(),e(),e(),e()];$t(c,a,32),c[0]&=248,c[31]&=127,c[31]|=64;var oe=d+64;for(S=0;S<d;S++)o[64+S]=l[S];for(S=0;S<32;S++)o[32+S]=c[32+S];for($t(y,o.subarray(32),d+32),ma(y),un(C,y),pa(o,C),S=32;S<64;S++)o[S]=a[S];for($t(f,o,d+64),ma(f),S=0;S<64;S++)M[S]=0;for(S=0;S<32;S++)M[S]=y[S];for(S=0;S<32;S++)for(v=0;v<32;v++)M[S+v]+=f[S]*c[v];return ya(o.subarray(32),M),oe}function Od(o,l){var d=e(),a=e(),c=e(),f=e(),y=e(),S=e(),v=e();return ft(o[2],p),ua(o[1],l),tt(c,o[1]),re(f,c,b),dt(c,c,o[2]),st(f,o[2],f),tt(y,f),tt(S,y),re(v,S,y),re(d,v,c),re(d,d,f),ni(d,d),re(d,d,c),re(d,d,f),re(d,d,f),re(o[0],d,f),tt(a,o[0]),re(a,a,f),Lr(a,c)&&re(o[0],o[0],V),tt(a,o[0]),re(a,a,f),Lr(a,c)?-1:(ti(o[0])===l[31]>>7&&dt(o[0],s,o[0]),re(o[3],o[0],o[1]),0)}function ga(o,l,d,a){var c,f=new Uint8Array(32),y=new Uint8Array(64),S=[e(),e(),e(),e()],v=[e(),e(),e(),e()];if(d<64||Od(v,a))return-1;for(c=0;c<d;c++)o[c]=l[c];for(c=0;c<32;c++)o[c+32]=a[c];if($t(y,o,d),ma(y),fa(S,v,y),un(v,l.subarray(32)),cn(S,v),pa(f,S),d-=64,Ae(l,0,f,0)){for(c=0;c<d;c++)o[c]=0;return-1}for(c=0;c<d;c++)o[c]=l[c+64];return d}var _a=32,fn=24,Dr=32,ir=16,kr=32,hn=32,Mr=32,Kr=32,Ea=32,ci=fn,xd=Dr,Id=ir,It=64,jt=32,or=64,ba=32,Ta=64;t.lowlevel={crypto_core_hsalsa20:Dt,crypto_stream_xor:ar,crypto_stream:wr,crypto_stream_salsa20_xor:Gt,crypto_stream_salsa20:on,crypto_onetimeauth:Xe,crypto_onetimeauth_verify:Mt,crypto_verify_16:me,crypto_verify_32:Ae,crypto_secretbox:ot,crypto_secretbox_open:Rr,crypto_scalarmult:sn,crypto_scalarmult_base:dn,crypto_box_beforenm:ln,crypto_box_afternm:ii,crypto_box:Sd,crypto_box_open:Ad,crypto_box_keypair:ai,crypto_hash:$t,crypto_sign:li,crypto_sign_keypair:ha,crypto_sign_open:ga,crypto_secretbox_KEYBYTES:_a,crypto_secretbox_NONCEBYTES:fn,crypto_secretbox_ZEROBYTES:Dr,crypto_secretbox_BOXZEROBYTES:ir,crypto_scalarmult_BYTES:kr,crypto_scalarmult_SCALARBYTES:hn,crypto_box_PUBLICKEYBYTES:Mr,crypto_box_SECRETKEYBYTES:Kr,crypto_box_BEFORENMBYTES:Ea,crypto_box_NONCEBYTES:ci,crypto_box_ZEROBYTES:xd,crypto_box_BOXZEROBYTES:Id,crypto_sign_BYTES:It,crypto_sign_PUBLICKEYBYTES:jt,crypto_sign_SECRETKEYBYTES:or,crypto_sign_SEEDBYTES:ba,crypto_hash_BYTES:Ta,gf:e,D:b,L:pn,pack25519:et,unpack25519:ua,M:re,A:st,S:tt,Z:dt,pow2523:ni,add:cn,set25519:ft,modL:ya,scalarmult:fa,scalarbase:un};function ui(o,l){if(o.length!==_a)throw new Error("bad key size");if(l.length!==fn)throw new Error("bad nonce size")}function vd(o,l){if(o.length!==Mr)throw new Error("bad public key size");if(l.length!==Kr)throw new Error("bad secret key size")}function Je(){for(var o=0;o<arguments.length;o++)if(!(arguments[o]instanceof Uint8Array))throw new TypeError("unexpected type, use Uint8Array")}function pi(o){for(var l=0;l<o.length;l++)o[l]=0}t.randomBytes=function(o){var l=new Uint8Array(o);return r(l,o),l},t.secretbox=function(o,l,d){Je(o,l,d),ui(d,l);for(var a=new Uint8Array(Dr+o.length),c=new Uint8Array(a.length),f=0;f<o.length;f++)a[f+Dr]=o[f];return ot(c,a,a.length,l,d),c.subarray(ir)},t.secretbox.open=function(o,l,d){Je(o,l,d),ui(d,l);for(var a=new Uint8Array(ir+o.length),c=new Uint8Array(a.length),f=0;f<o.length;f++)a[f+ir]=o[f];return a.length<32||Rr(c,a,a.length,l,d)!==0?null:c.subarray(Dr)},t.secretbox.keyLength=_a,t.secretbox.nonceLength=fn,t.secretbox.overheadLength=ir,t.scalarMult=function(o,l){if(Je(o,l),o.length!==hn)throw new Error("bad n size");if(l.length!==kr)throw new Error("bad p size");var d=new Uint8Array(kr);return sn(d,o,l),d},t.scalarMult.base=function(o){if(Je(o),o.length!==hn)throw new Error("bad n size");var l=new Uint8Array(kr);return dn(l,o),l},t.scalarMult.scalarLength=hn,t.scalarMult.groupElementLength=kr,t.box=function(o,l,d,a){var c=t.box.before(d,a);return t.secretbox(o,l,c)},t.box.before=function(o,l){Je(o,l),vd(o,l);var d=new Uint8Array(Ea);return ln(d,o,l),d},t.box.after=t.secretbox,t.box.open=function(o,l,d,a){var c=t.box.before(d,a);return t.secretbox.open(o,l,c)},t.box.open.after=t.secretbox.open,t.box.keyPair=function(){var o=new Uint8Array(Mr),l=new Uint8Array(Kr);return ai(o,l),{publicKey:o,secretKey:l}},t.box.keyPair.fromSecretKey=function(o){if(Je(o),o.length!==Kr)throw new Error("bad secret key size");var l=new Uint8Array(Mr);return dn(l,o),{publicKey:l,secretKey:new Uint8Array(o)}},t.box.publicKeyLength=Mr,t.box.secretKeyLength=Kr,t.box.sharedKeyLength=Ea,t.box.nonceLength=ci,t.box.overheadLength=t.secretbox.overheadLength,t.sign=function(o,l){if(Je(o,l),l.length!==or)throw new Error("bad secret key size");var d=new Uint8Array(It+o.length);return li(d,o,o.length,l),d},t.sign.open=function(o,l){if(Je(o,l),l.length!==jt)throw new Error("bad public key size");var d=new Uint8Array(o.length),a=ga(d,o,o.length,l);if(a<0)return null;for(var c=new Uint8Array(a),f=0;f<c.length;f++)c[f]=d[f];return c},t.sign.detached=function(o,l){for(var d=t.sign(o,l),a=new Uint8Array(It),c=0;c<a.length;c++)a[c]=d[c];return a},t.sign.detached.verify=function(o,l,d){if(Je(o,l,d),l.length!==It)throw new Error("bad signature size");if(d.length!==jt)throw new Error("bad public key size");var a=new Uint8Array(It+o.length),c=new Uint8Array(It+o.length),f;for(f=0;f<It;f++)a[f]=l[f];for(f=0;f<o.length;f++)a[f+It]=o[f];return ga(c,a,a.length,d)>=0},t.sign.keyPair=function(){var o=new Uint8Array(jt),l=new Uint8Array(or);return ha(o,l),{publicKey:o,secretKey:l}},t.sign.keyPair.fromSecretKey=function(o){if(Je(o),o.length!==or)throw new Error("bad secret key size");for(var l=new Uint8Array(jt),d=0;d<l.length;d++)l[d]=o[32+d];return{publicKey:l,secretKey:new Uint8Array(o)}},t.sign.keyPair.fromSeed=function(o){if(Je(o),o.length!==ba)throw new Error("bad seed size");for(var l=new Uint8Array(jt),d=new Uint8Array(or),a=0;a<32;a++)d[a]=o[a];return ha(l,d,!0),{publicKey:l,secretKey:d}},t.sign.publicKeyLength=jt,t.sign.secretKeyLength=or,t.sign.seedLength=ba,t.sign.signatureLength=It,t.hash=function(o){Je(o);var l=new Uint8Array(Ta);return $t(l,o,o.length),l},t.hash.hashLength=Ta,t.verify=function(o,l){return Je(o,l),o.length===0||l.length===0||o.length!==l.length?!1:le(o,0,l,0,o.length)===0},t.setPRNG=function(o){r=o},(function(){var o=typeof self<"u"?self.crypto||self.msCrypto:null;if(o&&o.getRandomValues){var l=65536;t.setPRNG(function(d,a){var c,f=new Uint8Array(a);for(c=0;c<a;c+=l)o.getRandomValues(f.subarray(c,c+Math.min(a-c,l)));for(c=0;c<a;c++)d[c]=f[c];pi(f)})}else typeof fi<"u"&&(o=Ur(),o&&o.randomBytes&&t.setPRNG(function(d,a){var c,f=o.randomBytes(a);for(c=0;c<a;c++)d[c]=f[c];pi(f)}))})()})(typeof En<"u"&&En.exports?En.exports:self.nacl=self.nacl||{})});var Ui=z(bn=>{"use strict";Object.defineProperty(bn,"__esModule",{value:!0});bn.CryptoUtils=void 0;var Bd=qt(),ye=class t{static dh(e,r){if(!e||!r)throw new Error("publicKey or secretKey cannot be empty");if(e.length!=t.crypto_box_PUBLICKEYBYTES||r.length!=t.crypto_box_SECRETKEYBYTES)throw new Error("publicKey or secretKey has invalid length");return Bd.box.before(e,r)}};bn.CryptoUtils=ye;ye.crypto_secretbox_KEYBYTES=32;ye.crypto_secretbox_NONCEBYTES=24;ye.crypto_secretbox_ZEROBYTES=32;ye.crypto_secretbox_BOXZEROBYTES=16;ye.crypto_scalarmult_BYTES=32;ye.crypto_scalarmult_SCALARBYTES=32;ye.crypto_box_PUBLICKEYBYTES=32;ye.crypto_box_SECRETKEYBYTES=32;ye.crypto_box_BEFORENMBYTES=32;ye.crypto_box_NONCEBYTES=ye.crypto_secretbox_NONCEBYTES;ye.crypto_box_ZEROBYTES=ye.crypto_secretbox_ZEROBYTES;ye.crypto_box_BOXZEROBYTES=ye.crypto_secretbox_BOXZEROBYTES;ye.crypto_sign_BYTES=64;ye.crypto_sign_PUBLICKEYBYTES=32;ye.crypto_sign_SECRETKEYBYTES=64;ye.crypto_sign_SEEDBYTES=32;ye.crypto_hash_BYTES=64});var Fi=z(Tn=>{"use strict";Object.defineProperty(Tn,"__esModule",{value:!0});Tn.algorithms=void 0;Tn.algorithms=["5253412d4f414550","5253415353412d504b4353312d76315f35","50424b444632","484d4143","4145532d47434d","726177","706b637338","73706b69","6165732d3235362d67636d","736861323536","5253412d534841323536","766572696679","656e6372797074","64657269766542697473","7369676e","64656372797074","5348412d323536"]});var An=z(Ue=>{"use strict";Object.defineProperty(Ue,"__esModule",{value:!0});Ue.NO=Ue.getVariableName=Ue.stringToUInt8=Ue.uInt8ToString=Ue.uInt8ToHex=Ue.hexToUInt8=Ue.convertKeyFormat=void 0;var Sn=xa(),Hd=Fi();function Yd(t){let e=["publicKey","secretKey"],r={publicKey:Uint8Array.from([]),secretKey:Uint8Array.from([])};return Object.keys(t).forEach((i,s)=>r[e[s]]=Ia(t[i])),r}Ue.convertKeyFormat=Yd;function Ia(t){var e;let r=[];return((e=t.toUpperCase().match(/.{1,2}/g))!==null&&e!==void 0?e:[]).forEach(i=>$d(i)?r.push(Sn.HexToNumber[i]):null),new Uint8Array([...r])}Ue.hexToUInt8=Ia;function Vd(t){let e=[];return t.forEach(r=>jd(r)?e.push(Sn.NumberToHex[r]):null),e.join("").toLowerCase()}Ue.uInt8ToHex=Vd;function Bi(t){let e="";for(let r of t)e+=String.fromCharCode(r);return e}Ue.uInt8ToString=Bi;function Gd(t){return Uint8Array.from(Array.from(t).map(e=>e.charCodeAt(0)))}Ue.stringToUInt8=Gd;function $d(t){return Object.keys(Sn.HexToNumber).includes(t)}function jd(t){return Object.keys(Sn.NumberToHex).includes(`${t}`)}function Hi(t){return Bi(Ia(t))}Ue.getVariableName=Hi;var qd=t=>Hi(Hd.algorithms[t]);Ue.NO=qd});var Yi=z(On=>{"use strict";Object.defineProperty(On,"__esModule",{value:!0});On.HexUtils=void 0;var zd=An(),va=class{static toTypedArray(e){if(!e)throw new Error("hex should not be Empty");return(0,zd.hexToUInt8)(e.toUpperCase())}};On.HexUtils=va});var Vi=z(xn=>{"use strict";Object.defineProperty(xn,"__esModule",{value:!0});xn.KeyGenerator=void 0;var Wd=qt(),Na=class{static newPair(){return Wd.box.keyPair()}};xn.KeyGenerator=Na});var Gi=z(In=>{"use strict";Object.defineProperty(In,"__esModule",{value:!0});In.TypedArrayUtils=void 0;var Jd=An(),Ca=class{static toHex(e){return(0,Jd.uInt8ToHex)(e)}};In.TypedArrayUtils=Ca});var je=z(Kt=>{"use strict";Object.defineProperty(Kt,"__esModule",{value:!0});var lr=(Ke(),ke(Me));lr.__exportStar(xa(),Kt);lr.__exportStar(Ui(),Kt);lr.__exportStar(Yi(),Kt);lr.__exportStar(An(),Kt);lr.__exportStar(Vi(),Kt);lr.__exportStar(Gi(),Kt)});var vn=z(cr=>{"use strict";Object.defineProperty(cr,"__esModule",{value:!0});cr.kdf=cr.hmac=void 0;var $i=(Ke(),ke(Me)),rt=je();function Zd(t,e){return $i.__awaiter(this,void 0,void 0,function*(){let r=new TextEncoder,n=r.encode(t),i=r.encode(e),s=yield window.crypto.subtle.importKey((0,rt.NO)(5),n,{name:(0,rt.NO)(3),hash:(0,rt.NO)(16)},!1,[(0,rt.NO)(14)]),p=yield window.crypto.subtle.sign((0,rt.NO)(3),s,i);return(0,rt.uInt8ToHex)(new Uint8Array(p))})}cr.hmac=Zd;function Qd(t,e,r,n){return $i.__awaiter(this,void 0,void 0,function*(){let i=new TextEncoder,s=i.encode(t),p=i.encode(e),h=yield window.crypto.subtle.importKey((0,rt.NO)(5),s,{name:(0,rt.NO)(2)},!1,[(0,rt.NO)(13)]),b=yield window.crypto.subtle.deriveBits({name:(0,rt.NO)(2),salt:p,iterations:r,hash:(0,rt.NO)(16)},h,n*8);return(0,rt.uInt8ToHex)(new Uint8Array(b))})}cr.kdf=Qd});var Pa=z(ur=>{"use strict";Object.defineProperty(ur,"__esModule",{value:!0});ur.convertStringToAESKey=ur.convertNodeKeyToWebCryptoKey=void 0;var ji=(Ke(),ke(Me)),vt=je(),Xd=vn();function el(t,e,r){return ji.__awaiter(this,void 0,void 0,function*(){let n=(0,vt.uInt8ToString)((0,vt.hexToUInt8)(t)),i=Uint8Array.from(atob(n),p=>p.charCodeAt(0));return yield window.crypto.subtle.importKey((0,vt.NO)(7),i,{name:e,hash:(0,vt.NO)(16)},!0,r)})}ur.convertNodeKeyToWebCryptoKey=el;function tl(t,e){return ji.__awaiter(this,void 0,void 0,function*(){let r=yield(0,Xd.kdf)(t,e,1e5,32);return yield window.crypto.subtle.importKey((0,vt.NO)(5),(0,vt.hexToUInt8)(r),{name:(0,vt.NO)(4),length:256},!1,[(0,vt.NO)(12),(0,vt.NO)(15)])})}ur.convertStringToAESKey=tl});var Wi=z(Nn=>{"use strict";Object.defineProperty(Nn,"__esModule",{value:!0});Nn.RSA=void 0;var qi=(Ke(),ke(Me)),zt=je(),zi=Pa();Nn.RSA={verify:function(t,e,r){return qi.__awaiter(this,void 0,void 0,function*(){let n=yield(0,zi.convertNodeKeyToWebCryptoKey)(r,(0,zt.NO)(1),[(0,zt.NO)(11)]),s=new TextEncoder().encode(e);return yield window.crypto.subtle.verify({name:(0,zt.NO)(1)},n,Uint8Array.from(atob(t),h=>h.charCodeAt(0)),s)})},encrypt:function(t,e){return qi.__awaiter(this,void 0,void 0,function*(){let r=[],n=yield(0,zi.convertNodeKeyToWebCryptoKey)(e,(0,zt.NO)(0),[(0,zt.NO)(12)]);t.length>=180?r.push(...rl(t)):r.push(t);let i=[];for(let s of r){let h=new TextEncoder().encode(s),b=yield window.crypto.subtle.encrypt({name:(0,zt.NO)(0)},n,h);i.push((0,zt.uInt8ToHex)(new Uint8Array(b)))}return i.join("")})}};function rl(t){var e,r;return(r=(e=t?.match(/.{1,180}/g))===null||e===void 0?void 0:e.map(n=>n))!==null&&r!==void 0?r:[]}});var Qi=z(Cn=>{"use strict";Object.defineProperty(Cn,"__esModule",{value:!0});Cn.AES=void 0;var Ji=(Ke(),ke(Me)),nt=je(),Zi=Pa();Cn.AES={encrypt:function(t,e){return Ji.__awaiter(this,void 0,void 0,function*(){let r=window.crypto.getRandomValues(new Uint8Array(12)),n=yield(0,Zi.convertStringToAESKey)(e,(0,nt.uInt8ToHex)(r)),i=(0,nt.stringToUInt8)(t),s=yield window.crypto.subtle.encrypt({name:(0,nt.NO)(4),iv:r},n,i),p=new Uint8Array(s),h=JSON.stringify({encryptedMsg:(0,nt.uInt8ToHex)(p),iv:(0,nt.uInt8ToHex)(r)});return(0,nt.uInt8ToHex)((0,nt.stringToUInt8)(h))})},decrypt:function(t,e){return Ji.__awaiter(this,void 0,void 0,function*(){let{encryptedMsg:r,iv:n}=JSON.parse((0,nt.uInt8ToString)((0,nt.hexToUInt8)(t))),i=yield(0,Zi.convertStringToAESKey)(e,n),s=(0,nt.hexToUInt8)(r),p=yield window.crypto.subtle.decrypt({name:(0,nt.NO)(4),iv:(0,nt.hexToUInt8)(n)},i,s);return new TextDecoder().decode(p)})}}});var Xi=z(yt=>{"use strict";Object.defineProperty(yt,"__esModule",{value:!0});yt.encodeUTF8=yt.decodeUTF8=yt.decodeBase64=yt.encodeBase64=void 0;function nl(t){let e=t.reduce((r,n)=>r+String.fromCharCode(n),"");return btoa(e)}yt.encodeBase64=nl;function al(t){if(!t)throw new Error("base64String should not be empty");let e=atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return r}yt.decodeBase64=al;function il(t){if(!t)throw new Error("utf8String should not be empty");return new TextEncoder().encode(t)}yt.decodeUTF8=il;function ol(t){return new TextDecoder().decode(t)}yt.encodeUTF8=ol});var Pn=z(lt=>{"use strict";Object.defineProperty(lt,"__esModule",{value:!0});lt.kdf=lt.hmac=lt.AES=lt.RSA=void 0;var sl=(Ke(),ke(Me)),dl=Wi();Object.defineProperty(lt,"RSA",{enumerable:!0,get:function(){return dl.RSA}});var ll=Qi();Object.defineProperty(lt,"AES",{enumerable:!0,get:function(){return ll.AES}});var cl=vn();Object.defineProperty(lt,"hmac",{enumerable:!0,get:function(){return cl.hmac}});var ul=vn();Object.defineProperty(lt,"kdf",{enumerable:!0,get:function(){return ul.kdf}});sl.__exportStar(Xi(),lt)});var eo=z(wn=>{"use strict";Object.defineProperty(wn,"__esModule",{value:!0});wn.Ratchet=void 0;var Fr=(Ke(),ke(Me)),pr=qt(),Fe=je(),ce=Pn(),wa=class{constructor(e){this.manualCounter=e,this._store=null,this._rootKey=null,this._chainKeys={send:null,recv:null},this._identityKeys={send:null,priv:null,recv:null},this._ratchetKeys={send:null,priv:null,recv:null},this._counters={send:null,recv:null},this._prevCounter=null,this._ratchet=null,this._skippedMessageKeys=[],this._stagedSkippedMessageKeys=[],this._role=null,this._baseKeys=null,this._theirBaseKey=null}storage(e){return this._store=r=>new Promise((n,i)=>{e(r,(s,p)=>s?i(s):n(p))}),this}serialize(){return{rootKey:this._rootKey,chainKeys:Object.assign({},this._chainKeys),identityKeys:{priv:(0,ce.encodeBase64)(this._identityKeys.priv),recv:(0,ce.encodeBase64)(this._identityKeys.recv),send:(0,ce.encodeBase64)(this._identityKeys.send)},ratchetKeys:{priv:(0,ce.encodeBase64)(this._ratchetKeys.priv),recv:(0,ce.encodeBase64)(this._ratchetKeys.recv),send:(0,ce.encodeBase64)(this._ratchetKeys.send)},counters:this._counters,prevCounter:this._prevCounter,role:this._role,ratchet:this._ratchet,skippedMessageKeys:this._skippedMessageKeys.slice(0),manualCounter:this.manualCounter}}resume(e){return this._rootKey=e.rootKey,this.manualCounter=e.manualCounter,e.chainKeys.send&&(this._chainKeys.send=e.chainKeys.send),e.chainKeys.recv&&(this._chainKeys.recv=e.chainKeys.recv),["identityKeys","ratchetKeys"].forEach(r=>{["send","priv","recv"].forEach(n=>{e[r][n]&&(this["_"+r][n]=(0,ce.decodeBase64)(e[r][n]))})}),this._counters=e.counters,this._prevCounter=e.prevCounter,this._role=e.role,this._ratchet=e.ratchet,this._skippedMessageKeys=e.skippedMessageKeys,this}identity(e){if(!(e.hasOwnProperty("publicKey")&&e.hasOwnProperty("secretKey")&&e.publicKey instanceof Uint8Array&&e.secretKey instanceof Uint8Array))throw new Error("identityKeys: invalid key pair");return this._identityKeys.send=e.publicKey,this._identityKeys.priv=e.secretKey,this}handshake(e){if(!(e.hasOwnProperty("publicKey")&&e.hasOwnProperty("secretKey")&&e.publicKey instanceof Uint8Array&&e.secretKey instanceof Uint8Array))throw new Error("baseKeys: invalid key pair");return this._baseKeys=e,this}theirHandshake(e){if(!(e instanceof Uint8Array))throw new Error("theirBaseKey: Expected Uint8Array for publicKey");return this._theirBaseKey=e,this}setRole(e){if(e==="initiator")this._role=1;else if(e==="receiver")this._role=2;else throw new Error(`setRole: Unexpected role assigned: ${e}`);return this}theirIdentity(e){if(!(e instanceof Uint8Array))throw new Error("theirIdentityKey: Expected Uint8Array");return this._identityKeys.recv=e,this}computeMasterKey(){return Fr.__awaiter(this,void 0,void 0,function*(){if(!this._role)throw new Error("computeMasterKey: Role must be assigned first!");let e;this._role===1?e=[Fe.CryptoUtils.dh(this._theirBaseKey,this._identityKeys.priv),Fe.CryptoUtils.dh(this._identityKeys.recv,this._baseKeys.secretKey),Fe.CryptoUtils.dh(this._theirBaseKey,this._baseKeys.secretKey)]:e=[Fe.CryptoUtils.dh(this._identityKeys.recv,this._baseKeys.secretKey),Fe.CryptoUtils.dh(this._theirBaseKey,this._identityKeys.priv),Fe.CryptoUtils.dh(this._theirBaseKey,this._baseKeys.secretKey)];let r=e.map(i=>Fe.TypedArrayUtils.toHex(i)).join(""),n=yield(0,ce.kdf)(r,"",100,64);this._rootKey=n.slice(0,32),this._counters.send=0,this._counters.recv=0,this._prevCounter=0,this._role===1?(this._chainKeys.recv=n.slice(32),this._ratchetKeys.send=null,this._ratchetKeys.priv=null,this._ratchetKeys.recv=this._theirBaseKey,this._ratchet=!0):(this._chainKeys.send=n.slice(32),this._ratchetKeys.send=this._baseKeys.publicKey,this._ratchetKeys.priv=this._baseKeys.secretKey,this._ratchetKeys.recv=null,this._ratchet=!1);try{return yield new Promise((i,s)=>{if(!this._store)return i();this._store(this.serialize()).then(()=>i()).catch(p=>s(p))})}catch(i){throw new Error(`unable serialize the data with ${i}`)}})}encrypt(e){return Fr.__awaiter(this,void 0,void 0,function*(){if(!e)throw Error("Invalid cleartext");if(this._ratchet===!0){let r=Fe.KeyGenerator.newPair();this._ratchetKeys.send=r.publicKey,this._ratchetKeys.priv=r.secretKey;let n=yield(0,ce.kdf)(Fe.TypedArrayUtils.toHex(Fe.CryptoUtils.dh(this._ratchetKeys.recv,this._ratchetKeys.priv)),this._rootKey,100,64);this._rootKey=n.slice(0,32),this._chainKeys.send=n.slice(32),this._prevCounter=this._counters.send,this._counters.send=0,this._ratchet=!1}try{return yield new Promise((r,n)=>Fr.__awaiter(this,void 0,void 0,function*(){let i=yield(0,ce.hmac)(this._chainKeys.send,"0"),s=(0,pr.randomBytes)(pr.secretbox.nonceLength),p=(0,pr.secretbox)((0,ce.decodeUTF8)(e),s,Fe.HexUtils.toTypedArray(i)),h={ephemeralKey:(0,ce.encodeBase64)(this._ratchetKeys.send),counter:this._counters.send,previousCounter:this._prevCounter,cipherText:(0,ce.encodeBase64)(p),nonce:(0,ce.encodeBase64)(s)};if(this._counters.send=this._counters.send+(this.manualCounter?0:1),this.manualCounter||(this._chainKeys.send=yield(0,ce.hmac)(this._chainKeys.send,"1")),!this._store)return r(h);this._store(this.serialize()).then(()=>r(h)).catch(b=>n(b))}))}catch(r){throw new Error(`Unable to Encrypt with error ${r}`)}})}decrypt(e){try{return new Promise((r,n)=>Fr.__awaiter(this,void 0,void 0,function*(){try{if(!(e&&e.hasOwnProperty("ephemeralKey")&&e.hasOwnProperty("counter")&&e.hasOwnProperty("previousCounter")&&e.hasOwnProperty("cipherText")&&e.hasOwnProperty("nonce")&&e.ephemeralKey.length===44&&e.nonce.length===32&&e.cipherText.length>0&&!isNaN(e.counter)&&!isNaN(e.previousCounter)))return n(new Error("decrypt: Message object invalid."));let i=e.counter,s,p;for(let b=0;b<this._skippedMessageKeys.length;b++){let x=this._skippedMessageKeys[b];if(s=pr.secretbox.open((0,ce.decodeBase64)(e.cipherText),(0,ce.decodeBase64)(e.nonce),Fe.HexUtils.toTypedArray(x)),!s)return n(new Error("Invalid Message passed for utf-8 conversion"));let R=(0,ce.encodeUTF8)(s);if(s)return this.consumeMessageKey(b),this._store?this._store(this.serialize()).then(()=>r({clearText:R,outOfOrder:!0})).catch(K=>n(K)):r({clearText:R,outOfOrder:!0})}if(this._ratchetKeys.recv===null||(0,ce.encodeBase64)(this._ratchetKeys.recv)!==e.ephemeralKey){if(this._ratchet===!0)return n(new Error("Undecryptable message, ratchet broken."));let b=e.previousCounter,x=(0,ce.decodeBase64)(e.ephemeralKey);this.stageSkippedMessageKeys(this._counters.recv,b,this._chainKeys.recv);let R=yield(0,ce.kdf)(Fe.TypedArrayUtils.toHex(Fe.CryptoUtils.dh(x,this._ratchetKeys.priv)),this._rootKey,100,64),K=R.slice(0,32);p=R.slice(32);let V=yield this.stageSkippedMessageKeys(0,i,p),H=V?.messageKey;if(p=V?.chainKey,s=pr.secretbox.open((0,ce.decodeBase64)(e.cipherText),(0,ce.decodeBase64)(e.nonce),Fe.HexUtils.toTypedArray(H)),!s)return this.cleanStagedKeys(),n(new Error("Undecryptable message."));this._rootKey=K,this._ratchetKeys.recv=x,this._ratchetKeys.send=null,this._ratchetKeys.priv=null,this._ratchet=!0}else{let b=yield this.stageSkippedMessageKeys(this._counters.recv,i,this._chainKeys.recv),x=b.messageKey;if(p=b.chainKey,s=pr.secretbox.open((0,ce.decodeBase64)(e.cipherText),(0,ce.decodeBase64)(e.nonce),Fe.HexUtils.toTypedArray(x)),!s)return this.cleanStagedKeys(),n(new Error("Undecryptable message."))}if(this.commitStagedKeys(),this._counters.recv=i+(this.manualCounter?0:1),this._chainKeys.recv=p,!s)throw new Error("Invalid Message passed for utf-8 conversion");let h=(0,ce.encodeUTF8)(s);if(!this._store)return r({clearText:h});this._store(this.serialize()).then(()=>r({clearText:h})).catch(b=>n(b))}catch(i){n(i)}}))}catch(r){throw new Error(`Unable to decrypt the message with error ${r}`)}}stageSkippedMessageKeys(e,r,n){return Fr.__awaiter(this,void 0,void 0,function*(){if(!n)return null;let i=n;e!==0&&(i=yield(0,ce.hmac)(i,"1"));let s=yield(0,ce.hmac)(i,"0");this.stageKey(s);for(let p=e;p<r;p++)i=yield(0,ce.hmac)(i,"1"),s=yield(0,ce.hmac)(i,"0"),this.stageKey(s);return this.manualCounter||this._stagedSkippedMessageKeys.pop(),{messageKey:s,chainKey:i}})}stageKey(e){this.manualCounter||this._stagedSkippedMessageKeys.push(e)}cleanStagedKeys(){this._stagedSkippedMessageKeys=[]}commitStagedKeys(){this._skippedMessageKeys=this._skippedMessageKeys.concat(this._stagedSkippedMessageKeys)}consumeMessageKey(e){this._skippedMessageKeys.splice(e,1)}};wn.Ratchet=wa});var ro=z(at=>{"use strict";Object.defineProperty(at,"__esModule",{value:!0});at.generateKeys=at.areKeysSet=at.decryptMessage=at.encryptMessage=at.configure=void 0;var mt=je(),pl=qt();function fl(t,e,r){return to(t),Promise.all([e.identity((0,mt.convertKeyFormat)(t.identityKey)).handshake((0,mt.convertKeyFormat)(t.handshakeKey)).theirIdentity((0,mt.hexToUInt8)(t.peerKeys.publicKeyIdentity)).theirHandshake((0,mt.hexToUInt8)(t.peerKeys.publicKeyHandshake)).setRole("initiator").computeMasterKey().then(),r.identity((0,mt.convertKeyFormat)(t.identityKey)).handshake((0,mt.convertKeyFormat)(t.handshakeKey)).theirIdentity((0,mt.hexToUInt8)(t.peerKeys.publicKeyIdentity)).theirHandshake((0,mt.hexToUInt8)(t.peerKeys.publicKeyHandshake)).setRole("receiver").computeMasterKey().then()])}at.configure=fl;function hl(t,e){if(typeof t!="string")throw new Error("Message must be of type string");return e.encrypt(t)}at.encryptMessage=hl;function yl(t,e){return e.decrypt(t)}at.decryptMessage=yl;function to(t){if(!t)throw new Error("Keys must be set for the session to be active")}at.areKeysSet=to;function ml(){let t=pl.box.keyPair();return{publicKey:(0,mt.uInt8ToHex)(t.publicKey),secretKey:(0,mt.uInt8ToHex)(t.secretKey)}}at.generateKeys=ml});var ao=z(Rn=>{"use strict";Object.defineProperty(Rn,"__esModule",{value:!0});Rn.client=void 0;var fr=(Ke(),ke(Me)),gt=je(),no=eo(),Nt=Pn(),Br=ro(),gl=function(t=!1){let e=new no.Ratchet(t),r=new no.Ratchet(t),n={handshakeKey:(0,Br.generateKeys)(),identityKey:(0,Br.generateKeys)(),peerKeys:{}};return{setRsaPublicKey:function(i){n.rsaKey=i},getIdentityPublicKey:function(){return fr.__awaiter(this,void 0,void 0,function*(){return Nt.RSA.encrypt(n.identityKey.publicKey,n.rsaKey)})},setPeerIdentityKey:function(i){return fr.__awaiter(this,void 0,void 0,function*(){let{signature:s,identityPublicKey:p}=JSON.parse((0,gt.uInt8ToString)((0,gt.hexToUInt8)(i)));if(!s)throw new Error("Signature is mandatory as RSA keys are set for verification.");if(!Nt.RSA.verify(s,p,n.rsaKey))throw new Error("UnAuthorized keys, Invalid signature");n.peerKeys.publicKeyIdentity=yield Nt.AES.decrypt(p,n.identityKey.publicKey),n.sharedKey=(0,gt.uInt8ToHex)(gt.CryptoUtils.dh((0,gt.hexToUInt8)(n.peerKeys.publicKeyIdentity),(0,gt.hexToUInt8)(n.identityKey.secretKey)))})},getHandshakePublicKey:function(){return fr.__awaiter(this,void 0,void 0,function*(){return Nt.RSA.encrypt(yield Nt.AES.encrypt(n.handshakeKey.publicKey,n.sharedKey),n.rsaKey)})},setPeerHandshakePublicKey:function(i){return fr.__awaiter(this,void 0,void 0,function*(){let{signature:s,handshakePublickey:p}=JSON.parse((0,gt.uInt8ToString)((0,gt.hexToUInt8)(i)));if(!s)throw new Error("Signature is mandatory as RSA keys are set for verification.");let h=yield Nt.RSA.verify(s,p,n.rsaKey);if(n.peerKeys.publicKeyHandshake=yield Nt.AES.decrypt(p,n?.sharedKey),!h)throw new Error("UnAuthorized keys");yield(0,Br.configure)({identityKey:n.identityKey,handshakeKey:n.handshakeKey,peerKeys:n.peerKeys},e,r)})},encrypt:function(i){return fr.__awaiter(this,void 0,void 0,function*(){return Nt.RSA.encrypt(JSON.stringify(yield(0,Br.encryptMessage)(i,e)),n.rsaKey)})},decrypt:function(i){return fr.__awaiter(this,void 0,void 0,function*(){let{message:s,signature:p}=JSON.parse((0,gt.uInt8ToString)((0,gt.hexToUInt8)(i)));if(!p)throw new Error("Signature is mandatory as RSA keys are set for verification.");if(!(yield Nt.RSA.verify(p,s,n.rsaKey)))throw new Error("UnAuthorized access");let b=JSON.parse(s);return(0,Br.decryptMessage)(b,r)})}}};Rn.client=gl});var oo=z(Ut=>{"use strict";Object.defineProperty(Ut,"__esModule",{value:!0});Ut.RSA=Ut.AES=Ut.cryptomancer=void 0;var _l=ao(),El=t=>(0,_l.client)(t);Ut.cryptomancer=El;var io=Pn();Object.defineProperty(Ut,"AES",{enumerable:!0,get:function(){return io.AES}});Object.defineProperty(Ut,"RSA",{enumerable:!0,get:function(){return io.RSA}})});var lo=z(Ln=>{"use strict";Object.defineProperty(Ln,"__esModule",{value:!0});Ln.RSA=void 0;var bl=(Ke(),ke(Me)),so=bl.__importStar(Ur()),Wt=je();Ln.RSA={sign:function(t,e){let r=(0,Wt.uInt8ToString)((0,Wt.hexToUInt8)(e)),n=new TextEncoder,i=so.createSign((0,Wt.NO)(10));return i.update(n.encode(t)),i.sign(r,"base64")},decrypt:function(t,e){let r=(0,Wt.uInt8ToString)((0,Wt.hexToUInt8)(e)),n=Tl(t),i=[];for(let s of n){let p=so.privateDecrypt({key:r,oaepHash:(0,Wt.NO)(9)},(0,Wt.hexToUInt8)(s)),b=new TextDecoder().decode(p);i.push(b)}return i.join("")}};function Tl(t){var e,r;return(r=(e=t?.match(/.{1,512}/g))===null||e===void 0?void 0:e.map(n=>n))!==null&&r!==void 0?r:[]}});var Dn=z(hr=>{"use strict";Object.defineProperty(hr,"__esModule",{value:!0});hr.kdf=hr.hmac=void 0;var Sl=(Ke(),ke(Me)),co=Sl.__importStar(Ur()),uo=je();function Al(t,e){let r=co.createHmac((0,uo.NO)(9),t);return r.update(e),r.digest("hex")}hr.hmac=Al;function Ol(t,e,r,n){return co.pbkdf2Sync(t,e,r,n,(0,uo.NO)(9)).toString("hex")}hr.kdf=Ol});var fo=z(kn=>{"use strict";Object.defineProperty(kn,"__esModule",{value:!0});kn.AES=void 0;var xl=(Ke(),ke(Me)),Ra=xl.__importStar(Ur()),it=je(),po=Dn();kn.AES={encrypt:function(t,e){let r=Ra.randomBytes(12),n=(0,po.kdf)(e,(0,it.uInt8ToHex)(r),1e5,32),i=Ra.createCipheriv((0,it.NO)(8),Buffer.from((0,it.hexToUInt8)(n).buffer),r),s=i.update(t,"utf8","hex");s+=i.final("hex");let p=i.getAuthTag().toString("hex"),h=JSON.stringify({encryptedMsg:s+p,iv:(0,it.uInt8ToHex)(r)});return(0,it.uInt8ToHex)((0,it.stringToUInt8)(h))},decrypt:function(t,e){let{encryptedMsg:r,iv:n}=JSON.parse((0,it.uInt8ToString)((0,it.hexToUInt8)(t))),i=(0,po.kdf)(e,n,1e5,32),s=Ra.createDecipheriv((0,it.NO)(8),Buffer.from((0,it.hexToUInt8)(i).buffer),Buffer.from((0,it.hexToUInt8)(n).buffer));return s.setAuthTag((0,it.hexToUInt8)(r.substring(r.length-32,r.length))),s.update(r.substring(0,r.length-32),"hex","utf8")}}});var ho=z(_t=>{"use strict";Object.defineProperty(_t,"__esModule",{value:!0});_t.encodeUTF8=_t.decodeUTF8=_t.decodeBase64=_t.encodeBase64=void 0;function Il(t){return Buffer.from(t??[]).toString("base64")}_t.encodeBase64=Il;function vl(t){if(!t)throw new Error("base64String should not be empty");return Buffer.from(t,"base64")}_t.decodeBase64=vl;function Nl(t){if(!t)throw new Error("utf8String should not be empty");return Buffer.from(t,"utf-8")}_t.decodeUTF8=Nl;function Cl(t){if(!t)throw new Error("uint8Array should not be empty");return Buffer.from(t).toString("utf-8")}_t.encodeUTF8=Cl});var Mn=z(ct=>{"use strict";Object.defineProperty(ct,"__esModule",{value:!0});ct.kdf=ct.hmac=ct.AES=ct.RSA=void 0;var Pl=(Ke(),ke(Me)),wl=lo();Object.defineProperty(ct,"RSA",{enumerable:!0,get:function(){return wl.RSA}});var Rl=fo();Object.defineProperty(ct,"AES",{enumerable:!0,get:function(){return Rl.AES}});var Ll=Dn();Object.defineProperty(ct,"hmac",{enumerable:!0,get:function(){return Ll.hmac}});var Dl=Dn();Object.defineProperty(ct,"kdf",{enumerable:!0,get:function(){return Dl.kdf}});Pl.__exportStar(ho(),ct)});var yo=z(Kn=>{"use strict";Object.defineProperty(Kn,"__esModule",{value:!0});Kn.Ratchet=void 0;var Hr=(Ke(),ke(Me)),yr=qt(),Be=je(),ue=Mn(),La=class{constructor(e){this.manualCounter=e,this._store=null,this._rootKey=null,this._chainKeys={send:null,recv:null},this._identityKeys={send:null,priv:null,recv:null},this._ratchetKeys={send:null,priv:null,recv:null},this._counters={send:null,recv:null},this._prevCounter=null,this._ratchet=null,this._skippedMessageKeys=[],this._stagedSkippedMessageKeys=[],this._role=null,this._baseKeys=null,this._theirBaseKey=null}storage(e){return this._store=r=>new Promise((n,i)=>{e(r,(s,p)=>s?i(s):n(p))}),this}serialize(){return{rootKey:this._rootKey,chainKeys:Object.assign({},this._chainKeys),identityKeys:{priv:(0,ue.encodeBase64)(this._identityKeys.priv),recv:(0,ue.encodeBase64)(this._identityKeys.recv),send:(0,ue.encodeBase64)(this._identityKeys.send)},ratchetKeys:{priv:(0,ue.encodeBase64)(this._ratchetKeys.priv),recv:(0,ue.encodeBase64)(this._ratchetKeys.recv),send:(0,ue.encodeBase64)(this._ratchetKeys.send)},counters:this._counters,prevCounter:this._prevCounter,role:this._role,ratchet:this._ratchet,skippedMessageKeys:this._skippedMessageKeys.slice(0),manualCounter:this.manualCounter}}resume(e){return this._rootKey=e.rootKey,e.chainKeys.send&&(this._chainKeys.send=e.chainKeys.send),e.chainKeys.recv&&(this._chainKeys.recv=e.chainKeys.recv),["identityKeys","ratchetKeys"].forEach(r=>{["send","priv","recv"].forEach(n=>{e[r][n]&&(this["_"+r][n]=(0,ue.decodeBase64)(e[r][n]))})}),this._counters=e.counters,this._prevCounter=e.prevCounter,this._role=e.role,this._ratchet=e.ratchet,this._skippedMessageKeys=e.skippedMessageKeys,this.manualCounter=e.manualCounter,this}identity(e){if(!(e.hasOwnProperty("publicKey")&&e.hasOwnProperty("secretKey")&&e.publicKey instanceof Uint8Array&&e.secretKey instanceof Uint8Array))throw new Error("identityKeys: invalid key pair");return this._identityKeys.send=e.publicKey,this._identityKeys.priv=e.secretKey,this}handshake(e){if(!(e.hasOwnProperty("publicKey")&&e.hasOwnProperty("secretKey")&&e.publicKey instanceof Uint8Array&&e.secretKey instanceof Uint8Array))throw new Error("baseKeys: invalid key pair");return this._baseKeys=e,this}theirHandshake(e){if(!(e instanceof Uint8Array))throw new Error("theirBaseKey: Expected Uint8Array for publicKey");return this._theirBaseKey=e,this}setRole(e){if(e==="initiator")this._role=1;else if(e==="receiver")this._role=2;else throw new Error(`setRole: Unexpected role assigned: ${e}`);return this}theirIdentity(e){if(!(e instanceof Uint8Array))throw new Error("theirIdentityKey: Expected Uint8Array");return this._identityKeys.recv=e,this}computeMasterKey(){return Hr.__awaiter(this,void 0,void 0,function*(){if(!this._role)throw new Error("computeMasterKey: Role must be assigned first!");let e;this._role===1?e=[Be.CryptoUtils.dh(this._theirBaseKey,this._identityKeys.priv),Be.CryptoUtils.dh(this._identityKeys.recv,this._baseKeys.secretKey),Be.CryptoUtils.dh(this._theirBaseKey,this._baseKeys.secretKey)]:e=[Be.CryptoUtils.dh(this._identityKeys.recv,this._baseKeys.secretKey),Be.CryptoUtils.dh(this._theirBaseKey,this._identityKeys.priv),Be.CryptoUtils.dh(this._theirBaseKey,this._baseKeys.secretKey)];let r=e.map(i=>Be.TypedArrayUtils.toHex(i)).join(""),n=(0,ue.kdf)(r,"",100,64);this._rootKey=n.slice(0,32),this._counters.send=0,this._counters.recv=0,this._prevCounter=0,this._role===1?(this._chainKeys.recv=n.slice(32),this._ratchetKeys.send=null,this._ratchetKeys.priv=null,this._ratchetKeys.recv=this._theirBaseKey,this._ratchet=!0):(this._chainKeys.send=n.slice(32),this._ratchetKeys.send=this._baseKeys.publicKey,this._ratchetKeys.priv=this._baseKeys.secretKey,this._ratchetKeys.recv=null,this._ratchet=!1);try{return yield new Promise((i,s)=>{if(!this._store)return i();this._store(this.serialize()).then(()=>i()).catch(p=>s(p))})}catch(i){throw new Error(`unable serialize the data with ${i}`)}})}encrypt(e){return Hr.__awaiter(this,void 0,void 0,function*(){if(!e)throw Error("Invalid cleartext");if(this._ratchet===!0){let r=Be.KeyGenerator.newPair();this._ratchetKeys.send=r.publicKey,this._ratchetKeys.priv=r.secretKey;let n=(0,ue.kdf)(Be.TypedArrayUtils.toHex(Be.CryptoUtils.dh(this._ratchetKeys.recv,this._ratchetKeys.priv)),this._rootKey,100,64);this._rootKey=n.slice(0,32),this._chainKeys.send=n.slice(32),this._prevCounter=this._counters.send,this._counters.send=0,this._ratchet=!1}try{return yield new Promise((r,n)=>Hr.__awaiter(this,void 0,void 0,function*(){try{let i=(0,ue.hmac)(this._chainKeys.send,"0"),s=(0,yr.randomBytes)(yr.secretbox.nonceLength),p=(0,yr.secretbox)((0,ue.decodeUTF8)(e),s,Be.HexUtils.toTypedArray(i)),h={ephemeralKey:(0,ue.encodeBase64)(this._ratchetKeys.send),counter:this._counters.send,previousCounter:this._prevCounter,cipherText:(0,ue.encodeBase64)(p),nonce:(0,ue.encodeBase64)(s)};if(this._counters.send=this._counters.send+(this.manualCounter?0:1),this.manualCounter||(this._chainKeys.send=yield(0,ue.hmac)(this._chainKeys.send,"1")),!this._store)return r(h);this._store(this.serialize()).then(()=>r(h)).catch(b=>n(b))}catch(i){n(i)}}))}catch(r){throw new Error(`Unable to Encrypt with error ${r}`)}})}decrypt(e){try{return new Promise((r,n)=>Hr.__awaiter(this,void 0,void 0,function*(){try{if(!(e&&e.hasOwnProperty("ephemeralKey")&&e.hasOwnProperty("counter")&&e.hasOwnProperty("previousCounter")&&e.hasOwnProperty("cipherText")&&e.hasOwnProperty("nonce")&&e.ephemeralKey.length===44&&e.nonce.length===32&&e.cipherText.length>0&&!isNaN(e.counter)&&!isNaN(e.previousCounter)))return n(new Error("decrypt: Message object invalid."));let i=e.counter,s,p;for(let b=0;b<this._skippedMessageKeys.length;b++){let x=this._skippedMessageKeys[b];if(s=yr.secretbox.open((0,ue.decodeBase64)(e.cipherText),(0,ue.decodeBase64)(e.nonce),Be.HexUtils.toTypedArray(x)),!s)return n(new Error("Invalid Message passed for utf-8 conversion"));let R=(0,ue.encodeUTF8)(s);if(s)return this.consumeMessageKey(b),this._store?this._store(this.serialize()).then(()=>r({clearText:R,outOfOrder:!0})).catch(K=>n(K)):r({clearText:R,outOfOrder:!0})}if(this._ratchetKeys.recv===null||(0,ue.encodeBase64)(this._ratchetKeys.recv)!==e.ephemeralKey){if(this._ratchet===!0)return n(new Error("Undecryptable message, ratchet broken."));let b=e.previousCounter,x=(0,ue.decodeBase64)(e.ephemeralKey);this.stageSkippedMessageKeys(this._counters.recv,b,this._chainKeys.recv);let R=(0,ue.kdf)(Be.TypedArrayUtils.toHex(Be.CryptoUtils.dh(x,this._ratchetKeys.priv)),this._rootKey,100,64),K=R.slice(0,32);p=R.slice(32);let V=yield this.stageSkippedMessageKeys(0,i,p),H=V?.messageKey;if(p=V?.chainKey,s=yr.secretbox.open((0,ue.decodeBase64)(e.cipherText),(0,ue.decodeBase64)(e.nonce),Be.HexUtils.toTypedArray(H)),!s)return this.cleanStagedKeys(),n(new Error("Undecryptable message."));this._rootKey=K,this._ratchetKeys.recv=x,this._ratchetKeys.send=null,this._ratchetKeys.priv=null,this._ratchet=!0}else{let b=yield this.stageSkippedMessageKeys(this._counters.recv,i,this._chainKeys.recv),x=b.messageKey;if(p=b.chainKey,s=yr.secretbox.open((0,ue.decodeBase64)(e.cipherText),(0,ue.decodeBase64)(e.nonce),Be.HexUtils.toTypedArray(x)),!s)return this.cleanStagedKeys(),n(new Error("Undecryptable message."))}if(this.commitStagedKeys(),this._counters.recv=i+(this.manualCounter?0:1),this._chainKeys.recv=p,!s)return n(new Error("Invalid Message passed for utf-8 conversion"));let h=(0,ue.encodeUTF8)(s);if(!this._store)return r({clearText:h});this._store(this.serialize()).then(()=>r({clearText:h})).catch(b=>n(b))}catch(i){n(i)}}))}catch(r){throw new Error(`Unable to decrypt the message with error ${r}`)}}stageSkippedMessageKeys(e,r,n){return Hr.__awaiter(this,void 0,void 0,function*(){if(!n)return null;let i=n;e!==0&&(i=(0,ue.hmac)(i,"1"));let s=(0,ue.hmac)(i,"0");this.stageKey(s);for(let p=e;p<r;p++)i=(0,ue.hmac)(i,"1"),s=(0,ue.hmac)(i,"0"),this.stageKey(s);return this.manualCounter||this._stagedSkippedMessageKeys.pop(),{messageKey:s,chainKey:i}})}stageKey(e){this.manualCounter||this._stagedSkippedMessageKeys.push(e)}cleanStagedKeys(){this._stagedSkippedMessageKeys=[]}commitStagedKeys(){this._skippedMessageKeys=this._skippedMessageKeys.concat(this._stagedSkippedMessageKeys)}consumeMessageKey(e){this._skippedMessageKeys.splice(e,1)}};Kn.Ratchet=La});var go=z(qe=>{"use strict";Object.defineProperty(qe,"__esModule",{value:!0});qe.validateSerializedSession=qe.generateKeys=qe.areKeysSet=qe.decryptMessage=qe.encryptMessage=qe.configure=void 0;var Et=je(),kl=qt();function Ml(t,e,r){return mo(t),Promise.all([e.identity((0,Et.convertKeyFormat)(t.identityKey)).handshake((0,Et.convertKeyFormat)(t.handshakeKey)).theirIdentity((0,Et.hexToUInt8)(t.peerKeys.publicKeyIdentity)).theirHandshake((0,Et.hexToUInt8)(t.peerKeys.publicKeyHandshake)).setRole("initiator").computeMasterKey().then(),r.identity((0,Et.convertKeyFormat)(t.identityKey)).handshake((0,Et.convertKeyFormat)(t.handshakeKey)).theirIdentity((0,Et.hexToUInt8)(t.peerKeys.publicKeyIdentity)).theirHandshake((0,Et.hexToUInt8)(t.peerKeys.publicKeyHandshake)).setRole("receiver").computeMasterKey().then()])}qe.configure=Ml;function Kl(t,e){if(typeof t!="string")throw new Error("Message must be of type string");return e.encrypt(t)}qe.encryptMessage=Kl;function Ul(t,e){return e.decrypt(t)}qe.decryptMessage=Ul;function mo(t){if(!t)throw new Error("Keys must be set for the session to be active")}qe.areKeysSet=mo;function Fl(){let t=kl.box.keyPair();return{publicKey:(0,Et.uInt8ToHex)(t.publicKey),secretKey:(0,Et.uInt8ToHex)(t.secretKey)}}qe.generateKeys=Fl;function Bl(t){let r=["cryptomancer","decryptRatchet","encryptRatchet"].reduce((n,i)=>!!t[i]&&n,!0);if(!r)throw new Error("Session Invalid malformed");if(t.cryptomancer&&(r=["handshakeKey","identityKey","peerKeys","rsaKey","sharedKey"].reduce((i,s)=>!!t.cryptomancer[s]&&i,r)),!r)throw new Error("Session Invalid malformed")}qe.validateSerializedSession=Bl});var Eo=z(Un=>{"use strict";Object.defineProperty(Un,"__esModule",{value:!0});Un.server=void 0;var Yr=(Ke(),ke(Me)),_o=yo(),ze=je(),Ct=Mn(),mr=go(),Hl=function(t=!1){let e=new _o.Ratchet(t),r=new _o.Ratchet(t),n={handshakeKey:(0,mr.generateKeys)(),identityKey:(0,mr.generateKeys)(),peerKeys:{}};return{setRsaPrivateKey:function(i){n.rsaKey=i},setPeerIdentityKey:function(i){return Yr.__awaiter(this,void 0,void 0,function*(){try{if(!n.rsaKey)throw new Error("Missing RSA keys");n.peerKeys.publicKeyIdentity=Ct.RSA.decrypt(i,n.rsaKey),n.sharedKey=(0,ze.uInt8ToHex)(ze.CryptoUtils.dh((0,ze.hexToUInt8)(n.peerKeys.publicKeyIdentity),(0,ze.hexToUInt8)(n.identityKey.secretKey)))}catch{throw new Error("RSA decryption failed")}})},getIdentityPublicKey:function(){return Yr.__awaiter(this,void 0,void 0,function*(){let i=Ct.AES.encrypt(n.identityKey.publicKey,n.peerKeys.publicKeyIdentity);if(!n.rsaKey)throw new Error("Missing RSA keys");let s=Ct.RSA.sign(i,n.rsaKey);return(0,ze.uInt8ToHex)((0,ze.stringToUInt8)(JSON.stringify({signature:s,identityPublicKey:i})))})},setPeerHandshakePublicKey:function(i){return Yr.__awaiter(this,void 0,void 0,function*(){if(!n.rsaKey)throw new Error("Missing RSA keys");if(!n.sharedKey)throw new Error("Missing Shared keys");if(n.peerKeys.publicKeyHandshake=Ct.AES.decrypt(Ct.RSA.decrypt(i,n.rsaKey),n.sharedKey),!n.peerKeys.publicKeyHandshake)throw new Error("Missing Peer HK");if(!n.peerKeys.publicKeyIdentity)throw new Error("Missing Peer PK");yield(0,mr.configure)({identityKey:n.identityKey,handshakeKey:n.handshakeKey,peerKeys:n.peerKeys},e,r)})},getHandshakePublicKey:function(){return Yr.__awaiter(this,void 0,void 0,function*(){if(!n.sharedKey)throw new Error("Missing Shared keys");let i=Ct.AES.encrypt(n.handshakeKey.publicKey,n.sharedKey),s=Ct.RSA.sign(i,n.rsaKey);return(0,ze.uInt8ToHex)((0,ze.stringToUInt8)(JSON.stringify({signature:s,handshakePublickey:i})))})},decrypt:function(i){let s=JSON.parse(Ct.RSA.decrypt(i,n.rsaKey));return(0,mr.decryptMessage)(s,r)},encrypt:function(i){return Yr.__awaiter(this,void 0,void 0,function*(){let s=JSON.stringify(yield(0,mr.encryptMessage)(i,e));if(!n.rsaKey)throw new Error("Missing RSA keys");let p=Ct.RSA.sign(s,n.rsaKey);return(0,ze.uInt8ToHex)((0,ze.stringToUInt8)(JSON.stringify({message:s,signature:p})))})},serialize:function(){let i={encryptRatchet:e.serialize(),decryptRatchet:r.serialize(),cryptomancer:n};return(0,ze.uInt8ToHex)((0,ze.stringToUInt8)(JSON.stringify(i)))},resume:function(i){let s=JSON.parse((0,ze.uInt8ToString)((0,ze.hexToUInt8)(i)));(0,mr.validateSerializedSession)(s),e.resume(s.encryptRatchet),r.resume(s.decryptRatchet),n&&Object.keys(s.cryptomancer).forEach(p=>s.cryptomancer[p]?n[p]=s.cryptomancer[p]:null)}}};Un.server=Hl});var To=z(Ft=>{"use strict";Object.defineProperty(Ft,"__esModule",{value:!0});Ft.RSA=Ft.AES=Ft.cryptomancer=void 0;var Yl=Eo(),Vl=t=>(0,Yl.server)(t);Ft.cryptomancer=Vl;var bo=Mn();Object.defineProperty(Ft,"AES",{enumerable:!0,get:function(){return bo.AES}});Object.defineProperty(Ft,"RSA",{enumerable:!0,get:function(){return bo.RSA}})});var Da=z(gr=>{"use strict";Object.defineProperty(gr,"__esModule",{value:!0});gr.Server=gr.Client=void 0;var Oo=(Ke(),ke(Me)),Vr=Oo.__importStar(oo()),Gr=Oo.__importStar(To()),So;(function(t){t.cryptomancer=Vr.cryptomancer,t.AES={encrypt:Vr.AES.encrypt,decrypt:Vr.AES.decrypt},t.RSA={encrypt:Vr.RSA.encrypt,verify:Vr.RSA.verify}})(So||(gr.Client=So={}));var Ao;(function(t){t.cryptomancer=Gr.cryptomancer,t.AES={encrypt:Gr.AES.encrypt,decrypt:Gr.AES.decrypt},t.RSA={decrypt:Gr.RSA.decrypt,sign:Gr.RSA.sign}})(Ao||(gr.Server=Ao={}))});var as=z(Tt=>{"use strict";Object.defineProperty(Tt,"__esModule",{value:!0});Tt.BASE64_CHARACTER_MAP_INVERSE=Tt.BASE64_CHARACTER_MAP=Tt.BASE32_MAP_INVERSE=Tt.BASE32_MAP=void 0;Tt.BASE32_MAP={A:"00000",B:"00001",C:"00010",D:"00011",E:"00100",F:"00101",G:"00110",H:"00111",J:"01000",K:"01001",M:"01010",N:"01011",P:"01100",Q:"01101",R:"01110",S:"01111",T:"10000",V:"10001",W:"10010",X:"10011",Y:"10100",Z:"10101",0:"10110",1:"10111",2:"11000",3:"11001",4:"11010",5:"11011",6:"11100",7:"11101",8:"11110",9:"11111"};Tt.BASE32_MAP_INVERSE={"00000":"A","00001":"B","00010":"C","00011":"D","00100":"E","00101":"F","00110":"G","00111":"H","01000":"J","01001":"K","01010":"M","01011":"N","01100":"P","01101":"Q","01110":"R","01111":"S",1e4:"T",10001:"V",10010:"W",10011:"X",10100:"Y",10101:"Z",10110:"0",10111:"1",11e3:"2",11001:"3",11010:"4",11011:"5",11100:"6",11101:"7",11110:"8",11111:"9"};Tt.BASE64_CHARACTER_MAP={"000000":"A","000001":"B","000010":"C","000011":"D","000100":"E","000101":"F","000110":"G","000111":"H","001000":"I","001001":"J","001010":"K","001011":"L","001100":"M","001101":"N","001110":"O","001111":"P","010000":"Q","010001":"R","010010":"S","010011":"T","010100":"U","010101":"V","010110":"W","010111":"X","011000":"Y","011001":"Z","011010":"a","011011":"b","011100":"c","011101":"d","011110":"e","011111":"f",1e5:"g",100001:"h",100010:"i",100011:"j",100100:"k",100101:"l",100110:"m",100111:"n",101e3:"o",101001:"p",101010:"q",101011:"r",101100:"s",101101:"t",101110:"u",101111:"v",11e4:"w",110001:"x",110010:"y",110011:"z",110100:"0",110101:"1",110110:"2",110111:"3",111e3:"4",111001:"5",111010:"6",111011:"7",111100:"8",111101:"9",111110:"-",111111:"_"};Tt.BASE64_CHARACTER_MAP_INVERSE={A:"000000",B:"000001",C:"000010",D:"000011",E:"000100",F:"000101",G:"000110",H:"000111",I:"001000",J:"001001",K:"001010",L:"001011",M:"001100",N:"001101",O:"001110",P:"001111",Q:"010000",R:"010001",S:"010010",T:"010011",U:"010100",V:"010101",W:"010110",X:"010111",Y:"011000",Z:"011001",a:"011010",b:"011011",c:"011100",d:"011101",e:"011110",f:"011111",g:"100000",h:"100001",i:"100010",j:"100011",k:"100100",l:"100101",m:"100110",n:"100111",o:"101000",p:"101001",q:"101010",r:"101011",s:"101100",t:"101101",u:"101110",v:"101111",w:"110000",x:"110001",y:"110010",z:"110011",0:"110100",1:"110101",2:"110110",3:"110111",4:"111000",5:"111001",6:"111010",7:"111011",8:"111100",9:"111101","-":"111110",_:"111111"}});var Wn,Ua=Sa(()=>{Wn="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"});var ss={};hi(ss,{customAlphabet:()=>ic,customRandom:()=>os,nanoid:()=>oc,random:()=>is,urlAlphabet:()=>Wn});var is,os,ic,oc,ds=Sa(()=>{Ua();Ua();is=t=>crypto.getRandomValues(new Uint8Array(t)),os=(t,e,r)=>{let n=(2<<Math.log2(t.length-1))-1,i=-~(1.6*n*e/t.length);return(s=e)=>{let p="";for(;;){let h=r(i),b=i|0;for(;b--;)if(p+=t[h[b]&n]||"",p.length>=s)return p}}},ic=(t,e=21)=>os(t,e|0,is),oc=(t=21)=>{let e="",r=crypto.getRandomValues(new Uint8Array(t|=0));for(;t--;)e+=Wn[r[t]&63];return e}});var ls=z(Ar=>{"use strict";Object.defineProperty(Ar,"__esModule",{value:!0});Ar.LEAPYEAR=Ar.PERPETUAL=void 0;Ar.PERPETUAL=[[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31],[32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59],[60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90],[91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120],[121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151],[152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181],[182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212],[213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243],[244,245,246,247,248,249,250,251,252,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,273],[274,275,276,277,278,279,280,281,282,283,284,285,286,287,288,289,290,291,292,293,294,295,296,297,298,299,300,301,302,303,304],[305,306,307,308,309,310,311,312,313,314,315,316,317,318,319,320,321,322,323,324,325,326,327,328,329,330,331,332,333,334],[335,336,337,338,339,340,341,342,343,344,345,346,347,348,349,350,351,352,353,354,355,356,357,358,359,360,361,362,363,364,365]];Ar.LEAPYEAR=[[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31],[32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60],[61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91],[92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121],[122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152],[153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182],[183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213],[214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244],[245,246,247,248,249,250,251,252,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,273,274],[275,276,277,278,279,280,281,282,283,284,285,286,287,288,289,290,291,292,293,294,295,296,297,298,299,300,301,302,303,304,305],[306,307,308,309,310,311,312,313,314,315,316,317,318,319,320,321,322,323,324,325,326,327,328,329,330,331,332,333,334,335],[336,337,338,339,340,341,342,343,344,345,346,347,348,349,350,351,352,353,354,355,356,357,358,359,360,361,362,363,364,365,366]]});var zr=z(St=>{"use strict";Object.defineProperty(St,"__esModule",{value:!0});St.generateClientId=sc;St.isNumeric=dc;St.isHexByte=lc;St.checkIdLength=cc;St.getSequenceNumberInBits=uc;St.generateShortClientId=pc;St.getJulianDate=fc;St.getJulianDay=ps;var us=(ds(),ke(ss)),cs=ls();function sc(){return(0,us.customAlphabet)("0123456789ABCDEFGHJKMNPQRSTVW",4)()}function dc(t){return!isNaN(t-parseFloat(t))}function lc(t){return/^[0-9A-F]{2}$/i.test(t)}function cc(t){return t.length===64||t.length===72}function uc(t){return t.toString(2).padStart(7,"0")}function pc(){return(0,us.customAlphabet)("0123456789ABCDEF",2)()}function fc(t=new Date){return`${t.getFullYear()%100}${ps()}`}function ps(t=new Date){let e=t.getMonth(),r=t.getDate()-1;return`${(hc(t.getFullYear())?cs.LEAPYEAR:cs.PERPETUAL)[e][r]}`.padStart(3,"0")}function hc(t){return t%4==0&&t%100!=0||t%400==0}});var Wr=z(We=>{"use strict";Object.defineProperty(We,"__esModule",{value:!0});We.binaryIDToDecimal=yc;We.binaryIDToHex=mc;We.binaryIDToString=gc;We.binaryIDToURLSafe=_c;We.convertRepresentationToBinary=Ec;We.clientIdFromBinary=Oc;We.convertClientIdToBinary=xc;We.convertTimestampToBinary=Ic;We.convertHexToBinary=vc;We.convertBinaryToNumber=Nc;We.binaryToHex=Fa;We.calculateTypeIdentifier=Cc;var Jn=as(),Rt=zr();function yc(t){if(!(0,Rt.checkIdLength)(t))throw new Error("Invalid ID");return BigInt("0b"+t)}function mc(t){if(!(0,Rt.checkIdLength)(t))throw new Error("Invalid ID");return Fa(t)}function gc(t){if(!(0,Rt.checkIdLength)(t))throw new Error("Invalid ID");return t.match(/.{1,8}/g).map(e=>String.fromCharCode(parseInt(e,2))).join("")}function _c(t){if(!(0,Rt.checkIdLength)(t))throw new Error("Invalid ID");return`${t.length===64?"00":""}${t}`.match(/.{1,6}/g).map(e=>Jn.BASE64_CHARACTER_MAP[e]).join("")}function Ec(t,e,r){switch(e){case"BINARY":return t;case"DECIMAL":return bc(t);case"HEX":return Tc(t);case"STRING":return Sc(t);case"URLSAFE":return Ac(t);default:throw new Error(`Invalid representation: ${e}`)}}function bc(t){let e=t.toString(2);if(!(0,Rt.checkIdLength)(e))throw Error("Invalid ID passed for transformation.");return e}function Tc(t){let e=BigInt(`0x${t}`).toString(2);if(!(0,Rt.checkIdLength)(e))throw Error("Invalid ID passed for transformation.");return e}function Sc(t){let e=t.split("").map(r=>r.charCodeAt(0).toString(2)).join("");if(!(0,Rt.checkIdLength)(e))throw Error("Invalid ID passed for transformation.");return e}function Ac(t){let e=t.split("").map(r=>Jn.BASE64_CHARACTER_MAP_INVERSE[r]).join("");if(!(0,Rt.checkIdLength)(e))throw Error("Invalid ID passed for transformation.");return e}function Oc(t){if(t.length!==20)throw new Error("Invalid clientId passed for transformation.");return t.match(/.{1,5}/g).map(e=>Jn.BASE32_MAP_INVERSE[e]).join("")}function xc(t){return t.split("").map(e=>Jn.BASE32_MAP[e]).join("")}function Ic(t,e=32){if(!(0,Rt.isNumeric)(t))throw new Error("Invalid Value Passed");return t.toString(2).padStart(e,"0")}function vc(t,e=8){return BigInt("0x"+t).toString(2).padStart(e,"0")}function Nc(t){return BigInt("0b"+t)}function Fa(t){return BigInt("0b"+t).toString(16)}function Cc(t){return Fa(t.slice(64,72)).padStart(2,"0").toUpperCase()}});var Ba=z(Zn=>{"use strict";Object.defineProperty(Zn,"__esModule",{value:!0});Zn.calculateChecksum=wc;Zn.calculateShortChecksum=Rc;var Pc=Wr();function wc(t,e){if(t.length!==60)throw new Error("Invalid Value is Passed to checksum calculation");let s=("00"+t+(e?(0,Pc.convertHexToBinary)(e):"")+"00").match(/.{1,8}/g).reduce((h,b)=>(parseInt(h,2)+parseInt(b,2)).toString(2)).match(/.{1,4}/g);return(parseInt(s[0],2)^parseInt(s[1],2)).toString(2).padStart(4,"0")}function Rc(t,e){if(console.log(t,t.length),t.length!==45)throw new Error("Invalid Value is Passed to checksum calculation");let n=(t.padStart(45,"0")+e).match(/.{1,6}/g);if(!n)return"0";let s=n.reduce((h,b)=>(parseInt(h,2)+parseInt(b,2)).toString(2)).match(/.{1,3}/g);return s?(parseInt(s[0],2)^parseInt(s[1],2)).toString(2).padStart(3,"0"):"0"}});var fs=z(Ha=>{"use strict";Object.defineProperty(Ha,"__esModule",{value:!0});Ha.generateRRN=kc;var Lc=zr(),Dc={stan:1};function kc(t){let e=new Date,r=e.getFullYear(),n=`${e.getHours()}`.padStart(2,"0"),i=`${t??Dc.stan++}`;return`${r%10}${(0,Lc.getJulianDay)(e)}${n}${i.padStart(6,"0")}`}});var Es=z(Zr=>{"use strict";Object.defineProperty(Zr,"__esModule",{value:!0});Zr.generateShortId=Mc;Zr.validateShortId=_s;Zr.getShortIdComponents=Kc;var ms=Ba(),tr=Wr(),Qn=zr(),hs=(0,Qn.generateShortClientId)(),Jr=0,ys="",gs=1640995200;function Mc(t){if(t&&!(0,Qn.isHexByte)(t))throw new Error("Invalid Type Identifier");let e=Math.floor(new Date().getTime()/1e3)-gs,r=(0,tr.convertTimestampToBinary)(e,30);if(r.length>30)throw new Error("Timestamp is too large. This library has probably outlived its usefullness. Update the Epoch start time to the start of your system if you want to keep going.");Jr===126&&(console.warn("Sequence number has reached maximum value. Switching to a new clientId"),hs=(0,Qn.generateShortClientId)(),Jr=0);let n=(0,tr.convertHexToBinary)(hs,8),i=r+n;ys===i?Jr++:(ys=i,Jr=0);let s=(0,tr.convertHexToBinary)(t,6),p=(0,Qn.getSequenceNumberInBits)(Jr),h=(0,ms.calculateShortChecksum)(i+p,s),b=i+p+h+s;return(0,tr.binaryIDToURLSafe)(b)}function _s(t){try{let e=(0,tr.convertRepresentationToBinary)(t,"URLSAFE"),r=e.slice(0,45),n=e.slice(45,48),i=e.slice(48,54),s=(0,ms.calculateShortChecksum)(r,i);return n===s}catch{return!1}}function Kc(t){let e=_s(t);if(!e)return{isValid:e};let r=(0,tr.convertRepresentationToBinary)(t,"URLSAFE"),n=new Date((parseInt(r.slice(0,30),2)+gs)*1e3),i=(0,tr.binaryToHex)(r.slice(48,54)).toUpperCase();return{isValid:e,timestamp:n,typeIdentifier:i}}});var Os=z(Ve=>{"use strict";Object.defineProperty(Ve,"__esModule",{value:!0});Ve.convertRepresentationToBinary=Ve.validateShortId=Ve.getShortIdComponents=Ve.generateShortId=Ve.generateRRN=void 0;Ve.generateID=Fc;Ve.validateId=Bc;Ve.explainId=Hc;var Ss=Ba(),Pe=Wr(),Xr=zr(),Uc=fs();Object.defineProperty(Ve,"generateRRN",{enumerable:!0,get:function(){return Uc.generateRRN}});var Ya=Es();Object.defineProperty(Ve,"generateShortId",{enumerable:!0,get:function(){return Ya.generateShortId}});Object.defineProperty(Ve,"getShortIdComponents",{enumerable:!0,get:function(){return Ya.getShortIdComponents}});Object.defineProperty(Ve,"validateShortId",{enumerable:!0,get:function(){return Ya.validateShortId}});var bs=(0,Xr.generateClientId)(),As=1640995200,Qr=0,Ts="";function Fc(t,e){if(e&&!(0,Xr.isHexByte)(e))throw new Error("Invalid Type Identifier");let r="1",n=Math.floor(new Date().getTime()/1e3)-As,i=(0,Pe.convertTimestampToBinary)(n);Qr===126&&(console.warn("Sequence number has reached maximum value. Switching to a new clientId"),bs=(0,Xr.generateClientId)(),Qr=0);let s=(0,Pe.convertClientIdToBinary)(bs),p=r+i+s;Ts===p?Qr++:(Ts=p,Qr=0);let h=(0,Xr.getSequenceNumberInBits)(Qr),b=(0,Ss.calculateChecksum)(p+h,e),x=p+h+b+(e?(0,Pe.convertHexToBinary)(e):"");switch(t){case"DECIMAL":return(0,Pe.binaryIDToDecimal)(x);case"BINARY":return x;case"HEX":return(0,Pe.binaryIDToHex)(x);case"STRING":return(0,Pe.binaryIDToString)(x);case"URLSAFE":return(0,Pe.binaryIDToURLSafe)(x);default:return x}}function Bc(t,e,r){if(r&&!(0,Xr.isHexByte)(r))throw new Error("Invalid Type Identifier");let n=(0,Pe.convertRepresentationToBinary)(t,e,r);return(0,Ss.calculateChecksum)(n.slice(0,60),r)===n.slice(60,64)}function Hc(t,e){let r=(0,Pe.convertRepresentationToBinary)(t,e),n=(0,Pe.convertBinaryToNumber)(r.slice(1,33)),i=new Date((parseInt(n.toString(),10)+As)*1e3),s=(0,Pe.clientIdFromBinary)(r.slice(33,53)),p=(0,Pe.convertBinaryToNumber)(r.slice(53,60)),h;return r.length===72&&(h=(0,Pe.calculateTypeIdentifier)(r)),{id:{binary:r,decimal:(0,Pe.binaryIDToDecimal)(r),hex:(0,Pe.binaryIDToHex)(r),string:(0,Pe.binaryIDToString)(r),urlsafe:(0,Pe.binaryIDToURLSafe)(r)},typeIdentifier:h,clientId:s,sequence:p,createdTimestamp:i.getTime(),createdTimestampReadable:i.toISOString(),representation:e}}var Yc=Wr();Object.defineProperty(Ve,"convertRepresentationToBinary",{enumerable:!0,get:function(){return Yc.convertRepresentationToBinary}})});var Xn=z(rr=>{"use strict";var Vc=rr&&rr.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),Gc=rr&&rr.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&Vc(e,t,r)};Object.defineProperty(rr,"__esModule",{value:!0});Gc(Os(),rr)});var cd=z(($m,vu)=>{vu.exports={"401":"Invalid or Expired Link. Cannot proceed","card.number":"Card number","card.cvv":"Security code","card.expiry":"Expiry date","card.name":"Name on card","card.store":"Securely save information for 1-click Checkout","card.store.detail":"Pay faster here and everywhere Surfpay is supported","card.required":"Enter the card number","card.short":"Enter the full card number","card.long":"Card number is too long. Please check the card number","card.numberonly":"Card number contains other characters. Please enter numbers only","card.number.general":"Card is invalid/not supported","card.brand.notsupported":"This card brand is not supported currently","cvv.required":"Enter the CVV/CVC","cvv.short":"CVV is short. Enter the complete security code","cvv.long":"CVV is too long. Please check the length of the security code","cvv.numeric":"CVV should be only numbers","expiry.required":"Please enter a Expiry Date","expiry.invalid":"Enter a valid expiry date","expiry.expired":"The card is expired","name.required":"Enter the name on card","name.long":"Please enter a valid Name",ON_008:"Customer Information update failed",ON_009:"Phone number is a required parameter to perform this payment",ON_010:"This payment method is not supported for this payment",ON_011:"This payment is already completed",ON_012:"An error occurred while initiating payments. Please try again",ON_013:"Unknown Error. Please try again",ON_014:"Maximum Checks Exceeded. Please refresh Page",ON_015:"Payment Status cannot be fetched currently. Please Try Again",ON_016:"Invalid Card Details",ON_017:"Email is a required parameter to perform a this payment",ON_018:"Billing Address is a required parameter to perform a this payment",ON_019:"3DS check Failed","pay.addMoney":"Add Money with $PAYMENT_METHOD$","pay.book":"Book with $PAYMENT_METHOD$","pay.buy":"Buy with $PAYMENT_METHOD$","pay.checkout":"Check out with $PAYMENT_METHOD$","pay.continue":"Continue with $PAYMENT_METHOD$","pay.contribute":"Contribute with $PAYMENT_METHOD$","pay.donate":"Donate with $PAYMENT_METHOD$","pay.order":"Order with $PAYMENT_METHOD$","pay.pay":"Pay with $PAYMENT_METHOD$","pay.rent":"Rent with $PAYMENT_METHOD$","pay.subscribe":"Subscribe with $PAYMENT_METHOD$","pay.support":"Support with $PAYMENT_METHOD$","pay.tip":"Tip with $PAYMENT_METHOD$","pay.topup":"Top-up with $PAYMENT_METHOD$",ONL_0001:"Card is invalid/not supported",ONL_0002:"Technical Error",ONL_0003:"Technical Error",ONL_0004:"Technical Error. Please try again",ONL_0005:"3DS Authorisation Failed. Try with another card",ONL_0006:"3DS Authorisation Failed. Try with another card",ONL_0007:"3DS Authorisation Failed. Try with another card",ONL_0008:"3DS Authorisation Failed. Try with another card",ONL_0009:"Technical Error. Please try again",ONL_0010:"Technical Error",ONL_0011:"Technical Error",ONL_0012:"Technical Error",ONL_0013:"Technical Error",ONL_0014:"Technical Error",ONL_0015:"Technical Error",ONL_0016:"CVV Verification Failed. Please enter the correct CVV.",ONL_0017:"Technical Error",ONL_0018:"Technical Error",ONL_0019:"Technical Error",ONL_0020:"Technical Error",ONL_0021:"Technical Error",ONL_0022:"Apple Pay Failed. Please try with another method.",ONL_0023:"Apple Pay Failed. Please try with another method.",ONL_0024:"Apple Pay Failed. Please try with another method.",ONL_0025:"Apple Pay Failed. Please try with another method.",ONL_0026:"Klarna payment failed. Please try with another method.",ONL_0027:"Klarna payment failed. Please try with another method.",ONL_0028:"Klarna payment failed. Please try with another method.",ONL_0029:"Klarna payment failed. Please fix the error and try again.",ONL_0030:"Klarna payment failed. Please try with another method.",ONL_0031:"Klarna payment failed. Please try with another method.",ONL_0032:"Klarna payment failed. Please try with another method.",ONL_0033:"Klarna payment failed. Please try with another method.",ONL_0034:"Name is a required parameter to perform this payment.",ONL_0035:"Last name is mandatory for this payment type",ONL_0036:"Invalid last name. Expecting atleast 2 characters.",ONL_0037:"Network Error. Please check network and retry. If issue persists please contact the support email on this page.",ONL_0038:"Google Pay failed. Please try with another method.",ONL_0039:"Google Pay is not supported on your device.",ONL_0040:"Apple Pay is not supported on your device.",ONL_0041:"We are noticing a high failure rate on this card. Please use a different card.",ONL_0042:"Vipps is not initialized properly. Please try again."}});var ud=z((jm,Nu)=>{Nu.exports={"401":"L\xE4nken har antingen g\xE5tt ut eller s\xE5 \xE4r den ogiltig.","card.number":"Kortnummer","card.cvv":"S\xE4kerhetskod","card.expiry":"Utg\xE5ngsdatum","card.name":"Namn p\xE5 kortet","card.store":"Spara informationen f\xF6r snabbare betalning n\xE4sta g\xE5ng","card.store.detail":"Betala snabbare \xF6verallt d\xE4r Surfboard Payments st\xF6ds","card.required":"Ange kortnumret","card.short":"Ange hela kortnumret","card.long":"Kortnumret \xE4r f\xF6r l\xE5ngt. Kontrollera kortnumret","card.numberonly":"Kortnumret inneh\xE5ller ogiltiga tecken. Ange endast siffror","card.number.general":"Kortet \xE4r ogiltigt/st\xF6ds inte","card.brand.notsupported":"Detta kortm\xE4rke st\xF6ds inte","cvv.required":"Ange CVV/CVC","cvv.short":"CVV \xE4r f\xF6r kort. Ange den fullst\xE4ndiga s\xE4kerhetskoden","cvv.long":"CVV \xE4r f\xF6r l\xE5ngt. Kontrollera l\xE4ngden p\xE5 s\xE4kerhetskoden","cvv.numeric":"CVV ska endast best\xE5 av siffror","expiry.required":"Ange kortets utg\xE5ngsdatum","expiry.invalid":"Ange ett giltigt utg\xE5ngsdatum","expiry.expired":"Kortets utg\xE5ngsdatum har passerat","name.required":"Ange kortinnehavarens namn","name.long":"Ange ett giltigt namn",ON_008:"Uppdatering av kundinformation misslyckades",ON_009:"Telefonnummer \xE4r obligatoriskt f\xF6r att genomf\xF6ra en Swish-betalning",ON_010:"Denna betalmetod st\xF6ds inte f\xF6r denna betalning",ON_011:"Denna betalning \xE4r redan slutf\xF6rd",ON_012:"Ett fel intr\xE4ffade n\xE4r betalningen initierades. F\xF6rs\xF6k igen",ON_013:"Ok\xE4nt fel. F\xF6rs\xF6k igen",ON_014:"Maximalt antal f\xF6rs\xF6k \xF6verskridet. Uppdatera sidan och f\xF6rs\xF6k igen",ON_015:"Betalningsstatusen kunde inte h\xE4mtas. F\xF6rs\xF6k igen",ON_016:"Ogiltiga kortuppgifter",ON_017:"E-post \xE4r obligatoriskt f\xF6r att slutf\xF6ra denna betalning",ON_018:"Faktureringsadress \xE4r obligatoriskt f\xF6r att slutf\xF6ra denna betalning",ON_019:"3DS-autentisering misslyckades","pay.addMoney":"L\xE4gg till pengar med $PAYMENT_METHOD$","pay.book":"Boka med $PAYMENT_METHOD$","pay.buy":"K\xF6p med $PAYMENT_METHOD$","pay.checkout":"Betala med $PAYMENT_METHOD$","pay.continue":"Forts\xE4tt med $PAYMENT_METHOD$","pay.contribute":"Bidra med $PAYMENT_METHOD$","pay.donate":"Donera med $PAYMENT_METHOD$","pay.order":"Best\xE4ll med $PAYMENT_METHOD$","pay.pay":"Betala med $PAYMENT_METHOD$","pay.rent":"Hyr med $PAYMENT_METHOD$","pay.subscribe":"Prenumerera med $PAYMENT_METHOD$","pay.support":"St\xF6d med $PAYMENT_METHOD$","pay.tip":"Ge dricks med $PAYMENT_METHOD$","pay.topup":"Fyll p\xE5 med $PAYMENT_METHOD$",ONL_0001:"Kortet \xE4r ogiltigt/st\xF6ds inte",ONL_0002:"Tekniskt fel",ONL_0003:"Tekniskt fel",ONL_0004:"Tekniskt fel. Tekniskt fel. F\xF6rs\xF6k igen.",ONL_0005:"3DS-autentisering misslyckades. F\xF6rs\xF6k med ett annat kort",ONL_0006:"3DS-autentisering misslyckades. F\xF6rs\xF6k med ett annat kort",ONL_0007:"3DS-autentisering misslyckades. F\xF6rs\xF6k med ett annat kort",ONL_0008:"3DS-autentisering misslyckades. F\xF6rs\xF6k med ett annat kort",ONL_0009:"Tekniskt fel. Tekniskt fel. F\xF6rs\xF6k igen.",ONL_0010:"Tekniskt fel",ONL_0011:"Tekniskt fel",ONL_0012:"Tekniskt fel",ONL_0013:"Tekniskt fel",ONL_0014:"Tekniskt fel",ONL_0015:"Tekniskt fel",ONL_0016:"CVV-verifiering misslyckades. Ange r\xE4tt CVV.",ONL_0017:"Tekniskt fel",ONL_0018:"Tekniskt fel",ONL_0019:"Tekniskt fel",ONL_0020:"Tekniskt fel",ONL_0021:"Tekniskt fel",ONL_0022:"Apple Pay misslyckades. F\xF6rs\xF6k med en annan metod.",ONL_0023:"Apple Pay misslyckades. F\xF6rs\xF6k med en annan metod.",ONL_0024:"Apple Pay misslyckades. F\xF6rs\xF6k med en annan metod.",ONL_0025:"Apple Pay misslyckades. F\xF6rs\xF6k med en annan metod.",ONL_0026:"Klarna-betalning misslyckades. F\xF6rs\xF6k med en annan metod.",ONL_0027:"Klarna-betalning misslyckades. F\xF6rs\xF6k med en annan metod.",ONL_0028:"Klarna-betalning misslyckades. F\xF6rs\xF6k med en annan metod.",ONL_0029:"Klarna-betalning misslyckades. R\xE4tta till felet och f\xF6rs\xF6k igen.",ONL_0030:"Klarna-betalning misslyckades. F\xF6rs\xF6k med en annan metod.",ONL_0031:"Klarna-betalning misslyckades. F\xF6rs\xF6k med en annan metod.",ONL_0032:"Klarna-betalning misslyckades. F\xF6rs\xF6k med en annan metod.",ONL_0033:"Klarna-betalning misslyckades. F\xF6rs\xF6k med en annan metod.",ONL_0034:"Namn \xE4r en obligatorisk parameter f\xF6r att utf\xF6ra denna betalning.",ONL_0035:"Efternamn \xE4r obligatoriskt f\xF6r denna betalningstyp",ONL_0036:"Ogiltigt efternamn. F\xF6rv\xE4ntar sig minst 2 tecken.",ONL_0037:"N\xE4tverksfel. Kontrollera n\xE4tverket och f\xF6rs\xF6k igen. Om problemet kvarst\xE5r, kontakta support via e-postadressen p\xE5 denna sida.",ONL_0038:"Google Pay misslyckades. F\xF6rs\xF6k med en annan metod.",ONL_0039:"Google Pay st\xF6ds inte p\xE5 din enhet.",ONL_0040:"Apple Pay st\xF6ds inte p\xE5 din enhet.",ONL_0041:"Det h\xE4r kortet har ofta problem med att godk\xE4nna k\xF6p. V\xE4nligen anv\xE4nd ett annat kort",ONL_0042:"Vipps \xE4r inte initierat ordentligt. F\xF6rs\xF6k igen."}});var pd=z((qm,Cu)=>{Cu.exports={"401":"Virheellinen tai vanhentunut linkki. Ei voida jatkaa","card.number":"Kortin numero","card.cvv":"Turvakoodi","card.expiry":"Viimeinen voimassaolop\xE4iv\xE4","card.name":"Kortinhaltijan nimi","card.store":"Tallenna tiedot turvallisesti nopeampaa maksamista varten","card.store.detail":"Maksa nopeammin t\xE4\xE4ll\xE4 ja kaikkialla, miss\xE4 Surfpay on k\xE4yt\xF6ss\xE4","card.required":"Sy\xF6t\xE4 kortin numero","card.short":"Sy\xF6t\xE4 koko kortin numero","card.long":"Kortin numero on liian pitk\xE4. Tarkista kortin numero","card.numberonly":"Kortin numero sis\xE4lt\xE4\xE4 muita merkkej\xE4. Sy\xF6t\xE4 vain numeroita","card.number.general":"Korti on virheellinen/tukematon","card.brand.notsupported":"T\xE4m\xE4 kortimerkki ei ole t\xE4ll\xE4 hetkell\xE4 tuettu","cvv.required":"Sy\xF6t\xE4 CVV/CVC","cvv.short":"CVV on liian lyhyt. Sy\xF6t\xE4 koko turvakoodi","cvv.long":"CVV on liian pitk\xE4. Tarkista turvakoodin pituus","cvv.numeric":"CVV:n tulisi olla vain numeroita","expiry.required":"Sy\xF6t\xE4 viimeinen voimassaolop\xE4iv\xE4","expiry.invalid":"Sy\xF6t\xE4 kelvollinen viimeinen voimassaolop\xE4iv\xE4","expiry.expired":"Kortti on vanhentunut","name.required":"Sy\xF6t\xE4 kortinhaltijan nimi","name.long":"Sy\xF6t\xE4 kelvollinen nimi",ON_008:"Asiakastietojen p\xE4ivitys ep\xE4onnistui",ON_009:"Puhelinnumero on pakollinen t\xE4m\xE4n maksun suorittamiseksi",ON_010:"T\xE4t\xE4 maksutapaa ei tueta t\xE4lle maksulle",ON_011:"T\xE4m\xE4 maksu on jo suoritettu",ON_012:"Virhe maksun aloittamisessa. Yrit\xE4 uudelleen",ON_013:"Tuntematon virhe. Yrit\xE4 uudelleen",ON_014:"Enimm\xE4ism\xE4\xE4r\xE4 tarkistuksia ylitetty. P\xE4ivit\xE4 sivu",ON_015:"Maksun tilaa ei voida noutaa t\xE4ll\xE4 hetkell\xE4. Yrit\xE4 uudelleen",ON_016:"Virheelliset kortitiedot",ON_017:"S\xE4hk\xF6posti on pakollinen t\xE4m\xE4n maksun suorittamiseksi",ON_018:"Laskutusosoite on pakollinen t\xE4m\xE4n maksun suorittamiseksi",ON_019:"3DS-todennus ep\xE4onnistui","pay.addMoney":"Lis\xE4\xE4 rahaa $PAYMENT_METHOD$","pay.book":"Tee varaus $PAYMENT_METHOD$","pay.buy":"Osta $PAYMENT_METHOD$","pay.checkout":"Siirry maksamaan $PAYMENT_METHOD$","pay.continue":"Jatka $PAYMENT_METHOD$","pay.contribute":"Lahjoita $PAYMENT_METHOD$","pay.donate":"Lahjoita $PAYMENT_METHOD$","pay.order":"Tilaa $PAYMENT_METHOD$","pay.pay":"Maksa $PAYMENT_METHOD$","pay.rent":"Vuokraa $PAYMENT_METHOD$","pay.subscribe":"Tilaa $PAYMENT_METHOD$","pay.support":"Tue $PAYMENT_METHOD$","pay.tip":"Anna tippi $PAYMENT_METHOD$","pay.topup":"T\xE4ydenn\xE4 $PAYMENT_METHOD$",ONL_0001:"Korti on virheellinen/tukematon",ONL_0002:"Tekninen virhe",ONL_0003:"Tekninen virhe",ONL_0004:"Tekninen virhe. Yrit\xE4 uudelleen",ONL_0005:"3DS-todennus ep\xE4onnistui. Kokeile toisella kortilla",ONL_0006:"3DS-todennus ep\xE4onnistui. Kokeile toisella kortilla",ONL_0007:"3DS-todennus ep\xE4onnistui. Kokeile toisella kortilla",ONL_0008:"3DS-todennus ep\xE4onnistui. Kokeile toisella kortilla",ONL_0009:"Tekninen virhe. Yrit\xE4 uudelleen",ONL_0010:"Tekninen virhe",ONL_0011:"Tekninen virhe",ONL_0012:"Tekninen virhe",ONL_0013:"Tekninen virhe",ONL_0014:"Tekninen virhe",ONL_0015:"Tekninen virhe",ONL_0016:"CVV-vahvistus ep\xE4onnistui. Anna oikea CVV.",ONL_0017:"Tekninen virhe",ONL_0018:"Tekninen virhe",ONL_0019:"Tekninen virhe",ONL_0020:"Tekninen virhe",ONL_0021:"Tekninen virhe",ONL_0022:"Apple Pay ep\xE4onnistui. Yrit\xE4 toisella menetelm\xE4ll\xE4.",ONL_0023:"Apple Pay ep\xE4onnistui. Yrit\xE4 toisella menetelm\xE4ll\xE4.",ONL_0024:"Apple Pay ep\xE4onnistui. Yrit\xE4 toisella menetelm\xE4ll\xE4.",ONL_0025:"Apple Pay ep\xE4onnistui. Yrit\xE4 toisella menetelm\xE4ll\xE4.",ONL_0026:"Klarna-maksu ep\xE4onnistui. Yrit\xE4 toisella menetelm\xE4ll\xE4.",ONL_0027:"Klarna-maksu ep\xE4onnistui. Yrit\xE4 toisella menetelm\xE4ll\xE4.",ONL_0028:"Klarna-maksu ep\xE4onnistui. Yrit\xE4 toisella menetelm\xE4ll\xE4.",ONL_0029:"Klarna-maksu ep\xE4onnistui. Korjaa virhe ja yrit\xE4 uudelleen.",ONL_0030:"Klarna-maksu ep\xE4onnistui. Yrit\xE4 toisella menetelm\xE4ll\xE4.",ONL_0031:"Klarna-maksu ep\xE4onnistui. Yrit\xE4 toisella menetelm\xE4ll\xE4.",ONL_0032:"Klarna-maksu ep\xE4onnistui. Yrit\xE4 toisella menetelm\xE4ll\xE4.",ONL_0033:"Klarna-maksu ep\xE4onnistui. Yrit\xE4 toisella menetelm\xE4ll\xE4.",ONL_0034:"Nimi on pakollinen parametri t\xE4m\xE4n maksun suorittamiseen.",ONL_0035:"Sukunimi on pakollinen t\xE4lle maksutyypille",ONL_0036:"Virheellinen sukunimi. Odottaa v\xE4hint\xE4\xE4n 2 merkki\xE4.",ONL_0037:"Verkkovirhe. Tarkista verkkoyhteys ja yrit\xE4 uudelleen. Jos ongelma jatkuu, ota yhteytt\xE4 t\xE4m\xE4n sivun tukis\xE4hk\xF6postiin.",ONL_0038:"Google Pay ep\xE4onnistui. Yrit\xE4 toisella menetelm\xE4ll\xE4.",ONL_0039:"Laitteesi ei tue Google Payta.",ONL_0040:"Laitteesi ei tue Apple Payta.",ONL_0041:"T\xE4ll\xE4 kortilla on korkea hylk\xE4ysaste. Ole hyv\xE4 ja k\xE4yt\xE4 toista korttia.",ONL_0042:"Vippsi\xE4 ei ole alustettu oikein. Yrit\xE4 uudelleen."}});var fd=z((zm,Pu)=>{Pu.exports={"401":"Ugyldigt eller udl\xF8bet link. Kan ikke forts\xE6tte","card.number":"Kortnummer","card.cvv":"Sikkerhedskode","card.expiry":"Udl\xF8bsdato","card.name":"Navn p\xE5 kort","card.store":"Gem oplysningerne sikkert for hurtigere betaling","card.store.detail":"Betal hurtigere her og alle steder, hvor Surfpay underst\xF8ttes","card.required":"Indtast kortnummer","card.short":"Indtast det fulde kortnummer","card.long":"Kortnummeret er for langt. Tjek kortnummeret","card.numberonly":"Kortnummeret indeholder andre tegn. Indtast kun tal","card.number.general":"Kortet er ugyldigt/ikke underst\xF8ttet","card.brand.notsupported":"Dette kortm\xE6rke underst\xF8ttes ikke i \xF8jeblikket","cvv.required":"Indtast CVV/CVC","cvv.short":"CVV er for kort. Indtast den fulde sikkerhedskode","cvv.long":"CVV er for lang. Tjek l\xE6ngden af sikkerhedskoden","cvv.numeric":"CVV skal kun v\xE6re tal","expiry.required":"Indtast en udl\xF8bsdato","expiry.invalid":"Indtast en gyldig udl\xF8bsdato","expiry.expired":"Kortet er udl\xF8bet","name.required":"Indtast navnet p\xE5 kortet","name.long":"Indtast et gyldigt navn",ON_008:"Opdatering af kundeoplysninger mislykkedes",ON_009:"Telefonnummer er p\xE5kr\xE6vet for at gennemf\xF8re denne betaling",ON_010:"Denne betalingsmetode underst\xF8ttes ikke for denne betaling",ON_011:"Denne betaling er allerede gennemf\xF8rt",ON_012:"En fejl opstod under initiering af betalinger. Pr\xF8v igen",ON_013:"Ukendt fejl. Pr\xF8v igen",ON_014:"Maksimalt antal fors\xF8g overskredet. Opdater siden",ON_015:"Betalingsstatus kan ikke hentes i \xF8jeblikket. Pr\xF8v igen",ON_016:"Ugyldige kortoplysninger",ON_017:"E-mail er p\xE5kr\xE6vet for at gennemf\xF8re denne betaling",ON_018:"Faktureringsadresse er p\xE5kr\xE6vet for at gennemf\xF8re denne betaling",ON_019:"3DS-godkendelse mislykkedes","pay.addMoney":"Tilf\xF8j penge med $PAYMENT_METHOD$","pay.book":"Bestil med $PAYMENT_METHOD$","pay.buy":"K\xF8b med $PAYMENT_METHOD$","pay.checkout":"Betal med $PAYMENT_METHOD$","pay.continue":"Forts\xE6t med $PAYMENT_METHOD$","pay.contribute":"Bidrag med $PAYMENT_METHOD$","pay.donate":"Doner med $PAYMENT_METHOD$","pay.order":"Bestil med $PAYMENT_METHOD$","pay.pay":"Betal med $PAYMENT_METHOD$","pay.rent":"Lej med $PAYMENT_METHOD$","pay.subscribe":"Abonner med $PAYMENT_METHOD$","pay.support":"St\xF8t med $PAYMENT_METHOD$","pay.tip":"Giv drikkepenge med $PAYMENT_METHOD$","pay.topup":"Fyld op med $PAYMENT_METHOD$",ONL_0001:"Kortet er ugyldigt/ikke underst\xF8ttet",ONL_0002:"Teknisk fejl",ONL_0003:"Teknisk fejl",ONL_0004:"Teknisk fejl. Pr\xF8v igen",ONL_0005:"3DS-godkendelse mislykkedes. Pr\xF8v med et andet kort",ONL_0006:"3DS-godkendelse mislykkedes. Pr\xF8v med et andet kort",ONL_0007:"3DS-godkendelse mislykkedes. Pr\xF8v med et andet kort",ONL_0008:"3DS-godkendelse mislykkedes. Pr\xF8v med et andet kort",ONL_0009:"Teknisk fejl. Pr\xF8v igen",ONL_0010:"Teknisk fejl",ONL_0011:"Teknisk fejl",ONL_0012:"Teknisk fejl",ONL_0013:"Teknisk fejl",ONL_0014:"Teknisk fejl",ONL_0015:"Teknisk fejl",ONL_0016:"CVV-bekr\xE6ftelse mislykkedes. Indtast venligst det korrekte CVV.",ONL_0017:"Teknisk fejl",ONL_0018:"Teknisk fejl",ONL_0019:"Teknisk fejl",ONL_0020:"Teknisk fejl",ONL_0021:"Teknisk fejl",ONL_0022:"Apple Pay mislykkedes. Pr\xF8v venligst med en anden metode.",ONL_0023:"Apple Pay mislykkedes. Pr\xF8v venligst med en anden metode.",ONL_0024:"Apple Pay mislykkedes. Pr\xF8v venligst med en anden metode.",ONL_0025:"Apple Pay mislykkedes. Pr\xF8v venligst med en anden metode.",ONL_0026:"Klarna-betaling mislykkedes. Pr\xF8v venligst med en anden metode.",ONL_0027:"Klarna-betaling mislykkedes. Pr\xF8v venligst med en anden metode.",ONL_0028:"Klarna-betaling mislykkedes. Pr\xF8v venligst med en anden metode.",ONL_0029:"Klarna-betaling mislykkedes. Ret venligst fejlen, og pr\xF8v igen.",ONL_0030:"Klarna-betaling mislykkedes. Pr\xF8v venligst med en anden metode.",ONL_0031:"Klarna-betaling mislykkedes. Pr\xF8v venligst med en anden metode.",ONL_0032:"Klarna-betaling mislykkedes. Pr\xF8v venligst med en anden metode.",ONL_0033:"Klarna-betaling mislykkedes. Pr\xF8v venligst med en anden metode.",ONL_0034:"Navn er en n\xF8dvendig parameter for at udf\xF8re denne betaling.",ONL_0035:"Efternavn er obligatorisk for denne betalingstype",ONL_0036:"Ugyldigt efternavn. Forventer mindst 2 tegn.",ONL_0037:"Netv\xE6rksfejl. Tjek venligst netv\xE6rket og pr\xF8v igen. Hvis problemet forts\xE6tter, kontakt support via e-mailadressen p\xE5 denne side.",ONL_0038:"Google Pay mislykkedes. Pr\xF8v venligst med en anden metode.",ONL_0039:"Google Pay underst\xF8ttes ikke p\xE5 din enhed.",ONL_0040:"Apple Pay underst\xF8ttes ikke p\xE5 din enhed.",ONL_0041:"Dette kort har en h\xF8j afvisningsrate. Brug venligst et andet kort.",ONL_0042:"Vipps er ikke initialiseret korrekt. Pr\xF8v venligst igen."}});var hd=z((Wm,wu)=>{wu.exports={"401":"Lenken er enten utl\xF8pt eller ugyldig","card.number":"Kortnummer","card.cvv":"Sikkerhetskode","card.expiry":"Utl\xF8psdato","card.name":"Navn p\xE5 kortet","card.store":"Lagre informasjonen for raskere betaling neste gang","card.store.detail":"Betal raskere overalt hvor Surfboard Payments st\xF8ttes","card.required":"Oppgi kortnummeret","card.short":"Oppgi hele kortnummeret","card.long":"Kortnummeret er for langt. Kontroller kortnummeret","card.numberonly":"Kortnummeret inneholder ugyldige tegn. Oppgi kun tall","card.number.general":"Kortet er ugyldig/st\xF8ttes ikke","card.brand.notsupported":"Dette kortmerket st\xF8ttes ikke","cvv.required":"Oppgi CVV/CVC","cvv.short":"CVV er for kort. Oppgi hele sikkerhetskoden","cvv.long":"CVV er for lang. Kontroller lengden p\xE5 sikkerhetskoden","cvv.numeric":"CVV skal kun best\xE5 av tall","expiry.required":"Oppgi kortets utl\xF8psdato","expiry.invalid":"Oppgi en gyldig utl\xF8psdato","expiry.expired":"Kortet er utl\xF8pt","name.required":"Oppgi kortholderens navn","name.long":"Oppgi et gyldig navn",ON_008:"Oppdatering av kundeinformasjon mislyktes",ON_009:"Telefonnummer er p\xE5krevd for \xE5 gjennomf\xF8re en Vipps-betaling",ON_010:"Denne betalingsmetoden st\xF8ttes ikke for denne betalingen",ON_011:"Denne betalingen er allerede fullf\xF8rt",ON_012:"Det oppstod en feil ved initiering av betalingen. Pr\xF8v igjen",ON_013:"Ukjent feil. Pr\xF8v igjen",ON_014:"Maksimalt antall fors\xF8k overskredet. Oppdater siden og pr\xF8v igjen",ON_015:"Betalingsstatus kunne ikke hentes. Pr\xF8v igjen",ON_016:"Ugyldige kortopplysninger",ON_017:"E-post er p\xE5krevd for \xE5 fullf\xF8re denne betalingen",ON_018:"Faktureringsadresse er p\xE5krevd for \xE5 fullf\xF8re denne betalingen",ON_019:"3DS-autentisering mislyktes","pay.addMoney":"Legg til penger med $PAYMENT_METHOD$","pay.book":"Bestill med $PAYMENT_METHOD$","pay.buy":"Kj\xF8p med $PAYMENT_METHOD$","pay.checkout":"Betal med $PAYMENT_METHOD$","pay.continue":"Fortsett med $PAYMENT_METHOD$","pay.contribute":"Bidra med $PAYMENT_METHOD$","pay.donate":"Doner med $PAYMENT_METHOD$","pay.order":"Bestill med $PAYMENT_METHOD$","pay.pay":"Betal med $PAYMENT_METHOD$","pay.rent":"Lei med $PAYMENT_METHOD$","pay.subscribe":"Abonner med $PAYMENT_METHOD$","pay.support":"St\xF8tt med $PAYMENT_METHOD$","pay.tip":"Gi tips med $PAYMENT_METHOD$","pay.topup":"Fyll p\xE5 med $PAYMENT_METHOD$",ONL_0001:"Kortet er ugyldig/st\xF8ttes ikke",ONL_0002:"Teknisk feil",ONL_0003:"Teknisk feil",ONL_0004:"Teknisk feil. Pr\xF8v igjen",ONL_0005:"3DS-autentisering mislyktes. Pr\xF8v med et annet kort",ONL_0006:"3DS-autentisering mislyktes. Pr\xF8v med et annet kort",ONL_0007:"3DS-autentisering mislyktes. Pr\xF8v med et annet kort",ONL_0008:"3DS-autentisering mislyktes. Pr\xF8v med et annet kort",ONL_0009:"Teknisk feil. Pr\xF8v igjen",ONL_0010:"Teknisk feil",ONL_0011:"Teknisk feil",ONL_0012:"Teknisk feil",ONL_0013:"Teknisk feil",ONL_0014:"Teknisk feil",ONL_0015:"Teknisk feil",ONL_0016:"CVV-verifisering mislyktes. Oppgi riktig CVV",ONL_0017:"Teknisk feil",ONL_0018:"Teknisk feil",ONL_0019:"Teknisk feil",ONL_0020:"Teknisk feil",ONL_0021:"Teknisk feil",ONL_0022:"Apple Pay mislyktes. Pr\xF8v med en annen metode",ONL_0023:"Apple Pay mislyktes. Pr\xF8v med en annen metode",ONL_0024:"Apple Pay mislyktes. Pr\xF8v med en annen metode",ONL_0025:"Apple Pay mislyktes. Pr\xF8v med en annen metode",ONL_0026:"Klarna-betaling mislyktes. Pr\xF8v med en annen metode",ONL_0027:"Klarna-betaling mislyktes. Pr\xF8v med en annen metode",ONL_0028:"Klarna-betaling mislyktes. Pr\xF8v med en annen metode",ONL_0029:"Klarna-betaling mislyktes. Rett opp feilen og pr\xF8v igjen",ONL_0030:"Klarna-betaling mislyktes. Pr\xF8v med en annen metode",ONL_0031:"Klarna-betaling mislyktes. Pr\xF8v med en annen metode",ONL_0032:"Klarna-betaling mislyktes. Pr\xF8v med en annen metode",ONL_0033:"Klarna-betaling mislyktes. Pr\xF8v med en annen metode",ONL_0034:"Navn er et p\xE5krevd parameter for \xE5 utf\xF8re denne betalingen",ONL_0035:"Etternavn er p\xE5krevd for denne betalingstypen",ONL_0036:"Ugyldig etternavn. Forventer minst 2 tegn",ONL_0037:"Nettverksfeil. Kontroller nettverket og pr\xF8v igjen. Hvis problemet vedvarer, kontakt support via e-postadressen p\xE5 denne siden",ONL_0038:"Google Pay mislyktes. Pr\xF8v med en annen metode",ONL_0039:"Google Pay st\xF8ttes ikke p\xE5 enheten din",ONL_0040:"Apple Pay st\xF8ttes ikke p\xE5 enheten din",ONL_0041:"Dette kortet har ofte problemer med \xE5 godkjenne kj\xF8p. Vennligst bruk et annet kort",ONL_0042:"Vipps er ikke initialisert riktig. Pr\xF8v igjen."}});var ld=ht(Da());var Pt=class extends Error{constructor(e,r,n=!1){super(`${e}:${r}`),n&&(window.SurfboardOnlineSDK=null)}};var Jt={ValidationFailed:"ON_001",NotInitialised:"ON_002",InvalidEnvironment:"ON_003",InvalidInitialisation:"ON_004",ConstantChangeAttempt:"ON_005"};var Bt=class extends Pt{constructor(e){super(Jt.ValidationFailed,e)}},Zt=class extends Pt{constructor(e){super(Jt.InvalidEnvironment,e,!0)}},ve=class extends Pt{constructor(e){super(Jt.ConstantChangeAttempt,e)}};var _r=class extends Pt{constructor(e){super(Jt.NotInitialised,e)}},Ht=class extends Pt{constructor(e){super(Jt.InvalidInitialisation,e,!0)}};var Gl=class{constructor(t){this.listeners={},this.captureRejections=t.captureRejections}addListener(t,e){return this.listeners[t]||(this.listeners[t]=[]),this.listeners[t].push(e),this}emit(t,...e){if(!this.listeners[t])return!1;let r=this.listeners[t];for(let n of r)this.captureRejections?Promise.resolve(n(...e)).catch(i=>{console.error(i)}):n(...e);return!0}},$l=class{constructor(){this._size=0}get size(){return this._size}enQueue(t,e){this._size++;let r={item:t,id:e,next:void 0};this.head?(this.tail&&(this.tail.next=r),this.tail=r):(this.head=r,this.tail=r)}deQueue(){if(this._size--,this.head){let t=this.head.item,e=this.head.id;return this.head=this.head.next,{value:t,id:e}}}peek(){return this.head?.item}clear(){this._size=0,this.head=this.tail=void 0}},Fn=class{constructor(t){this.options=t,this.queue=new $l,this.currentQueued=0,this.destroy=!1,this.ee=new Gl({captureRejections:!1}),this.executeFunctions().then(()=>{this.ee.emit("log","Execution complete")}).catch(e=>{this.ee.emit("log",`Error in executeFunctions: ${e.message}`),console.error(e)})}on(t,e){this.ee.addListener(t,e)}addToQueue(t,e=new Date().getTime().toString()){this.queue.enQueue({method:()=>t.function,args:t.args},e),this.ee.emit("add")}get currentStatus(){return{queueSize:this.queue.size,currentlyQueued:this.currentQueued,maxThreshold:this.options.maxThreshold}}clearQueue(){this.queue.clear(),this.ee.emit("clear")}async delay(){await new Promise(t=>{setTimeout(()=>{t(null)},this.options.delayExecutions)})}async executeFunctions(){for(;;){if(this.destroy){this.ee.emit("log","Destroy called");break}if(this.currentQueued<this.options.maxThreshold&&this.queue.size!==0){this.ee.emit("log","Called to execute");let t=[];for(let e=0;e<this.options.maxThreshold&&this.queue.size>0;e++){this.currentQueued++;let r=this.queue.deQueue();r&&t.push(()=>this.functionExecutor(r.value,r.id))}await Promise.all(t.map(e=>e()))}else this.ee.emit("empty"),this.ee.emit("log","Nothing to do");this.ee.emit("log",`CONSTRAINED_ASYNC: Queue Size -> ${this.queue.size}`),this.ee.emit("log",`CONSTRAINED_ASYNC: CurrentQueue Size -> ${this.currentQueued}`),await this.delay()}}async functionExecutor(t,e){try{let r=await t.method()(...t.args);this.ee.emit("result",{value:r,id:e})}catch(r){this.ee.emit("log",`Error in functionExecutor: ${r.message}`),this.ee.emit("resultError",{id:e,error:r})}this.currentQueued--}stop(){this.destroy=!0,this.ee.emit("stop")}};function jl(){return"client_"+Math.random().toString(36).substring(2)+Date.now().toString(36)}function xo(t){return`surfboard_monotonic_${t}`}function ql(t){try{let e=localStorage.getItem(xo(t));return e?JSON.parse(e):null}catch(e){return console.error("Error reading monotonic data from localStorage:",e),null}}function zl(t,e){try{localStorage.setItem(xo(t),JSON.stringify(e))}catch(r){console.error("Error saving monotonic data to localStorage:",r)}}function Io(t){let e=ql(t);if(e)g.MONOTONIC_START_TIME=e.startTime,g.MONOTONIC_CLIENT_ID=e.clientId;else{let r={startTime:Date.now(),clientId:jl()};zl(t,r),g.MONOTONIC_START_TIME=r.startTime,g.MONOTONIC_CLIENT_ID=r.clientId}}function Bn(){return Date.now()-g.MONOTONIC_START_TIME}function Hn(){return g.MONOTONIC_CLIENT_ID}var $r=ht(Da());function vo(t,e,r){return Se({headers:{"X-Payment-ID":e,"x-terminal-Id":r},type:"A",routeUrl:"applepayv"},{u:t})}function No(t,e,r){return Se({headers:{"X-Payment-ID":e,"x-terminal-Id":r},type:"A",routeUrl:"applepayp"},t)}function Co(t,e,r){return Se({headers:{"X-Payment-ID":t,"x-terminal-Id":e},type:"A",routeUrl:"transaction"},r)}function Po(t,e,r){return Se({headers:{"X-Payment-ID":t,"x-terminal-Id":e},type:"A",routeUrl:"event"},r)}function wo(t,e){return Se({headers:{"x-terminal-Id":t},type:"A",routeUrl:"echo"},e)}function Ro(t,e,r){return Se({headers:{"X-Payment-ID":e,"x-terminal-Id":r},type:"A",routeUrl:"googlepayp"},t)}function Lo(t,e){let r={headers:{"X-Order-ID":g.ORDER_ID,"X-Terminal-Id":g.TERMINAL_ID},type:"K",routeUrl:"key-exchange"},n={type:t};return n[`${t.toLowerCase()}Key`]=e,Se(r,n)}var ie={kR:Lo,aR:Co,iR:Do,sR:ko,oR:Mo,cR:Ko,eR:Po,aV:vo,aP:No,pO:Uo,gP:Ro,eC:wo,cP:Fo};var bt=class{static client=$r.Client.cryptomancer(!0)};async function Wl(t,e,r){let n=!0,i=1;for(;n&&i<r;){i++;try{await Bo(t),m({type:"SECURE_CHANNEL_INITIALISATION_SUCCESS",data:{orderId:e}});return}catch(s){m({type:"SECURE_CHANNEL_INITIALIZATION_FAILED",data:{orderId:e,attempt:i+1,maxRetries:r,error:s.message}})}}m({type:"MAX_TRIED_TO_SECURE_CHANNEL_INITIALIZATION_REACHED",data:{orderId:e,attempt:i+1,maxRetries:r}}),await Bo(t)}async function Bo(t){jr(),bt.client.setRsaPublicKey(t);let e=await bt.client.getIdentityPublicKey(),n=(await(await ie.kR("IDENTITY",e)).data()).data.identityKey;await bt.client.setPeerIdentityKey(n);let i=await bt.client.getHandshakePublicKey(),p=(await(await ie.kR("HANDSHAKE",i)).data()).data.handshakeKey;await bt.client.setPeerHandshakePublicKey(p)}async function Er(t,e,r){await Wl(t,e,r)}function jr(){bt.client=$r.Client.cryptomancer(!0)}function Ho(t){return bt.client.encrypt(t)}function Yo(t){return bt.client.decrypt(t)}function Vo(t){return $r.Client.AES.encrypt(t,g.NONCE)}function Go(t){return $r.Client.AES.decrypt(t,g.NONCE)}function Se(t,e){return new Promise(async function(r,n){let i=t.headers||{},s=Jl(t),p=`${s.requestUrl}${t.routeUrl?`/${t.routeUrl}`:""}`,h={"Content-Type":s.contentType,"X-Order-ID":g.ORDER_ID};i&&Object.keys(i).forEach(function(x){var R=i[x];typeof R=="string"&&(h[x]=R)}),t.routeHeader&&(h["x-surfboard-route-header"]=t.routeHeader);let b=await s.requestData(e);try{let x=await fetch(p,{method:"POST",headers:h,body:b,mode:"cors"}),R=await x.text();x.ok||n(new Error(`Request failed with status: ${x.status}`)),r({responseURL:x.url,status:x.status,data:()=>s.responseParser(R),getResponseHeader:function(K){return x.headers.get(K)||""},responseText:R})}catch(x){console.error(x),n(new Error(x+" for URL: "+p))}})}function Jl(t){let e={A:{contentType:"application/x-agw-data",requestData:r=>Ho(JSON.stringify(r)),requestUrl:g.AGW_URL,responseParser:async r=>{try{let n=await Yo(r);if(n.outOfOrder)throw new Error("Message Decryption failed");return JSON.parse(n.clearText)}catch{throw new Error("API Server Response error")}}},G:{contentType:"application/json",requestData:r=>JSON.stringify(r),requestUrl:g.API_URL,responseParser:async r=>JSON.parse(r)},K:{contentType:"application/json",requestData:r=>JSON.stringify(r),requestUrl:g.AGW_URL,responseParser:async r=>JSON.parse(r)},C:{contentType:"application/json",requestData:r=>JSON.stringify(r),requestUrl:g.CAMOUFLAGE_URL,responseParser:async r=>JSON.parse(r)}};if(!Object.keys(e).includes(t.type))throw new Error("Invalid Request Type");return e[t.type]}async function F(t,e=!1){let r=await Ne.getStringValue(t);return g.ERROR_CALLBACK(t,r),m({type:"ERROR_OCCURRED",data:{code:t,message:r}}),{code:t,message:r}}var br={PI:new Map,GATEWAY:new Map},$o=120*1e3,jo=3;async function Tr(t,e){let r=Date.now(),n=br[e].get(t);n?br[e].set(t,{timestamp:r,retryCount:n.retryCount+1}):br[e].set(t,{timestamp:r,retryCount:1})}async function qo(t,e){return Zl(e),t.filter(r=>!Wo(r,e))}async function zo(t,e){return Wo(t,e)}function Wo(t,e){let r=br[e].get(t);if(!r)return!1;let i=Date.now()-r.timestamp;return r.retryCount>=jo?!0:!(i>$o)}function Zl(t){let e=Date.now();br[t].forEach((r,n)=>{e-r.timestamp>$o&&r.retryCount<jo&&br[t].delete(n)})}async function Qt(t,e){let r={"Content-Type":"application/json","x-surfboard-nonce":g.NONCE},n=performance.now(),i="",s=g.PI_URLS,p=await qo(s,"PI"),h=[];for(let R of p)try{let K=`${R}/${t.routeUrl}`,V={method:t.method,headers:{...r,...t.headers}};t.method!=="GET"&&t.method!=="HEAD"&&(V.body=JSON.stringify(e));let H=await fetch(K,V);if(![200,201].includes(H.status)||!H.ok){h.push({url:R,active:!1,error:`HTTP Error: ${H.status} ${H.statusText}`}),await Tr(R,"PI"),i=`HTTP Error: ${H.status} ${H.statusText}`;continue}h.push({url:R,active:!0});let le=performance.now(),me=Math.round(le-n);return{status:"SUCCESS",data:await H.json(),message:"Request successful",performance:{latency:me},serviceStatus:h}}catch(K){h.push({url:R,active:!1,error:K instanceof Error?K.message:"Unknown error"}),await Tr(R,"PI"),i=K instanceof Error?K.message:"Unknown error";continue}let b=performance.now();return{status:"ERROR",message:"All request attempts failed",performance:{latency:Math.round(b-n),error:i},serviceStatus:h}}function Ze(t){return Array.isArray(t)?t.map(Ze).filter(Boolean):typeof t=="object"&&t!==null&&t!==void 0?Object.entries(t).reduce((e,[r,n])=>{let i=Ze(n);return i!=null&&(e[r]=i),e},{}):t}var Ql=1e3,qr={};function Xl(){let t=Object.entries(qr);if(t.length<=Ql)return;t.sort((r,n)=>r[1].timestamp-n[1].timestamp);let e=Math.ceil(t.length*.2);for(let r=0;r<e;r++)delete qr[t[r][0]]}function Xt(t,e,r=100){return async()=>{let n=g.ORDER_ID,i=g.AGW_URL;if(await zo(i,"GATEWAY"))try{return await e()}catch{return await t()}let p;if(n){if(!qr[n]){let h=Math.random()*100<r;qr[n]={useGateway:h,timestamp:Date.now()},Xl()}p=r===100?!0:qr[n].useGateway}else p=Math.random()*100<r;try{return await(p?t():e())}catch(h){p&&await Tr(i,"GATEWAY");try{return await(p?e():t())}catch{throw p||await Tr(i,"GATEWAY"),h}}}}function ut(t){return typeof t!="string"?t:t.trim().replace(/[<>]/g,"").replace(/[\\"']/g,"\\$&")}function Yn(t){if(!t||typeof t!="object")return t;let e={};return Object.entries(t).forEach(([r,n])=>{typeof n=="string"?e[r]=ut(n):Array.isArray(n)?e[r]=n.map(i=>typeof i=="string"?ut(i):i!==null&&typeof i=="object"?Yn(i):i):n!==null&&typeof n=="object"?e[r]=Yn(n):n!=null&&(e[r]=n)}),e}function Jo(t){if(!t||typeof t!="object")throw new Error("Payment data must be an object");if(!t.paymentMethod)throw new Error("Payment method is required");return{orderId:g.ORDER_ID,nonce:g.NONCE,paymentMethod:ut(t.paymentMethod),bic:t.bic}}function Zo(t){if(!t||typeof t!="object")throw new Error("Payment status data must be an object");if(!t.paymentId)throw new Error("Payment ID is required");if(typeof t.paymentId!="string")throw new Error("Payment ID must be a string");return{orderId:g.ORDER_ID,nonce:g.NONCE,paymentId:ut(t.paymentId)}}function Qo(t){if(!t||typeof t!="object")throw new Error("Order details data must be an object");if(!t.orderId)throw new Error("Order ID is required");return{orderId:g.ORDER_ID,currentUrl:ut(t.currentUrl||""),topUrl:ut(t.topUrl||""),nonce:g.NONCE,checkParam:ut(t.checkParam||"")}}function Xo(t){if(!t||typeof t!="object")throw new Error("Customer details must be an object");return Yn(t)}function es(t){if(!t||typeof t!="object")throw new Error("Klarna order data must be an object");if(!t.authorizationToken)throw new Error("Authorization token is required");if(!t.paymentId)throw new Error("Payment ID is required");return{orderId:g.ORDER_ID,paymentId:ut(t.paymentId),authorizationToken:ut(t.authorizationToken)}}function ts(t){if(!t||typeof t!="object")throw new Error("Event data must be an object");if(!t.eventType)throw new Error("Event type is required");if(!t.inputData||typeof t.inputData!="object")throw new Error("Input data must be a valid object");let e=Yn(t.inputData),r={orderId:t.orderId||g.ORDER_ID,terminalId:t.terminalId||g.TERMINAL_ID,event:{type:ut(t.eventType),data:{...e,orderId:g.ORDER_ID},timestamp:new Date().toISOString()}};return t.paymentId&&(r.paymentId=ut(t.paymentId)),r}var Vn=[],er=()=>({headers:{"x-surfboard-nonce":g.NONCE},type:"G"}),ka=t=>({data:()=>Promise.resolve(t)});function Sr(t,e,r,n,i){setTimeout(()=>{try{let s=t.includes("orders/online/")&&!t.includes("customer"),p=!!g.TERMINAL_ID;if(s&&!p){Vn.push({eventType:"MULTICLOUD_SERVICE_INACTIVE",inputData:{latency:r.latency.toString(),error:r.error||"",endpoint:t,method:e,status:r.error?"ERROR":"SUCCESS"},paymentId:i,serviceStatus:n});return}if(wt({eventType:"MULTICLOUD_PERFORMANCE",inputData:{latency:r.latency.toString(),error:r.error||"",endpoint:t,method:e,status:r.error?"ERROR":"SUCCESS"},paymentId:i}).catch(h=>{}),n&&n.length>0){let h=r.error||"";n.forEach(b=>{if(!b.active){let x=b.error||"Unknown error";if(h&&x===h)return;wt({eventType:"MULTICLOUD_SERVICE_INACTIVE",inputData:{serviceUrl:b.url,error:x,endpoint:t,method:e,timestamp:new Date().toISOString()},paymentId:i}).catch(R=>{})}})}}catch{}},0)}function rs(){Vn.length>0&&(Vn.forEach(t=>{wt({eventType:t.eventType,inputData:t.inputData,paymentId:t.paymentId}).catch(e=>{})}),Vn.length=0)}async function Do(t,e={}){try{let r=Jo({paymentMethod:t,...e});return await Xt(()=>Se({...er(),routeHeader:"SB_ONLINE_INITIATE_PAYMENTS"},r),async()=>{let i=await Qt({method:"POST",headers:{"x-surfboard-nonce":g.NONCE},routeUrl:"payments"},r);if(i.performance&&Sr("payments","POST",i.performance,i.serviceStatus),i.status==="SUCCESS")return ka(i.data);throw new Error("Multicloud request failed")})()}catch{return F("ONL_0037",!1)}}async function ko(t){try{let e=Zo({paymentId:t});return await Xt(()=>Se({...er(),routeHeader:"SB_ONLINE_CHECK_PAYMENT_STATUS"},e),async()=>{let n=await Qt({method:"GET",headers:{"x-surfboard-nonce":g.NONCE},routeUrl:`payments/${t}/status`},e);if(n.performance&&Sr(`payments/${t}/status`,"GET",n.performance,n.serviceStatus,t),n.status==="SUCCESS")return ka(n.data);throw new Error("Multicloud request failed")})()}catch{return null}}async function wt({eventType:t,inputData:e,paymentId:r}){let n={...er(),routeHeader:"SB_SAVE_EVENTS"},i=g.TERMINAL_ID,s=g.ORDER_ID,p=ts({eventType:t,inputData:e,paymentId:r,orderId:s,terminalId:i});try{return{success:!0,data:await Se(n,p),eventType:t,inputData:e,paymentId:r}}catch(h){return console.error("[SaveEvents] Failed to save event:",{error:h,eventType:t,orderId:s,terminalId:i,paymentId:r,timestamp:new Date().toISOString()}),{success:!1,error:"Failed to save event",eventType:t,inputData:e,paymentId:r}}}async function Mo(){try{let t=Qo({orderId:g.ORDER_ID,currentUrl:g.CURRENT_DOMAIN,topUrl:g.TOP_DOMAIN,nonce:g.NONCE,checkParam:await g.CHECK_PARAM});return await Xt(()=>Se({...er(),routeHeader:"SB_GET_ONLINE_ORDER_BY_ID"},t),async()=>{let r=await Qt({method:"POST",headers:{"x-surfboard-nonce":g.NONCE},routeUrl:`orders/online/${t.orderId}`},t);if(r.performance&&Sr(`orders/online/${t.orderId}`,"POST",r.performance,r.serviceStatus),r.status==="SUCCESS")return{data:()=>Promise.resolve({status:"SUCCESS",data:{order:r.data}})};throw new Error("Multicloud request failed")})()}catch{return F("ONL_0037",!1)}}async function Ko(t){try{let e=Xo(t),r=g.ORDER_ID;return await Xt(()=>Se({...er(),routeHeader:"SB_UPDATE_ONLINE_ORDER_CUSTOMER_DETAILS"},{...e,orderId:r}),async()=>{let i=ec(e),s=await Qt({method:"PUT",headers:{"x-surfboard-nonce":g.NONCE},routeUrl:`orders/${r}/customer`},{orderId:r,...i});if(s.performance&&Sr(`orders/${r}/customer`,"PUT",s.performance,s.serviceStatus),s.status==="SUCCESS")return{data:()=>Promise.resolve({status:"SUCCESS",data:{customer_details:s.data}})};throw new Error("Multicloud request failed")})()}catch{return F("ONL_0037",!1)}}function ec(t){return Ze({person:{name:{firstName:t.name},email:t.email,phone:{code:t.phone.countryCode,number:t.phone.number}},billing:t.billingAddress&&{city:t.billingAddress?.city,postalCode:t.billingAddress?.postalCode,countryCode:t.billingAddress?.countryCode,addressLine1:t.billingAddress?.addressLine1,addressLine2:t.billingAddress?.addressLine2,addressLine3:t.billingAddress?.addressLine3},shipping:t.shippingAddress&&{city:t.shippingAddress?.city,postalCode:t.shippingAddress?.postalCode,countryCode:t.shippingAddress?.countryCode,addressLine1:t.shippingAddress?.addressLine1,addressLine2:t.shippingAddress?.addressLine2,addressLine3:t.shippingAddress?.addressLine3}})}async function Uo(t,e){try{let r=es({authorizationToken:t,paymentId:e});return await Xt(()=>Se({...er(),routeHeader:"PAYMENT_SERVICE_PLACE_KLARNA_ORDER"},r),async()=>{let i=await Qt({method:"POST",headers:{"x-surfboard-nonce":g.NONCE},routeUrl:`payments/${e}/klarna/place-order`},{authorizationToken:t});if(i.performance&&Sr(`payments/${e}/klarna/place-order`,"POST",i.performance,i.serviceStatus,e),i.status==="SUCCESS")return ka(i.data);throw new Error("Multicloud request failed")})()}catch{return F("ONL_0037",!1)}}async function Fo(t){try{let e=g.ORDER_ID;return await Xt(()=>Se({...er(),routeHeader:"SB_ONLINE_CANCEL_PAYMENT"},{orderId:e,paymentId:t}),async()=>{let n=await Qt({method:"DELETE",headers:{"x-surfboard-nonce":g.NONCE},routeUrl:`payments/${t}`},{orderId:e,paymentId:t});if(n.performance&&Sr(`payments/${t}`,"DELETE",n.performance,n.serviceStatus),n.status==="SUCCESS")return{data:()=>Promise.resolve({status:"SUCCESS",data:{paymentStatus:n.data.paymentStatus}})};throw new Error("Multicloud request failed")})()}catch{return F("ONL_0037",!1)}}function m({type:t,data:e,paymentId:r}){e||(e={}),e.monotonic=Bn(),e.monotonicClientId=Hn(),e.localTime=new Date().toString(),e.orderId=g.ORDER_ID,e.terminalId=g.TERMINAL_ID,g.throttle.addToQueue({args:[t,e,r],function:(n,i,s)=>wt({eventType:n,inputData:i,paymentId:s})})}function fe(t,e){m({type:t,data:{orderId:g.ORDER_ID,...e||{}}})}function Ye(){let t=window.navigator.userAgent;if(!t)throw new Zt("Invalid runtime");let e={isEdgeHTMLBrowser:function(n){return/Edge\//i.test(n)},isEdgeChromiumBrowser:function(n){return/Edg\//i.test(n)},isInternetExplorer:function(n){return/(MSIE ([0-9]{1,}[.0-9]{0,})|Trident\/)/i.test(n)},isSamsungBrowser:function(n){return/SamsungBrowser/.test(n)},isIPhone:function(n,i){return(/iPhone/i.test(n)||e.isIPad(n,i))&&!e.isInternetExplorer(n)},isIPad:function(n,i){return(/iPad/i.test(n)||/Macintosh/i.test(n)&&(i>0||"ontouchstart"in window))&&!e.isInternetExplorer(n)},isOperaMini:function(n){return/Opera Mini/i.test(n)},isSafari:function(n){return/^((?!chrome|android).)*safari/i.test(n)&&!e.isSamsungBrowser(n)},isAndroid:function(n){return/Android/i.test(n)&&!e.isInternetExplorer(n)}},r=window.navigator.maxTouchPoints;return{isEdgeHTML:e.isEdgeHTMLBrowser(t),isEdgeChromium:e.isEdgeChromiumBrowser(t),isIE:e.isInternetExplorer(t),isIPhoneDevice:e.isIPhone(t,r),isIPadDevice:e.isIPad(t,r),isAndroidDevice:e.isAndroid(t),isSafariBrowser:e.isSafari(t),isFirefox:/Firefox\//i.test(t),isSamsung:e.isSamsungBrowser(t),isChrome:/Chrome\//i.test(t),isChromeNotEdge:/Chrome/i.test(t),isEdgeIOS:/EdgiOS/i.test(t),isElectron:/\belectron\b/i.test(t),isOperaMiniBrowser:e.isOperaMini(t),isMacWebKitNotSafari:/Macintosh.*AppleWebKit(?!.*Safari)/i.test(t),isSafariLine:/Safari Line/i.test(t),isBrave:!!window.navigator.brave&&typeof window.navigator.brave.isBrave=="function",isStandaloneModeIOS:window.navigator&&"standalone"in window.navigator&&window.navigator.standalone,userAgent:t,isJavaEnabled:navigator.javaEnabled(),browserTZ:new Date().getTimezoneOffset().toString(),colorDepth:screen.colorDepth,jsEnabled:!0,language:navigator.language,screenHeight:screen.height.toString(),screenWidth:screen.height.toString()}}var Ma=class{registry=new Map;registerField(e){this.registry.set(e,{touched:!1,valid:!1})}addError(e,r,n){let i=this.registry.get(e)??{valid:!1,touched:!0};i.valid=!1,i.touched=!0,i.errorMessages={code:r,message:n},this.registry.set(e,i)}cleanErrors(e){let r={valid:!0,touched:!0};this.registry.set(e,r)}getValidity(){return!Array.from(this.registry.values()).map(e=>e.valid).includes(!1)}frameExternalObject(){return Object.fromEntries(this.registry)}getErrorForField(e){return this.registry.get(e)}},Ce=new Ma;var tc=["name","card","expiryDate","cvc","storeInformation"],ns=[...tc];var Qe={invalidPan:"ONL_0001",decryptionFailed:"ONL_0002",invalidIp:"ONL_0003",unknownPayment:"ONL_0004",threeDsPreAuthFailed:"ONL_0005",threeDsAuthRequestFailed:"ONL_0006",threeDsPostAuthRequestFailed:"ONL_0007",threeDsChallengeFailed:"ONL_0008",paymentNotFound:"ONL_0009",merchantNotFound:"ONL_0010",paymentReferencesNotAvailable:"ONL_0011",invalidStepEvent:"ONL_0012",stepSelectionError:"ONL_0013",invalidOnlineParams:"ONL_0014",tokenizationFailed:"ONL_0015",cvvVerificationFailed:"ONL_0016",citInitiationFailed:"ONL_0017",noCardFoundWithTheGivenId:"ONL_0018",tokenizedCardIsNotActive:"ONL_0019",tokenCryptogramRetrievalFailed:"ONL_0020",tokenBlobCorrupted:"ONL_0021",applePayInvalidUrl:"ONL_0022",applePayCreateSessionError:"ONL_0023",applePayPaymentDecryptionFailed:"ONL_0024",applePayProcessingFailed:"ONL_0025",sbPaymentInitFailed:"ONL_0026",klarnaPaymentInitFailed:"ONL_0027",klarnaPaymentWidgetLoadFailed:"ONL_0028",klarnaPaymentAuthFailedWithFixableErrors:"ONL_0029",klarnaPaymentAuthFailed:"ONL_0030",klarnaPlaceOrderFailed:"ONL_0031",klarnaSDKLoadFailed:"ONL_0032",klarnaUnexpectedErrorOccured:"ONL_0033",googlePayFailed:"ONL_0038",googlePayMountFailed:"ONL_0039",applePayMountFailed:"ONL_0040"};function Gn(t){let e=t.replace(/\D/g,"");if(!e)return"card.required";if(e.length<13)return"card.short";if(e.length>19)return"card.long";if(!rc(e))return"card.number.general";let r=Ka(e);return r?["VISA","MASTERCARD","DISCOVER","DINERS","AMEX"].includes(r)?null:"card.brand.notsupported":"card.number.general"}var rc=t=>{let e=0,r=parseInt(t.slice(-1)),n=t.length%2;for(let i=t.length-2;i>=0;i--){let s=parseInt(t.charAt(i));i%2===n&&(s*=2,s>9&&(s-=9)),e+=s}return(10-e%10)%10===r};function Ka(t){let e=/^4[0-9]{12}(?:[0-9]{3,6})?$/,r=/^(5[1-5][0-9]{14}|2[2-7][0-9]{14,16})$/,n=/^3[47][0-9]{13}$/,i=/^3(?:0[0-5]|[68][0-9])[0-9]{11}$/,s=/^6(?:011|5[0-9]{2})[0-9]{12,15}$/,p=/^(?:2131|1800|35\d{3})\d{11,14}$/;if(e.test(t))return"VISA";if(r.test(t))return"MASTERCARD";if(n.test(t))return"AMEX";if(i.test(t))return"DINERS";if(s.test(t))return"DISCOVER";if(p.test(t))return"JCB"}var nc=new Set;function $n(t){return nc.has(t.replace(/\s/g,"").slice(0,6))}function jn(t,e){return t?/^\d+$/.test(t)?null:"cvv.numeric":"cvv.required"}function qn(t){if(!t)return"expiry.required";if(!/^\d{2}\/\d{2}$/.test(t))return"expiry.invalid";let[e,r]=t.split("/").map(n=>parseInt(n,10));return e<1||e>12||r<0||r>99?"expiry.invalid":ac(e,r)?"expiry.expired":null}function ac(t,e){let r=new Date,n=r.getFullYear()%100,i=r.getMonth()+1;return e<n?!0:e>n?!1:t<i}function zn(t){return!t||t.length<2?"name.required":t.length>50?"name.long":null}var xs=ht(Xn());function Is(t){if(!(0,xs.validateId)(t,"HEX","0B"))throw new Bt("Invalid Order ID")}var Va={752:1e3,978:100,208:1e3};function vs(t){if(!t||t.trim().length<128)throw new Bt("Invalid NONCE")}var Ns={card:Gn,expiryDate:qn,cvc:jn,name:zn,storeInformation:()=>null};function he(){return{ge:e=>document.getElementById(e),ce:e=>document.createElement(e),de:document.documentElement,ahc:e=>document.head.appendChild(e)}}function Cs(){let t=he();t.ge(`sb-card-details-form-${g.FIELD_NONCE}`)?.remove();let e=document.createElement(we.d);e.id=`sb-card-details-loading-${g.FIELD_NONCE}`,e.className="sb-w-full sb-flex sb-justify-center sb-items-center sb-h-full";let r=t.ce("span");r.classList.add("sb-loader"),e.appendChild(r),t.ge("sb-section--wrapper-card-details")?.appendChild(e)}function Or(){he().ge(`sb-card-details-loading-${g.FIELD_NONCE}`)?.remove()}var we={d:"div",f:"form",i:"input",p:"p"};function Ps(){let t={};for(let e of ns){let r=$c(e),n=Ns[e](r);n?(Ce.addError(e,"ERR",n),jc(e,n).then()):(Ce.cleanErrors(e),t[e]=r)}return t}function $c(t){return he().ge(`sb-${t}_${g.FIELD_NONCE}`)?.value}async function jc(t,e){let n=he().ge(`sb-error-${t}`);n&&(n.innerText=await Ne.getStringValue(e))}var Ks=ht(Xn());async function ea(t,e){try{e&&await Ga();let r=`Attempting to echo with order ${t.order.orderId}`,i=await(await ie.eC(t.order.terminalId,{type:"ECHO",data:r})).data();(i.status!=="SUCCESS"||r!==i.data?.data)&&await Ga()}catch{await Ga()}}async function Ga(){jr(),await Er(g.PUBLIC_KEY,g.ORDER_ID,3)}async function Lt(t,e){try{let r=await e();return r.status=="ERROR"||r.status==500?(await ea(t,!0),await e()):r}catch{return await ea(t,!0),await e()}}async function ws(t,e,r){return await(await Lt(t,()=>ie.aV(e,r.p,r.t))).data()}async function Rs(t,e,r){return m({type:"APPLE_PAY_PROCESS_PAYMENT",data:{},paymentId:r.p}),await(await Lt(t,()=>ie.aP(e,r.p,r.t))).data()}var qc={da:"da-DK",en:"en-GB",fi:"fi-FI",sv:"sv-SE",no:"nb-NO"};function Ls(){return qc[g.SDK_LANGUAGE]??"en-GB"}var en={AD:"376",AE:"971",AF:"93",AG:"1",AI:"1",AL:"355",AM:"374",AO:"244",AR:"54",AS:"1",AT:"43",AU:"61",AW:"297",AX:"358",AZ:"994",BA:"387",BB:"1",BD:"880",BE:"32",BF:"226",BG:"359",BH:"973",BI:"257",BJ:"229",BL:"590",BM:"1",BN:"673",BO:"591",BQ:"599",BR:"55",BS:"1",BT:"975",BW:"267",BY:"375",BZ:"501",CA:"1",CC:"61",CD:"243",CF:"236",CG:"242",CH:"41",CI:"225",CK:"682",CL:"56",CM:"237",CN:"86",CO:"57",CR:"506",CU:"53",CV:"238",CW:"599",CX:"61",CY:"357",CZ:"420",DE:"49",DJ:"253",DK:"45",DM:"1",DO:"1",DZ:"213",EC:"593",EE:"372",EG:"20",EH:"212",ER:"291",ES:"34",ET:"251",FI:"358",FJ:"679",FK:"500",FM:"691",FO:"298",FR:"33",GA:"241",GB:"44",GD:"1",GE:"995",GF:"594",GG:"44",GH:"233",GI:"350",GL:"299",GM:"220",GN:"224",GP:"590",GQ:"240",GR:"30",GT:"502",GU:"1",GW:"245",GY:"592",HK:"852",HN:"504",HR:"385",HT:"509",HU:"36",ID:"62",IE:"353",IL:"972",IM:"44",IN:"91",IO:"246",IQ:"964",IR:"98",IS:"354",IT:"39",JE:"44",JM:"1",JO:"962",JP:"81",KE:"254",KG:"996",KH:"855",KI:"686",KM:"269",KN:"1",KP:"850",KR:"82",KW:"965",KY:"1",KZ:"7",LA:"856",LB:"961",LC:"1",LI:"423",LK:"94",LR:"231",LS:"266",LT:"370",LU:"352",LV:"371",LY:"218",MA:"212",MC:"377",MD:"373",ME:"382",MF:"590",MG:"261",MH:"692",MK:"389",ML:"223",MM:"95",MN:"976",MO:"853",MP:"1",MQ:"596",MR:"222",MS:"1",MT:"356",MU:"230",MV:"960",MW:"265",MX:"52",MY:"60",MZ:"258",NA:"264",NC:"687",NE:"227",NF:"672",NG:"234",NI:"505",NL:"31",NO:"47",NP:"977",NR:"674",NU:"683",NZ:"64",OM:"968",PA:"507",PE:"51",PF:"689",PG:"675",PH:"63",PK:"92",PL:"48",PM:"508",PR:"1",PS:"970",PT:"351",PW:"680",PY:"595",QA:"974",RE:"262",RO:"40",RS:"381",RU:"7",RW:"250",SA:"966",SB:"677",SC:"248",SD:"249",SE:"46",SG:"65",SH:"290",SI:"386",SJ:"47",SK:"421",SL:"232",SM:"378",SN:"221",SO:"252",SR:"597",SS:"211",ST:"239",SV:"503",SX:"1",SY:"963",SZ:"268",TC:"1",TD:"235",TG:"228",TH:"66",TJ:"992",TK:"690",TL:"670",TM:"993",TN:"216",TO:"676",TR:"90",TT:"1",TV:"688",TW:"886",TZ:"255",UA:"380",UG:"256",US:"1",UY:"598",UZ:"998",VA:"39",VC:"1",VE:"58",VG:"1",VI:"1",VN:"84",VU:"678",WF:"681",WS:"685",XK:"383",YE:"967",YT:"262",ZA:"27",ZM:"260",ZW:"263"},zc={752:"SEK",978:"EUR",840:"USD",826:"GBP",578:"NOK",208:"DKK"};function ta(t){return zc[t]}var Ds=Object.values(en).sort((t,e)=>e.length-t.length);function Ms(){try{let e=navigator.language.split("-")[1];return e&&en[e]?e:"SE"}catch{return"SE"}}function ks(t){let e=t.replace(/\D/g,"");return/^\d+$/.test(e)&&e.length>=5&&e.length<=15}function xr(t,e){let r=t.replace(/[^\d+]/g,"");if(r.startsWith("00")){let s=r.substring(2);return xr(`+${s}`,e)}let n=r,i=null;if(e&&en[e]){if(i=en[e],r.startsWith("0"))n=r.substring(1);else if(r.startsWith("+")){n=r.substring(1);for(let s of Ds)if(n.startsWith(s)){n=n.substring(s.length);break}}return ks(n)?{countryCode:`+${i}`,number:n}:null}r.startsWith("+")&&(n=r.substring(1));for(let s of Ds)if(n.startsWith(s)){i=s,n=n.substring(s.length);break}if(!i&&n.length>0){let s=n.charAt(0);Object.entries(en).find(([h,b])=>b===s)&&(i=s,n=n.substring(1))}return i&&ks(n)?{countryCode:`+${i}`,number:n}:null}var Oe=class t{static attempt;static paymentAttemptId;static onSuccess=async function(){};static onFailure=async function(e){let r=e?.data?.errorCodes?.[0]??"ONL_0025";m({type:"APPLE_PAY_ERROR",data:{error:r}}),F(r)};static onCancel=async function(){t.attempt?.cancelPayment()}};var $a=class t{static instance;tasks=new Map;asyncThrottle;constructor(){this.asyncThrottle=new Fn({maxThreshold:5,delayExecutions:1e3}),this.startTaskExecution()}static getInstance(){return t.instance||(t.instance=new t),t.instance}startTaskExecution(){let e=r=>{let n=this.tasks.get(r);n&&(n.attempts++,n.lastAttempt=Date.now(),n.options.maxRetries&&n.attempts>=n.options.maxRetries&&this.tasks.delete(r))};this.asyncThrottle.on("result",({value:r,id:n})=>e(n)),this.asyncThrottle.on("resultError",({id:r,error:n})=>e(r))}registerTask(e,r,n={},...i){let s={id:e,function:r,args:i,options:{maxRetries:3,retryDelay:1e3,timeout:3e4,...n},createdAt:Date.now(),attempts:0};this.tasks.set(e,s),this.asyncThrottle.addToQueue({function:()=>this.executeTask(s),args:[]},e)}async executeTask(e){if(e.options.executeUntil&&!(typeof e.options.executeUntil=="function"?e.options.executeUntil():new Date<=e.options.executeUntil)){this.tasks.delete(e.id);return}if(e.attempts>e.options.maxRetries)return;let r=e.function;try{return await Promise.race([r(...e.args),new Promise((i,s)=>setTimeout(()=>s(new Error("Task timeout")),e.options.timeout))])}catch(n){throw console.error(`Task ${e.id} failed:`,n),n}finally{if(e.attempts>e.options.maxRetries)return;setTimeout(()=>this.asyncThrottle.addToQueue({function:()=>this.executeTask(e),args:[]},e.id),e.options.retryDelay)}}cancelTask(e){this.tasks.delete(e)}getAllTasks(){return Array.from(this.tasks.values())}},pt=$a.getInstance();var xe=class{constructor(e,r){this._z=e;if(g.IS_INITIALISED!=="TRUE")throw new _r("Surfboard SDK is not initialised");r?.paymentMethod&&(this.paymentMethod=r?.paymentMethod),this.setSwishVariables(r);let n=0;this.paymentCheckTaskId=`payment-status-checks_${Date.now()}`,pt.registerTask(this.paymentCheckTaskId,async()=>{let i=await ie.sR(this.paymentId);if(i.code){m({type:"CHECK_PAYMENT_STATUS_ERRORED",data:{data:JSON.stringify(i.message)},paymentId:this.paymentId}),n++,n>10&&(F(i.code),pt.cancelTask(this.paymentCheckTaskId));return}let s=await i.data();if(!s||s.status==="ERROR"){m({type:"CHECK_PAYMENT_STATUS_ERRORED",data:{data:JSON.stringify(s)},paymentId:this.paymentId}),n++,n>10&&(F("ON_015"),pt.cancelTask(this.paymentCheckTaskId));return}m({type:"CHECK_PAYMENT_STATUS_RESPONSE",data:{status:s.data.paymentStatus,failureReason:s.data.failureReason},paymentId:this.paymentId}),n=0,this.paymentStatus!==s.data.paymentStatus&&(this.paymentStatus=s.data.paymentStatus,g.PAYMENT_STATUS_CALLBACK({paymentStatus:s.data.paymentStatus,failureReason:s.data.failureReason})),g.TERMINAL_PAYMENT_STATUSES.includes(this.paymentStatus)&&(g.TERMINAL_CALLBACKS.forEach(async p=>await p(this.paymentStatus)),pt.cancelTask(this.paymentCheckTaskId),fe("PAYMENT_FLOW_COMPLETED",{paymentStatus:this.paymentStatus}))},{maxRetries:g.MAXIMUM_CHECKS,retryDelay:1e3,executeUntil:()=>!["PAYMENT_CANCELLED","PAYMENT_COMPLETED","PAYMENT_FAILED"].includes(this.paymentStatus)}),g.PAYMENT_STATUS_CALLBACK({paymentStatus:this.paymentStatus})}paymentStatus="PAYMENT_INITIATED";paymentCheckTaskId;paymentMethod;nswishQRDataUrl=null;nswishPaymentToken=null;get paymentId(){return this._z}getPaymentStatus(){return{paymentStatus:this.paymentStatus}}async cancelPayment(){this.paymentStatus="PAYMENT_CANCELLED",m({type:"CANCEL_PAYMENT_REQUESTED",data:{paymentStatus:this.paymentStatus,failureReason:"User cancellation"}});let e="User Requested Cancellation";if(this.paymentMethod==="ACCTOACC"){let n=await(await ie.cP(this.paymentId)).data();n.data.paymentStatus!=="PAYMENT_CANCELLED"?this.paymentStatus=n.data.paymentStatus:pt.cancelTask(this.paymentCheckTaskId),e=""}g.PAYMENT_STATUS_CALLBACK({paymentStatus:this.paymentStatus,failureReason:e})}setSwishVariables(e){e&&(e.nswishPaymentToken&&(this.nswishPaymentToken=e.nswishPaymentToken),e.nswishQRDataUrl&&(this.nswishQRDataUrl=e.nswishQRDataUrl))}getSwishAppRedirectUrl(e){let r=`swish://paymentrequest?token=${this.nswishPaymentToken}`;return e?r+`&callbackurl=${e}`:r}get getSwishQRData(){return this.nswishQRDataUrl}};var Wc={DK:{format:"#####",example:"2100",region:"Nordic"},FI:{format:"#####",example:"00100",region:"Nordic"},IS:{format:"###",example:"101",region:"Nordic"},NO:{format:"####",example:"0010",region:"Nordic"},SE:{format:"### ##",example:"111 43",region:"Nordic"},UK:{format:"AA## #AA",example:"SW1A 1AA",region:"Western Europe"},DE:{format:"#####",example:"10115",region:"Western Europe"},FR:{format:"#####",example:"75001",region:"Western Europe"}};function ra(t){let e=`${"000000"+Math.floor(Math.random()*999999)}`.slice(-6);if(!t)return e;let r=t.toUpperCase(),n=Wc[r];return n?n.example.replace(/#/g,Jc()):(console.warn(`No zip code format found for country code: ${t}`),e)}function Jc(){return Math.floor(Math.random()*10).toString()}function na(t){return t.replace(/[^a-zA-Z0-9 ]/g,"")}var ja=he(),Ir=class t{static id="";static mountPointId="";static cdnLoaded=!1;session;static _order;static setOrderAndStore(e){t._order=e}order;store;orderHandler;getConfig(){return{currencyCode:ta(this.order.totalOrderPriceCurrency),countryCode:this.store.address.countryCode,merchantCapabilities:["supports3DS"],supportedNetworks:["masterCard","visa","discover","amex"],total:{label:this.store.name,amount:this.getAmount(),type:"final"},requiredBillingContactFields:["email","name","phone","postalAddress"],lineItems:this.order.orderLines.map(e=>({amount:this.getAmount(e.itemPrice.value),label:e.name}))}}constructor(){this.order=t._order.order,this.store=t._order.store,this.orderHandler=t._order,this.session=new ApplePaySession(t.applePayVersion,this.getConfig()),m({type:"APPLE_PAY_VERSION",data:{data:t.applePayVersion.toString()}})}static async ensureSdkAvailability(){return new Promise(e=>{if(t.cdnLoaded)return e(!0);{setTimeout(()=>{e(!1)},5e3);let r=ja.ce("script");r.src="https://applepay.cdn-apple.com/jsapi/1.latest/apple-pay-sdk.js",r.crossOrigin="anonymous",r.async=!0,r.onload=()=>{t.cdnLoaded=!0,e(!0),m({type:"APPLE_PAY_SDK_LOADED",data:{log:"Ensuring apple pay sdk availability"}})},document.head.appendChild(r)}})}static async mountApplePay(e){if(t._order&&(t._order.isTokenizedOrder||t._order.subscriptionData)===!0){m({type:"APPLE_PAY_SDK_DISABLED_TOKENISATION",data:{mountPointId:e}});return}if(!await t.ensureSdkAvailability()){m({type:"APPLE_PAY_SDK_NOT_AVAILABLE",data:{mountPointId:e}});return}if(t.mountPointId=e,!await t.isApplePayAvailable()){m({type:"APPLE_PAY_NOT_AVAILABLE",data:{mountPointId:e}});return}if(t._order.subscriptionData){m({type:"APPLE_PAY_DISABLED_FOR_SUBS",data:{mountPointId:e}});return}let n=ja.ge(e),i=ja.ce("apple-pay-button"),s=await t.getButtonStyleFromBrandConfig();if(!n||!i){m({type:"APPLE_PAY_MOUNT_FAILED",data:{log:"Apple pay mount failed, mount point or root node not found"}});return}i&&n&&(t.id=`apple-bay-btn-${(0,Ks.generateID)("HEX")}`,i.setAttribute("id",t.id),i.setAttribute("buttonstyle",s.color),i.setAttribute("locale",s.locale),i.setAttribute("type",s.type),Object.keys(s.style).forEach(p=>{i.style.setProperty(`--apple-pay-button-${p}`,s.style[p])}),i.onclick=async()=>{m({type:"APPLE_PAY_INITIATED",data:{log:"Apple pay initiated",orderId:t._order.order.orderId}}),await window.SurfboardOnlineSDK.order.initiatePayments("APPLE_PAY")},n.appendChild(i),n.classList.contains("sb-hidden")&&n.classList.remove("sb-hidden"),n.attributes.getNamedItem("hidden")&&n.attributes.removeNamedItem("hidden"),m({type:"APPLE_PAY_MOUNTED",data:{}}))}async updateBillingContactInformation(e,r){if(r){let n={};if(r.phoneNumber){m({type:"APPLE_PAY_UPDATE_BILLING_PHONE",data:{},paymentId:e});let i=xr(r.phoneNumber);i?n.phone={number:i.number,countryCode:i.countryCode}:n.phone={number:r.phoneNumber,countryCode:"+46"}}r.emailAddress&&(n.email=r.emailAddress,m({type:"APPLE_PAY_UPDATE_BILLING_EMAIL",data:{},paymentId:e})),r.givenName&&(n.name=r.givenName,m({type:"APPLE_PAY_UPDATE_BILLING_NAME",data:{},paymentId:e})),r.addressLines?.length!=0&&(n.billingAddress={addressLine1:`${r.addressLines?.[0]}`,addressLine2:r.addressLines?.[1],addressLine3:r.addressLines?.[2],careOf:r.givenName,city:`${na(`${r.locality??"no city"}`)}`,countryCode:`${r.countryCode}`,postalCode:`${r.postalCode??ra(r.countryCode)}`},m({type:"APPLE_PAY_UPDATE_BILLING_ADDRESS",data:{},paymentId:e})),await this.orderHandler.addCustomerInformation(n),m({type:"APPLE_PAY_UPDATED_BILLING_INFORMATION",data:{},paymentId:e})}}async updateShippingContactInformation(e,r){if(r){let n={};if(r.phoneNumber){let i=xr(r.phoneNumber);i?n.phone={number:i.number,countryCode:i.countryCode}:n.phone={number:r.phoneNumber,countryCode:"+46"}}r.emailAddress&&(n.email=r.emailAddress),r.givenName&&(n.name=r.givenName),r.addressLines?.length!=0&&(n.billingAddress={addressLine1:`${r.addressLines?.[0]}`,addressLine2:r.addressLines?.[1],addressLine3:r.addressLines?.[2],careOf:r.givenName,city:`${r.locality}`,countryCode:`${r.countryCode}`,postalCode:`${r.postalCode}`})}}static async getButtonStyleFromBrandConfig(){return{color:"black",locale:Ls(),type:"pay",style:{height:"30px",padding:"10px 0px","border-radius":"5px",width:"100%","box-sizing":"0px"}}}static async isApplePayAvailable(){return window.ApplePaySDK&&t.checkApplePayAvailability()}static checkApplePayAvailability(){return window.ApplePaySession?ApplePaySession.canMakePayments():!1}canPayWithActiveCards(){return ApplePaySession?.canMakePaymentsWithActiveCard("")}getAmount(e=this.order.totalOrderPriceValue){return`${parseFloat(e)/100}`}static applePayVersion=6;async initialize(e){await this.addApplePayEventListeners(e),this.session.begin();let r=Ye();!r.isSafariBrowser&&!r.isSafariLine&&m({data:{orderId:this.order.orderId},type:"APPLE_PAY_QR_DISPLAYED"})}async initiatePayment(e){let r=await(await ie.iR("CARD")).data();if(r.status==="ERROR"||r.data.status==="ERROR")throw F("ON_012"),new Error("ApplePay Initiation Error");let n=r.data.paymentId,i=new xe(n);return e(i),m({type:"APPLE_PAY_INITIATED",data:{},paymentId:n}),m({type:"DATA_COLLECTOR_AFTER_APPLE_PAY_INITIATION",data:{orderId:this.order.orderId,...Ye()},paymentId:n}),Oe.attempt=i,Oe.paymentAttemptId=n,{applePayAttempt:i,paymentId:n}}addApplePayEventListeners(e){this.session.onvalidatemerchant=async r=>{try{m({type:"APPLE_PAY_QR_SCANNED",data:{log:"Apple pay validation started after QR scanning",orderId:t._order.order.orderId}});let{paymentId:n}=await this.initiatePayment(e),i=await ws(t._order,r.validationURL,{p:n,t:this.order.terminalId});i.step==="ERROR"?(this.session.abort(),Oe.onFailure(i),m({type:"APPLE_PAY_MERCHANT_VALIDATION_FAILED",data:{log:"Merchant validation failed",code:"ONL_0017",data:JSON.stringify(i.data)},paymentId:n})):i.step==="APPLE_PAY_SESSION"?(this.session.completeMerchantValidation(i.data.session),m({type:"APPLE_PAY_SESSION_COMPLETED",data:{},paymentId:n})):(this.session.abort(),Oe.onFailure({step:"ERROR",data:{message:"Unhandled state",errorCodes:["ONL_0017"]}}),m({type:"APPLE_PAY_UNHANDLED_STATE",data:{log:"Unhandled state",code:"ONL_0017"},paymentId:n}))}catch(n){m({type:"APPLE_PAY_UNHANDLED_ERROR",data:{log:"Unhandled error",code:"ONL_0017",error:n.message},paymentId:Oe.paymentAttemptId})}},this.session.onpaymentmethodselected=async r=>{this.session.completePaymentMethodSelection({newTotal:{amount:this.getAmount(),label:this.store.name}}),m({type:"APPLE_PAY_PAYMENT_METHOD_SELECTED",data:{onPaymentMethodSelectedEvent:r.paymentMethod},paymentId:Oe.paymentAttemptId})},this.session.onshippingcontactselected=r=>{this.session.completeShippingContactSelection({newTotal:{amount:this.getAmount(),label:this.store.name}}),m({type:"APPLE_PAY_SHIPPING_CONTACT_SELECTED",data:{onShippingContactSelectedEvent:r.shippingContact},paymentId:Oe.paymentAttemptId})},this.session.onshippingmethodselected=r=>{this.session.completeShippingMethodSelection({newTotal:{amount:this.getAmount(),label:this.store.name}}),m({type:"APPLE_PAY_SHIPPING_METHOD_SELECTED",data:{onShippingMethodSelectedEvent:r.shippingMethod},paymentId:Oe.paymentAttemptId})},this.session.onpaymentauthorized=async r=>{await this.updateBillingContactInformation(Oe.paymentAttemptId,r.payment.billingContact);let n=await Rs(t._order,r.payment,{p:Oe.paymentAttemptId,t:this.order.terminalId});return this.session.completePayment(n?ApplePaySession.STATUS_SUCCESS:ApplePaySession.STATUS_FAILURE),n.step==="APPLE_PAY_AUTH_RESULT"&&n.data.approved?Oe.onSuccess():(m({type:"APPLE_PAY_AUTHORIZATION_FAILED",data:{log:"Authorization failed",code:"ONL_0025",data:JSON.stringify(n)},paymentId:Oe.paymentAttemptId}),Oe.onFailure({step:"ERROR",data:{errorCodes:["ONL_0025"],message:"Authorization failed"}}))},this.session.oncancel=async r=>{await Oe.onCancel(),m({type:"APPLE_PAY_CANCEL",data:{onCancelEventType:r.type},paymentId:Oe.paymentAttemptId})}}};async function Us(t){return await new Ir().initialize(t),{code:"ONL_0025",message:"Apple Pay payment initiated"}}function Fs(t){Ir.setOrderAndStore(t)}var qa=Ir.mountApplePay;function aa(t){return btoa(t).replace(/\+/g,"-").replace(/[\/]+/g,"_").replace(/=+$/,"")}var Bs=async function(t,e){let{data:r}=t;if(!r.url)throw new Error("ThreeDS Url is not present");Zc();let n={threeDSServerTransID:r.serverTransactionId,threeDSMethodNotificationURL:r.notificationUrl},{form:i,input:s}=Qc();if(!s||!i)throw new Error("Do not have enough permissions on browser to execute ThreeDS");let p=JSON.stringify(n),h=aa(p);return s.value=h,i.action=r.url,i.target="threeDSMethodIframe",i.submit(),{event:"IS_AUTH_COMPLETE_EVENT",data:{paymentId:e}}};function Zc(){let t=document.createElement("div");if(t.id="displayBox",t.setAttribute("width","1200px"),t.setAttribute("height","1200px"),document.body.appendChild(t),t){let e=document.createElement("iframe");e.setAttribute("sandbox","allow-forms allow-scripts allow-same-origin allow-downloads allow-modals"),e.setAttribute("allow","payment *"),e.classList.add("sb-hidden"),e.style.display="none",e.name="threeDSMethodIframe",t.appendChild(e)}}function Qc(){let t=document.createElement("form");t.id="threeDSMethodForm";let e=document.createElement("input");return e.type="hidden",e.name="threeDSMethodData",e.id="threeDSMethodData",t.appendChild(e),document.body.appendChild(t),{form:t,input:e}}var At=class t{static instance;modal=null;modalContent=null;contentWrapper=null;closeButton=null;config={};branding={};styleElement=null;isInitialized=!1;eventListeners=[];constructor(){}static getInstance(){return t.instance||(t.instance=new t),t.instance}initialize(e={}){this.isInitialized||(this.config={id:"surfboard-payment-modal",showCloseButton:!0,backdropBlur:!0,...e},this.branding={backgroundColor:"#FFFFFF",fontFamily:"system-ui, -apple-system, sans-serif",fontBaseSize:"16px",primaryColor:"#000000",secondaryColor:"#6B7280",borderRadius:"8px",buttonStyle:{backgroundColor:"#000000",textColor:"#FFFFFF",hoverColor:"#1F2937",borderRadius:"6px",fontSize:"16px"},contentPadding:"24px",...e.defaultBranding},this.createModalStructure(),this.attachEventListeners(),this.createStyles(),this.isInitialized=!0)}updateBranding(e){this.branding={...this.branding,...e,buttonStyle:{...this.branding.buttonStyle,...e.buttonStyle}},this.createStyles()}show(e){this.isInitialized||this.initialize(),this.setContent(e),this.modal&&(this.modal.style.display="flex",document.body.style.overflow="hidden",requestAnimationFrame(()=>{this.modal&&this.contentWrapper&&(this.modal.classList.add("sb-modal-visible"),this.contentWrapper.classList.add("sb-modal-content-visible"))}))}hide(){!this.modal||!this.contentWrapper||(this.modal.classList.remove("sb-modal-visible"),this.contentWrapper.classList.remove("sb-modal-content-visible"),setTimeout(()=>{this.modal&&(this.modal.style.display="none",document.body.style.overflow="",this.clearContent())},300))}createModalStructure(){this.modal=document.createElement("div"),this.modal.id=this.config.id,this.modal.className="sb-modal";let e=document.createElement("div");e.className="sb-modal-backdrop",this.contentWrapper=document.createElement("div"),this.contentWrapper.className="sb-modal-wrapper",this.modalContent=document.createElement("div"),this.modalContent.className="sb-modal-content",this.config.showCloseButton&&(this.closeButton=document.createElement("button"),this.closeButton.className="sb-modal-close",this.closeButton.textContent="\xD7",this.contentWrapper.appendChild(this.closeButton)),this.contentWrapper.appendChild(this.modalContent),this.modal.appendChild(e),this.modal.appendChild(this.contentWrapper),document.body.appendChild(this.modal)}createStyles(){this.styleElement&&document.head.removeChild(this.styleElement),this.styleElement=document.createElement("style"),this.styleElement.textContent=`
            .sb-modal {
                position: fixed;
                top: 0;
                left: 0;
                width: 100vw;
                height: 100vh;
                display: none;
                align-items: center;
                justify-content: center;
                z-index: 9999;
                opacity: 0;
                transition: opacity 0.3s ease-out;
            }

            .sb-modal-visible {
                opacity: 1;
            }

            .sb-modal-backdrop {
                position: absolute;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background-color: rgba(0, 0, 0, 0.5);
                ${this.config.backdropBlur?"backdrop-filter: blur(4px);":""}
            }

            .sb-modal-wrapper {
                position: relative;
                background: ${this.branding.backgroundColor};
                border-radius: ${this.branding.borderRadius};
                font-family: ${this.branding.fontFamily};
                font-size: ${this.branding.fontBaseSize};
                padding: ${this.branding.contentPadding};
                max-width: 95vw;
                max-height: 95vh;
                margin: 20px;
                box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
                transform: translateY(20px);
                opacity: 0;
                transition: transform 0.3s ease-out, opacity 0.3s ease-out;
            }

            .sb-modal-content-visible {
                transform: translateY(0);
                opacity: 1;
            }

            /* Ensure the direct content container can expand to fill wrapper */
            .sb-modal-content {
                width: 100%;
                height: 100%;
            }

            .sb-modal-close {
                position: absolute;
                top: 16px;
                right: 16px;
                width: 32px;
                height: 32px;
                border-radius: 50%;
                border: none;
                background: transparent;
                color: ${this.branding.secondaryColor};
                font-size: 24px;
                cursor: pointer;
                display: flex;
                align-items: center;
                justify-content: center;
                transition: background-color 0.2s;
            }

            .sb-modal-close:hover {
                background-color: rgba(0, 0, 0, 0.05);
            }

            .sb-modal-button {
                background: ${this.branding.buttonStyle?.backgroundColor};
                color: ${this.branding.buttonStyle?.textColor};
                border-radius: ${this.branding.buttonStyle?.borderRadius};
                font-size: ${this.branding.buttonStyle?.fontSize};
                padding: 12px 24px;
                border: none;
                cursor: pointer;
                transition: background-color 0.2s;
            }

            .sb-modal-button:hover {
                background: ${this.branding.buttonStyle?.hoverColor};
            }

            @media (max-width: 640px) {
                .sb-modal-wrapper {
                    width: 100%;
                    max-width: 100%;
                    max-height: 100%;
                    height: 100dvh; /* dynamic viewport height for mobile UI chrome */
                    margin: 0;
                    border-radius: 0;
                    padding: 0; /* remove padding so inner content (e.g., iframe) can be full-bleed */
                }
                .sb-modal-content {
                    width: 100%;
                    height: 100%;
                }
            }
        `,document.head.appendChild(this.styleElement)}setContent(e){this.modalContent&&(this.clearContent(),e.element.classList.add(`sb-modal-content-${e.type.toLowerCase()}`),e.customClass&&e.element.classList.add(e.customClass),e.styles&&(Object.assign(this.modalContent.style,e.styles),Object.assign(e.element.style,e.styles)),this.modalContent.appendChild(e.element))}clearContent(){if(this.modalContent)for(;this.modalContent.firstChild;)this.modalContent.removeChild(this.modalContent.firstChild)}attachEventListeners(){if(!this.modal)return;if(this.closeButton){let n=()=>{this.hide(),this.config.onClose?.()};this.closeButton.addEventListener("click",n),this.eventListeners.push({element:this.closeButton,event:"click",handler:n})}let e=n=>{n.target===this.modal&&(this.hide(),this.config.onClose?.())};this.modal.addEventListener("click",e),this.eventListeners.push({element:this.modal,event:"click",handler:e});let r=n=>{n.key==="Escape"&&this.modal?.style.display!=="none"&&(this.hide(),this.config.onClose?.())};document.addEventListener("keydown",r),this.eventListeners.push({element:document,event:"keydown",handler:r})}removeEventListeners(){this.eventListeners.forEach(({element:e,event:r,handler:n})=>{e.removeEventListener(r,n)}),this.eventListeners=[]}cleanup(){this.removeEventListeners(),this.styleElement&&document.head.contains(this.styleElement)&&document.head.removeChild(this.styleElement),this.modal&&document.body.contains(this.modal)&&document.body.removeChild(this.modal),this.isInitialized=!1,this.modal=null,this.modalContent=null,this.contentWrapper=null,this.closeButton=null}};var Hs=async function(t,e){let{data:r}=t;if(!r.url)throw new Error("ThreeDS Url is not present");Xc();let i=window.matchMedia("(max-width: 640px)").matches?"05":"03";return eu({acsTransID:r.acsTransID,challengeWindowSize:i,messageType:r.messageType,messageVersion:r.messageVersion,threeDSServerTransID:r.threeDSServerTransID},r.url),{event:"IS_CHALLENGE_COMPLETE_EVENT",data:{paymentId:e}}};function Xc(){let t=At.getInstance(),e=document.createElement("div");e.className="sb-wrapper",e.style.setProperty("width","100%","important"),e.style.setProperty("height","100dvh","important");let r=document.createElement("iframe");r.name="challengeIframe",r.setAttribute("sandbox","allow-forms allow-scripts allow-same-origin allow-downloads allow-modals"),r.setAttribute("allow","payment *"),r.setAttribute("allowpaymentrequest","true"),r.classList.add("sb-modal-challenge-content"),r.id="sb-modal-challenge-content",r.style.border="none",r.style.overflow="auto",r.style.setProperty("width","100%","important"),r.style.setProperty("height","100%","important"),r.style.display="block",e.appendChild(r);let n=window.matchMedia("(max-width: 640px)").matches;t.show({element:e,type:"OTHER",styles:n?{width:"100%",maxWidth:"100%",height:"100dvh",backgroundColor:"#FFFFFF"}:{width:"800px",maxWidth:"90vw",height:"90vh",backgroundColor:"#FFFFFF"}})}function eu(t,e){let{form:r,input:n}=tu();if(!n||!r)throw new Error("Do not have enough permissions on browser to execute ThreeDS");let i=JSON.stringify(t),s=aa(i);n.innerText=s,n.value=s,r.action=e,r.target="challengeIframe",r.method="post",r.submit()}function tu(){let t=document.createElement("form");t.id="challengeForm";let e=document.createElement("input");e.type="hidden",e.name="creq",e.id="creq",t.appendChild(e);let r=document.createElement("input");return r.type="hidden",r.name="threeDSSessionData",r.id="threeDSSessionData",t.appendChild(r),document.body.appendChild(t),{form:t,input:e}}async function Ys(t,e){let r=t.step,n=ru[r];return n?await n(t,e):{event:"ERROR_EVENT",data:{paymentId:e}}}var ru={CHALLENGE:async function(t,e){return await Hs(t,e)},THREE_DS_AUTH:async function(t,e){return await Bs(t,e)},PAYMENT_STATUS:async function(t,e){throw new Error("Function not implemented.")},ERROR:async function(t,e){return{event:"ERROR_EVENT",data:{paymentId:e}}},ACK:async function(t,e){return{event:"ACK_EVENT",data:{paymentId:e}}},IS_CHALLENGE_COMPLETE:async function(t,e){return{event:"IS_CHALLENGE_COMPLETE_EVENT",data:{paymentId:e}}},IS_AUTH_COMPLETE:async function(t,e){throw new Error("Function not implemented.")},APPLE_PAY_AUTH_RESULT:async function(t,e){throw new Error("Function not implemented.")},APPLE_PAY_SESSION:async function(t,e){throw new Error("Function not implemented.")},GOOGLE_PAY_AUTH_RESULT:async function(t,e){throw new Error("Function not implemented.")}};var vr=class{async waitForThreeDsAuth(e,r){return new Promise(n=>{let i={data:{paymentId:e},event:"IS_AUTH_COMPLETE_EVENT"},s=`threeds_auth_${e}`,p=`threeds_auth_state_${e}`,h=sessionStorage.getItem(p),b=h?JSON.parse(h):{authStarted:!1,retryCount:0,startTime:Date.now()};sessionStorage.setItem(p,JSON.stringify(b));let x=async()=>{try{let K=await(await ie.eR(e,r,i)).data(),V=JSON.parse(sessionStorage.getItem(p));return K.step==="IS_AUTH_COMPLETE"?(V.authStarted=!0,K.data.isComplete?(m({type:"THREEDS_AUTH_COMPLETE",paymentId:e,data:{message:"ThreeDS Auth completed successfully",authStarted:V.authStarted,retryCount:V.retryCount}}),sessionStorage.removeItem(p),n(K),!0):(V.retryCount++,sessionStorage.setItem(p,JSON.stringify(V)),m({type:"THREEDS_AUTH_RETRY",paymentId:e,data:{message:"ThreeDS Auth in progress",authStarted:V.authStarted,retryCount:V.retryCount}}),!1)):(m({type:"THREEDS_AUTH_DIFFERENT_STEP",paymentId:e,data:{step:K.step,message:"ThreeDS Auth received different step",authStarted:V.authStarted,retryCount:V.retryCount}}),sessionStorage.removeItem(p),n(K),!0)}catch(R){let K=JSON.parse(sessionStorage.getItem(p));return K.retryCount++,sessionStorage.setItem(p,JSON.stringify(K)),m({type:"THREEDS_AUTH_ERROR",paymentId:e,data:{message:"ThreeDS Auth encountered an error",error:R instanceof Error?R.message:String(R),authStarted:K.authStarted,retryCount:K.retryCount}}),!1}};pt.registerTask(s,x,{maxRetries:5,retryDelay:3e3,timeout:3e4,executeUntil:()=>{let R=JSON.parse(sessionStorage.getItem(p));return Date.now()-R.startTime>=3e4?(m({type:"THREEDS_AUTH_TIMEOUT",paymentId:e,data:{message:"ThreeDS Auth timed out after 30 seconds",authStarted:R.authStarted,retryCount:R.retryCount}}),sessionStorage.removeItem(p),n({step:"ERROR",data:{message:"ThreeDS Auth timed out after 30 seconds",data:void 0,errorCodes:["ONL_0005"]}}),!1):!0}})})}remove3DSModel(){At.getInstance().hide()}async handlerThreeDs(e,{orderId:r,paymentId:n,terminalId:i},s){let p=e;if(e.step==="THREE_DS_AUTH"){let h={event:"THREE_DS_AUTH_EVENT",data:{paymentId:n,threeDSCompInd:"U"}};p=await(await ie.eR(n,i,h)).data()}if(p.step==="CHALLENGE"){if(m({type:"THREE_DS_CHALLENGE_STARTED",data:{orderId:r,paymentId:n},paymentId:n}),await Ys(p,n),(await au({orderId:r,paymentId:n,terminalId:i},s)).step!=="IS_CHALLENGE_COMPLETE")return{step:"ERROR",data:{message:"ThreeDS Challenge auth did not complete",data:void 0,errorCodes:["ONL_0008"]}};let b={event:"CHALLENGE_EVENT",data:{paymentId:n,threeDSChallengeCompInd:"U"}};return await(await ie.eR(n,i,b)).data()}return p.step==="PAYMENT_STATUS"?p:{step:"ERROR",data:{message:"ThreeDS Auth/Challenge did not complete",data:void 0,errorCodes:["ONL_0005","ONL_0008"]}}}};async function nu(t,{orderId:e,paymentId:r,terminalId:n},i){try{let s=await Lt(i,()=>ie.eR(r,n,t));return[200,201,"OK","SUCCESS"].includes(s.status)?{status:"ONLINE",data:await s.data(),error:void 0}:(m({type:"THREEDS_NETWORK_ERROR_ONLINE",paymentId:r,data:{orderId:e,message:"ThreeDS Challenge terminated due to network error"}}),{status:"ONLINE",data:void 0,error:s.status})}catch(s){return s instanceof Error?navigator.onLine?(m({type:"THREEDS_NETWORK_ERROR_ONLINE",paymentId:r,data:{orderId:e,message:"ThreeDS Challenge terminated due to network error",error:s.message}}),{status:"ONLINE",data:void 0,error:s.message}):(m({type:"THREEDS_NETWORK_ERROR_OFFLINE",paymentId:r,data:{orderId:e,message:"ThreeDS Challenge terminated due to network error",error:s.message}}),{status:"OFFLINE",data:void 0,error:void 0}):(m({type:"THREEDS_NETWORK_ERROR_ONLINE_UNKNOWN",paymentId:r,data:{orderId:e,message:"ThreeDS Challenge terminated due to network error",error:s}}),{status:"ONLINE",data:void 0,error:`Unknown error: ${s}`})}}function ia(t){let e=`threeds_state_${t}`,r=sessionStorage.getItem(e);if(r)return JSON.parse(r);let n={challengeStarted:!1,consecutiveDifferentSteps:0,startTime:Date.now()};return sessionStorage.setItem(e,JSON.stringify(n)),n}function Vs(t,e){let r=`threeds_state_${t}`,i={...ia(t),...e};return sessionStorage.setItem(r,JSON.stringify(i)),i}async function au({orderId:t,paymentId:e,terminalId:r},n){return new Promise(i=>{let h=ia(e),b={data:{paymentId:e},event:"IS_CHALLENGE_COMPLETE_EVENT"},x=`threeds_challenge_${e}`,R=async()=>{let K=await nu(b,{orderId:t,paymentId:e,terminalId:r},n);if(K.status!=="ONLINE")return m({type:"THREEDS_NETWORK_ERROR_OFFLINE",paymentId:e,data:{orderId:t,message:"ThreeDS Challenge terminated due to network error"}}),!1;let V=K.data;if(!V)return m({type:"THREEDS_NETWORK_ERROR_ONLINE",paymentId:e,data:{orderId:t,message:"ThreeDS Challenge terminated due to network error",error:K.error}}),i({step:"ERROR",data:{message:"ThreeDS terminated due to an error",data:void 0,errorCodes:["ONL_0008"]}}),!0;if(V.step==="IS_CHALLENGE_COMPLETE"){let le=Vs(e,{challengeStarted:!0,consecutiveDifferentSteps:0});m({type:"THREEDS_CHALLENGE_STARTED",paymentId:e,data:{challengeStarted:le.challengeStarted,consecutiveDifferentSteps:le.consecutiveDifferentSteps}});let me=V;return me.data.isComplete?(m({type:"THREEDS_CHALLENGE_COMPLETE",paymentId:e,data:{challengeStarted:le.challengeStarted,consecutiveDifferentSteps:le.consecutiveDifferentSteps}}),sessionStorage.removeItem(`threeds_state_${e}`),i(me),!0):!1}let H=ia(e);if(H.challengeStarted){let le=Vs(e,{consecutiveDifferentSteps:H.consecutiveDifferentSteps+1});if(m({type:"THREEDS_CHALLENGE_CONSECUTIVE",paymentId:e,data:{challengeStarted:le.challengeStarted,consecutiveDifferentSteps:le.consecutiveDifferentSteps}}),le.consecutiveDifferentSteps>=3)return sessionStorage.removeItem(`threeds_state_${e}`),i(V),!0}return H.challengeStarted?!1:(m({type:"THREEDS_CHALLENGE_NOT_STARTED_YET_ERROR",paymentId:e,data:{challengeStarted:H.challengeStarted,consecutiveDifferentSteps:H.consecutiveDifferentSteps,step:V.step}}),sessionStorage.removeItem(`threeds_state_${e}`),i(V),!0)};pt.registerTask(x,R,{maxRetries:100,retryDelay:3e3,timeout:3e5,executeUntil:()=>{let K=ia(e);return Date.now()-K.startTime>=3e5?(m({type:"THREEDS_CHALLENGE_TIMEOUT",paymentId:e,data:{orderId:t,message:"ThreeDS Challenge timed out after 5 minutes"}}),sessionStorage.removeItem(`threeds_state_${e}`),i({step:"ERROR",data:{message:"ThreeDS Challenge timed out after 5 minutes",data:void 0,errorCodes:["ONL_0008"]}}),!1):!0}})})}async function Gs(t,e,r){return m({type:"GOOGLE_PAY_PROCESS_PAYMENT",data:{},paymentId:r.p}),await(await Lt(t,()=>ie.gP(e,r.p,r.t))).data()}var iu={da:"da",en:"en",fi:"fi",sv:"sv",no:"no"};function $s(){return iu[g.SDK_LANGUAGE]??"en"}var ou=he(),Yt=class t{constructor(e){this.callbacks=e;this.order=t._order.order,this.store=t._order.store,this.orderHandler=t._order}static surfboardGooglePayMerchantId="BCR2DN4TS6QJR3ZJ";static id="";static cdnLoaded=!1;static _order;static googlePayCDNUrl="https://pay.google.com/gp/p/js/pay.js";static client;static dummyCallbacks={onPaymentAuthorized:async function(e){return{transactionState:"ERROR"}},onPaymentDataChanged:async function(e){return{}}};static authCallbacks=t.dummyCallbacks;static setOrderAndStore(e){t._order=e}order;store;orderHandler;static getMerchantInfo(){return{merchantId:t._order.order.googlePayMerchantId||t.surfboardGooglePayMerchantId,merchantName:t._order.store.name,merchantOrigin:`${window.location.host}`}}static reset(){t.client=void 0}static setupGooglePay(){let e=t.getMerchantInfo();return wt({eventType:"GOOGLE_PAY_MERCHANT_ID_SELECTED",inputData:{log:"Google pay merchant id selected",merchantId:e.merchantId,isCustomMerchantId:`${e.merchantId!==t.surfboardGooglePayMerchantId}`}}),t.client=new google.payments.api.PaymentsClient({environment:"PRODUCTION",merchantInfo:e,paymentDataCallbacks:{onPaymentAuthorized:r=>t.authCallbacks.onPaymentAuthorized(r)}}),!!t.client}updateBillingContactInformation(e,r){let n={},i=Ms();if(r.paymentMethodData.info?.billingAddress){let s=r.paymentMethodData.info.billingAddress;m({type:"GOOGLE_PAY_UPDATE_BILLING_PHONE",data:{},paymentId:e}),i=s.countryCode??i,n.billingAddress={addressLine1:`${s.address1}`,addressLine2:s.address2||void 0,addressLine3:s.address3||void 0,careOf:s.name,city:na(`${s.locality||s.administrativeArea}`),countryCode:`${s.countryCode}`,postalCode:`${s.postalCode?.replace(/\s/g,"")??ra(s.countryCode)}`}}if(r.paymentMethodData.info?.billingAddress?.phoneNumber){m({type:"GOOGLE_PAY_UPDATE_BILLING_PHONE",data:{},paymentId:e});let s=r.paymentMethodData.info.billingAddress.phoneNumber.replace(/\s/g,""),p=xr(s,i);p?n.phone={number:p.number,countryCode:p.countryCode}:n.phone={number:s,countryCode:"+46"}}return r.email&&(m({type:"GOOGLE_PAY_UPDATE_BILLING_EMAIL",data:{},paymentId:e}),n.email=r.email),this.orderHandler.addCustomerInformation(n).then(()=>{m({type:"GOOGLE_PAY_UPDATED_BILLING_INFORMATION",data:{},paymentId:e})}).catch(s=>{m({type:"GOOGLE_PAY_UPDATED_BILLING_INFORMATION_FAILED",data:{log:"Failed to update billing information",code:"ONL_0027",error:s.message},paymentId:e})})}static baseRequest={apiVersion:2,apiVersionMinor:0};static tokenizationSpecification={type:"PAYMENT_GATEWAY",parameters:{gateway:"surfboard",gatewayMerchantId:"googletest"}};static allowedCardNetworks=["AMEX","DISCOVER","MASTERCARD","VISA"];static allowedCardAuthMethods=["CRYPTOGRAM_3DS","PAN_ONLY"];static allowedPaymentMethods=[{type:"CARD",parameters:{allowedAuthMethods:this.allowedCardAuthMethods,allowedCardNetworks:this.allowedCardNetworks,billingAddressRequired:!0,billingAddressParameters:{format:"FULL",phoneNumberRequired:!0},assuranceDetailsRequired:!0},tokenizationSpecification:this.tokenizationSpecification}];static async loadGooglePay(){let e=await t.ensureSdkAvailability();return this.client?e?!0:(m({type:"GOOGLE_PAY_SDK_LOAD_FAILED",data:{log:"Google pay sdk load failed"}}),!1):t.setupGooglePay()}static async ensureSdkAvailability(){return new Promise(e=>{if(t.cdnLoaded)e(!0);else{setTimeout(()=>{e(!1)},5e3);let r=ou.ce("script");r.src=t.googlePayCDNUrl,r.onload=()=>{t.cdnLoaded=!0,m({type:"GOOGLE_PAY_SDK_LOADED",data:{log:"Google pay sdk loaded"}}),e(!0)},he().ahc(r)}})}static get paymentsClient(){return t.client||(t.setupGooglePay(),m({type:"GOOGLE_PAY_SDK_NOT_LOADED_RELOADING",data:{log:"Google pay sdk load failed, reloading the client"}})),t.client}static get isReadyToPay(){return this.paymentsClient.isReadyToPay({...this.baseRequest,allowedPaymentMethods:this.allowedPaymentMethods})}static get getButtonStyleFromBrandConfig(){return{buttonColor:"black",buttonSizeMode:"fill",buttonType:"pay",buttonLocale:$s(),allowedPaymentMethods:t.allowedPaymentMethods,buttonRadius:5}}static async mountGooglePay(e){if(t._order&&(t._order.isTokenizedOrder||t._order.subscriptionData?.frequency)===!0){m({type:"GOOGLE_PAY_SDK_DISABLED_TOKENISATION",data:{mountPointId:e}});return}if(!await t.loadGooglePay()){m({type:"GOOGLE_PAY_MOUNT_FAILED",data:{log:"Google pay mount failed, loadGooglePay is false"}});return}if(!(await t.isReadyToPay).result){m({type:"GOOGLE_PAY_MOUNT_FAILED",data:{log:"Google pay mount failed, isReadyToPay is false"}});return}let n=he().ge(e);if(!n){m({type:"GOOGLE_PAY_MOUNT_FAILED",data:{log:"Google pay mount failed, mount point not found"}});return}let i=t.paymentsClient.createButton({onClick:async()=>{m({type:"GOOGLE_PAY_INITIATED",data:{log:"Google pay initiated",orderId:t._order.order.orderId}}),await window.SurfboardOnlineSDK.order.initiatePayments("GOOGLE_PAY")},...t.getButtonStyleFromBrandConfig});n.appendChild(i),n.classList.contains("sb-hidden")&&n.classList.remove("sb-hidden"),n.attributes.getNamedItem("hidden")&&n.attributes.removeNamedItem("hidden"),t.id=i.id,m({type:"GOOGLE_PAY_MOUNTED",data:{log:"Google pay button mounted"}})}createPaymentDataRequest(){return{...t.baseRequest,allowedPaymentMethods:t.allowedPaymentMethods,transactionInfo:{currencyCode:ta(this.order.totalOrderPriceCurrency),totalPriceStatus:"FINAL",totalPriceLabel:"Total",totalPrice:`${(parseInt(this.order.totalOrderPriceValue)/100).toFixed(2)}`,countryCode:this.store.address.countryCode,displayItems:[]},merchantInfo:t.getMerchantInfo(),emailRequired:!0,callbackIntents:["PAYMENT_AUTHORIZATION"]}}async initiatePayment(e){try{let r=await t.paymentsClient.loadPaymentData(e);m({type:"GOOGLE_PAY_TOKEN",data:{log:"Received the Google Pay token"}})}catch(r){m({type:"GOOGLE_PAY_TOKEN_FAILED",data:{log:`Failed to get the Google Pay token with message ${r.message}`}})}}initialize(){this.updateCallbacks(),this.initiatePayment(this.createPaymentDataRequest())}updateCallbacks(){let e=this;t.authCallbacks.onPaymentAuthorized=async function(r){let n=await e.callbacks.createPaymentId();if(e.updateBillingContactInformation(n,r),m({type:"GOOGLE_PAY_AUTHORIZATION_STARTED",data:{apiVersionMinor:`${r.apiVersionMinor}`,apiVersion:`${r.apiVersion}`,type:`${r.paymentMethodData.type}`},paymentId:n}),r.paymentMethodData.type==="CARD"&&r.paymentMethodData.tokenizationData.type==="PAYMENT_GATEWAY"){r.paymentMethodData.info;let i=Ye(),s={...r,browser:{browserTZ:i.browserTZ,colorDepth:"32",javaEnabled:i.isJavaEnabled,jsEnabled:!0,language:i.language,screenHeight:i.screenHeight,screenWidth:i.screenWidth,userAgent:i.userAgent}},p=await Gs(t._order,s,{p:n,t:e.order.terminalId});if(p.step==="GOOGLE_PAY_AUTH_RESULT")return m({type:"GOOGLE_PAY_AUTHORIZATION_COMPLETED",data:{log:"Google pay authorization completed",step:p.step,data:p.data,paymentId:n}}),p.data.approved?(e.callbacks.onSuccess(),{transactionState:"SUCCESS"}):{transactionState:"ERROR"};if(["THREE_DS_AUTH","CHALLENGE"].includes(p.step)){let h=su();return m({type:"GOOGLE_PAY_AUTHORIZATION_STARTED",data:{log:"Google pay authorization started",step:p.step,data:p.data,paymentId:n}}),e.callbacks.handleThreeDS(p,n,async()=>{m({type:"GOOGLE_PAY_3DS_STARTED",data:{log:"Google pay 3DS started",step:p.step,data:p.data,paymentId:n}}),h.remove()}).then(()=>{m({type:"GOOGLE_PAY_AUTHORIZATION_COMPLETED",data:{log:"Google pay authorization completed",step:p.step,data:p.data,paymentId:n}})}).catch(b=>{m({type:"GOOGLE_PAY_ERROR",data:{log:"Google pay error",error:b.message,step:p.step,data:p.data,paymentId:n}})}),{transactionState:"SUCCESS"}}return m({type:"GOOGLE_PAY_AUTHORIZATION_FAILED",data:{log:"Google pay authorization failed",step:p.step,data:p.data,paymentId:n}}),await e.callbacks.onFailure({step:"ERROR",data:{message:"Payment Failed with google pay",errorCodes:["ONL_0038"]}}),{transactionState:"ERROR"}}return m({type:"GOOGLE_PAY_AUTHORIZATION_FAILED",data:{log:"Authorization failed",code:"ONL_0038",data:JSON.stringify(r)},paymentId:n}),await e.callbacks.onCancel(),{transactionState:"ERROR"}},t.authCallbacks.onPaymentDataChanged=async function(r){switch(r.callbackTrigger){case"INITIALIZE":return{};case"OFFER":return{};case"SHIPPING_ADDRESS":return{};case"SHIPPING_OPTION":return{}}}}};function su(){let t=he(),e=t.ce("div");e.classList.add("sb-loader-overlay"),e.classList.add("sb-loader-google-pay"),e.style="position:fixed;top:0;left:0;width:100%;height:100%;z-index:9999;background-color:rgba(0,0,0,0.5);display:flex;flex-direction:column;justify-content:center;align-items:center;";let r=t.ce("div");r.classList.add("sb-loader");let n=t.ce("span");return n.innerText="Authorizing with Google Pay, please wait...",n.style="color:white;font-family:Arial,sans-serif;font-size:16px;margin-top:20px;text-align:center;",e.appendChild(r),e.appendChild(n),t.de.appendChild(e),e}async function js(t,e){let r={cancel:async()=>null};return await new Yt({onSuccess:async function(){},onFailure:async function(i){let s=i?.data?.errorCodes?.[0]??"ONL_0038";m({type:"GOOGLE_PAY_ERROR",data:{error:s}}),F(s)},onCancel:async function(){await r.cancel()},createPaymentId:async function(){let i=await ie.iR("CARD");if(i.code)return i;let s=await i.data();if(s.status==="ERROR"||s.data.status==="ERROR")return F("ON_012");let{paymentId:p}=s.data;m({type:"GOOGLE_PAY_INITIATED",data:{},paymentId:p}),m({type:"DATA_COLLECTOR_AFTER_GOOGLE_PAY_INITIATION",data:{...Ye()},paymentId:p});let h=new xe(p);return e(h),r.cancel=async()=>(h.cancelPayment(),null),p},handleThreeDS:async(i,s,p)=>{if(await p(),["THREE_DS_AUTH","CHALLENGE"].includes(i.step)){let h=new vr;m({type:"THREE_DS_AUTH_REQUESTED",data:{},paymentId:s});let b=await h.handlerThreeDs(i,{paymentId:s,orderId:t.order.orderId,terminalId:t.order.terminalId},t);h.remove3DSModel(),["ERROR","PAYMENT_STATUS"].includes(b.step)&&(Or(),b.step==="ERROR"&&F("ON_019"))}}}).initialize(),{code:"ONL_0024",message:"Google Pay payment initiated"}}async function qs(t){Yt.setOrderAndStore(t)}var za=Yt.mountGooglePay;var zs=ht(Xn());var Nr=class extends Error{invalid_fields;static isKlarnaError(e){return e.invalid_fields}};var oa=class{constructor(e){this.config=e}container=null;createModalContent(){this.container=document.createElement("div"),this.container.classList.add("sb-klarna-container","sb-wrapper");let e=document.createElement("img");e.src="https://x.klarnacdn.net/payment-method/assets/badges/generic/klarna.svg",e.classList.add("sb-klarna-logo-image"),this.container.appendChild(e);let r=document.createElement("div");r.id=g.KLARNA_MOUNT_POINT,r.classList.add("sb-klarna-widget-div"),this.container.appendChild(r);let n=document.createElement("div");n.classList.add("sb-klarna-bottom-section");let i=document.createElement("button");i.classList.add("sb-klarna-go-back-button","sb-w-full"),i.innerText="Go Back",i.onclick=()=>this.config.onBack();let s=document.createElement("button");return s.classList.add("sb-klarna-proceed-button","sb-w-full"),s.innerText="Proceed",s.onclick=async()=>{try{await this.config.onProceed()}catch{}},n.appendChild(i),n.appendChild(s),this.container.appendChild(n),setTimeout(()=>this.initializeKlarnaWidget(),0),this.container}async initializeKlarnaWidget(){try{await window.Klarna.Payments.load({container:`#${g.KLARNA_MOUNT_POINT}`},{},e=>{if(e.show_form===!1)throw m({type:"KLARNA_WIDGET_LOADED_FAILED",data:{logs:"Klarna widget load failed",fields:`${JSON.stringify(e)}`}}),new Nr(`Klarna payment widget load failed: ${JSON.stringify(e)}`,{cause:Qe.klarnaPaymentWidgetLoadFailed});m({type:"KLARNA_WIDGET_LOADED",data:{}})})}catch(e){throw m({type:"KLARNA_WIDGET_LOAD_ERROR",data:{error:e instanceof Error?e.message:"Unknown error"}}),e}}getContentType(){return"KLARNA"}getContentStyles(){return{}}};var nr=class{static cdnLoaded=!1;static pA=null;static modal=At.getInstance();static async ensureSdkAvailability(){return new Promise(e=>{if(this.cdnLoaded){e(!0);return}let r=setTimeout(()=>e(!1),5e3),n=document.createElement("script");n.src="https://x.klarnacdn.net/kp/lib/v1/api.js",n.onload=()=>{this.cdnLoaded=!0,clearTimeout(r),e(!0)},document.body.appendChild(n)})}static async mountKlarna(){if(g.KLARNA_MOUNT_POINT=`klarna-${(0,zs.generateID)("HEX")}`,!await this.ensureSdkAvailability())return F(Qe.klarnaSDKLoadFailed);this.modal.initialize({showCloseButton:!1,backdropBlur:!0,defaultBranding:{backgroundColor:"#FFFFFF",fontFamily:"system-ui, -apple-system, sans-serif",primaryColor:"#000000"}})}static async initializePayment(e,r){if(!this.cdnLoaded)return await F(Qe.klarnaSDKLoadFailed);if(!this.validateCustomerData(e))return await F(Qe.invalidOnlineParams);try{let n=await ie.iR("KLARNA");if(n.code)return n;let i=await n.data();if(!this.isSuccessfulResponse(i))return m({type:"FETCH_KLARNA_CLIENT_TOKEN_FAILED",data:{log:`Klarna client token fetch failed for orderId: ${g.ORDER_ID}`,orderId:g.ORDER_ID,paymentId:i.data.paymentId}}),await F(Qe.sbPaymentInitFailed);this.pA=new xe(i.data.paymentId),await window.Klarna.Payments.init({client_token:i.data.klarnaClientToken});let s=new oa({paymentId:i.data.paymentId,customer:e,emd:r,onProceed:async()=>{await this.authorize(i.data.paymentId,e,r)},onBack:()=>{this.modal.hide(),this.pA&&(this.pA.cancelPayment(),this.pA=null)}});return this.modal.show({element:s.createModalContent(),type:s.getContentType(),styles:s.getContentStyles()}),this.pA}catch(n){return m({type:"KLARNA_INITIATION_FAILED",data:{log:"Klarna payment initiation failed",error:n instanceof Error?n.message:"Unknown error",orderId:g.ORDER_ID}}),await F(Qe.klarnaPaymentInitFailed)}}static validateCustomerData(e){if(!e||!e.name||!e.email||!e.phone||!e.billingAddress)return!1;let r=e.name.split(" ");return!(r.length<2||r[r.length-1].length<2)}static isSuccessfulResponse(e){return e?.status==="SUCCESS"&&e?.data?.paymentId&&e?.data?.klarnaClientToken}static async authorize(e,r,n){try{if(m({type:"KLARNA_AUTH_STARTED",data:{message:"Klarna auth started",orderId:g.ORDER_ID,paymentId:e,customer:r},paymentId:e}),this.modal.hide(),!this.validateCustomerData(r))return F(Qe.invalidOnlineParams);let i=this.frameAddressForKlarna({name:r.name,email:r.email,phone:r.phone,address:r.billingAddress}),s=this.frameAddressForKlarna({name:r.shippingName,email:r.shippingEmail,phone:r.shippingPhone,address:r.shippingAddress})??i,p={billing_address:i,shipping_address:s,attachment:this.frameEMDForOnline(n)};m({type:"KLARNA_AUTH_INPUT_DATA",data:{message:`Klarna auth requested with following input data: ${JSON.stringify(p)}`,orderId:g.ORDER_ID,paymentId:e},paymentId:e}),window.Klarna.Payments.authorize({},p,async function(h){if(m({type:"KLARNA_AUTHORIZATION_RESPONSE",data:{data:JSON.stringify(h),orderId:g.ORDER_ID,paymentId:e},paymentId:e}),h.authorization_token){m({type:"KLARNA_AUTHORIZATION_SUCCESS",data:{data:JSON.stringify(h),orderId:g.ORDER_ID},paymentId:e});try{let b=await ie.pO(h.authorization_token,e);if(b.code){let R=b;m({type:"KLARNA_ORDER_PLACEMENT_FAILED",data:{message:R.message,orderId:g.ORDER_ID,paymentId:e},paymentId:e}),F(R.code);return}let x=await b.data();if(x.status==="SUCCESS"&&x.data?.placeKlarnaOrder.status==="SUCCESS")m({type:"KLARNA_ORDER_PLACEMENT_SUCCESS",data:{data:JSON.stringify(h),orderId:g.ORDER_ID,paymentId:e},paymentId:e});else throw new Error(x.data?.placeKlarnaOrder.message||"Klarna order placement failed")}catch(b){m({type:"KLARNA_ORDER_PLACEMENT_FAILED",data:{message:b.message,orderId:g.ORDER_ID,paymentId:e},paymentId:e}),F(Qe.klarnaPlaceOrderFailed)}}else h.show_form&&h.approved===!1?(h.error?m({type:"KLARNA_AUTHORIZATION_FAILED",data:{log:"Rejected authorization with fixable errors",fields:`${h.error.invalid_fields?.join(",")}`,message:h.error?.message,orderId:g.ORDER_ID,paymentId:e},paymentId:e}):m({type:"KLARNA_AUTHORIZATION_FAILED",data:{log:"Rejected authorization with fixable errors",orderId:g.ORDER_ID,paymentId:e},paymentId:e}),F(Qe.klarnaPaymentAuthFailedWithFixableErrors,!1)):h.approved&&h.show_form&&h.finalize_required?h.error&&m({type:"KLARNA_MULTI_STEP_AUTHORIZATION_FAILED",data:{log:"Rejected multi-step ",fields:`${h.error.invalid_fields?.join(",")}`,message:h.error?.message,orderId:g.ORDER_ID,paymentId:e},paymentId:e}):h.approved===!1&&h.show_form===!1&&(h.error?m({type:"KLARNA_AUTHORIZATION_FAILED",data:{log:"Rejected authorization",fields:`${h.error.invalid_fields?.join(",")}`,message:h.error?.message,orderId:g.ORDER_ID,paymentId:e},paymentId:e}):m({type:"KLARNA_AUTHORIZATION_FAILED",data:{log:"Rejected authorization",fields:`${JSON.stringify(h)}`,orderId:g.ORDER_ID,paymentId:e},paymentId:e}),F(Qe.klarnaPaymentAuthFailed))})}catch(i){Nr.isKlarnaError(i)&&m({type:"KLARNA_ERROR",data:{message:i.message,fields:`${i.invalid_fields?.join(",")}`,orderId:g.ORDER_ID,paymentId:e},paymentId:e}),F(Qe.klarnaPaymentAuthFailed)}}static frameEMDForOnline(e){return e?{content_type:"application/vnd.klarna.internal.emd-v2+json",body:e}:null}static frameAddressForKlarna(e){let r=e.address;if(!(e&&r&&e.name&&e.email&&e.phone))return;let[n,...i]=e.name.split(" ");return{given_name:n,family_name:`${i.pop()}`,email:e.email,street_address:this.formatStreetAddress(r.addressLine1,r.addressLine2,r.addressLine3),postal_code:r.postalCode?.replace(/[^a-zA-Z0-9]/g,""),city:r.city,country:r.countryCode,phone:`${e.phone.countryCode} ${e.phone.number}`}}static formatStreetAddress=(e,r,n)=>[e,r,n].filter(Boolean).join(", ")};var Cr=class t{static order;static initialize(e){t.order=e}static isInitialized(){return!!t.order}static async initiateSvea(e,r,n){try{let i=decodeURIComponent(r),s=JSON.parse(atob(i)),p=`${s.loadUrl}/${e}/${r}?branding=${s.branding}`,h=du(p),b=lu(h,n);return g.ADD_TERMINAL_CALLBACK(async x=>{b.remove()}),{status:"SUCCESS"}}catch(i){return m({type:`SVEA_${n.toUpperCase()}_PAYMENT_ERROR`,data:{errorCode:"ONL_0038",errorMessage:i instanceof Error?i.message:`${i}`,sveaParams:r},paymentId:e}),{status:"ERROR",errorCode:"ONL_0038"}}}};function du(t){let e=document.createElement("iframe");return e.src=t,e.width="100%",e.height="100%",e}function lu(t,e){let r=he(),n=r.ce(we.d);n.className="w-screen h-screen ",n.id=`sb-svea-${e.toLowerCase()}-execute-payment`,n.setAttribute("style","z-index: 9999;background-color: rgba(0, 0, 0, 0.5);backdrop-filter: blur(10px);display: none;position: fixed;top: 0;left: 0;");let i=r.ce(we.d);i.className="items-center justify-center w-full h-full modal-center flex m-auto";let s=r.ce(we.d);return s.className="flex flex-col m-auto",s.style.width="90%",s.style.height="90%",i.style.margin="auto",i.style.height="100%",s.style["z-index"]="9999",i.appendChild(s),s.appendChild(t),n.appendChild(i),n.style.display="block",document.body.appendChild(n),n}async function Ws(t){Cr.order=t}function Js(t,e){let r=uu(e),n=pu(r);return window.addEventListener("message",cu(t,r,n)),fe("ACCTOACC_IFRAME_CREATED"),{status:"SUCCESS"}}function cu(t,e,r){return function(i){if(i.origin!=="https://a2a.withsurfboard.com"){fe("REDIRECT_FROM_UNKNOWN_URL",{url:i.origin,data:i.data});return}let{type:s}=i.data;switch(s){case"PAYMENT_COMPLETED":e.remove(),r.remove(),t.getPaymentStatus();break;case"PAYMENT_FAILED":e.remove(),r.remove(),t.getPaymentStatus();break;case"PAYMENT_CANCELLED":e.remove(),r.remove(),t.cancelPayment();break}}}function uu(t){let e=document.createElement("iframe");return e.src=t,e.width="100%",e.height="100%",e}function pu(t){let e=he(),r=e.ce(we.d);r.className="w-screen h-screen ",r.id="sb-acctoacc-execute-payment",r.setAttribute("style","z-index: 9999;background-color: rgba(0, 0, 0, 0.5);backdrop-filter: blur(10px);display: none;position: fixed;top: 0;left: 0;");let n=e.ce(we.d);n.className="items-center justify-center w-full h-full modal-center flex m-auto";let i=e.ce(we.d);return i.className="flex flex-col m-auto",i.style.width="90%",i.style.height="90%",n.style.margin="auto",i.style["z-index"]="9999",n.appendChild(i),i.appendChild(t),r.appendChild(n),r.style.display="block",document.body.appendChild(r),r}var Zs=[{name:"Nordea",bic:"NDEASESS",logoURL:"https://enablebanking.com/brands/SE/Nordea",country:"SE"},{name:"Swedbank/Sparbankerna",bic:"SWEDSESS",logoURL:"https://enablebanking.com/brands/SE/Swedbank",country:"SE"},{name:"Handelsbanken",bic:"HANDSESS",logoURL:"https://enablebanking.com/brands/SE/Handelsbanken",country:"SE"},{name:"SEB",bic:"ESSESESS",logoURL:"https://enablebanking.com/brands/SE/SEB",country:"SE"},{name:"L\xE4nsf\xF6rs\xE4kringar",bic:"ELLFSESS",logoURL:"https://enablebanking.com/brands/SE/L%C3%A4nsf%C3%B6rs%C3%A4kringar%20Bank",country:"SE"},{name:"ICA",bic:"IBCASES1",logoURL:"https://static.openfintech.io/vendors/icabanken/logo.png?w=400&c=v0.59.26#w200",country:"SE"},{name:"Skandiabanken",bic:"SKIASESS",logoURL:"https://enablebanking.com/brands/SE/Skandia",country:"SE"},{name:"OP Bank",bic:"OKOYFIHH",logoURL:"https://enablebanking.com/brands/FI/OP",country:"FI"},{name:"Nordea",bic:"NDEAFIHH",logoURL:"https://enablebanking.com/brands/FI/Nordea",country:"FI"},{name:"Danske Bank",bic:"DABAFIHH",logoURL:"https://enablebanking.com/brands/FI/Danske%20Bank",country:"FI"},{name:"Aktia",bic:"HELSFIHH",logoURL:"https://enablebanking.com/brands/FI/Aktia",country:"FI"},{name:"Alandsbanken",bic:"AABAFI22",logoURL:"https://seekvectorlogo.com/wp-content/uploads/2018/04/alandsbanken-vector-logo.png",country:"FI"},{name:"POP Pankki",bic:"POPFFI22",logoURL:"https://enablebanking.com/brands/FI/POP%20Pankki",country:"FI"},{name:"S-Pankki",bic:"SBANFIHH",logoURL:"https://enablebanking.com/brands/FI/S-Pankki",country:"FI"},{name:"Handelsbanken",bic:"HANDFIHH",logoURL:"https://enablebanking.com/brands/FI/Handelsbanken",country:"FI"},{name:"S\xE4\xE4st\xF6pankki",bic:"ITELFIHH",logoURL:"https://enablebanking.com/brands/FI/S%C3%A4%C3%A4st%C3%B6pankki",country:"FI"},{name:"OMA s\xE4\xE4st\xF6pankki",bic:"OMSAFI2S",logoURL:"https://enablebanking.com/brands/FI/Oma%20S%C3%A4%C3%A4st%C3%B6pankki",country:"FI"},{name:"Danskebank",bic:"DABADKKK",logoURL:"https://enablebanking.com/brands/DK/Danske%20Bank",country:"DK"},{name:"Jyskebank",bic:"JYBADKKK",logoURL:"https://enablebanking.com/brands/DK/Jyske%20Bank",country:"DK"},{name:"Nykredit",bic:"NYKBDKKK",logoURL:"https://enablebanking.com/brands/DK/Nykredit%20Bank",country:"DK"},{name:"Sydbank",bic:"SYBKDK22",logoURL:"https://enablebanking.com/brands/DK/Sydbank",country:"DK"},{name:"Nordea",bic:"NDEADKKK",logoURL:"https://enablebanking.com/brands/DK/Nordea",country:"DK"},{name:"Arbejdernes Landsbank",bic:"ALBADKKK",logoURL:"https://enablebanking.com/brands/DK/Arbejdernes%20Landsbank/",country:"DK"}];function Qs(t){return Zs.findIndex(e=>e.bic===t)>-1}function Xs(t){return Zs.filter(e=>e.country===t)}var tn=class{_order;_merchant;_store;_branding;_paymentMethods;_customer;errorState=!1;_pA=null;constructor(){if(g.IS_INITIALISED!=="TRUE")throw new _r("Surfboard SDK is not initialised")}async reset(){g.MOUNT_POINTS&&await ed(g.MOUNT_POINTS),this._pA=null}getPaymentAttempt(){return this._pA}getBankList(e=this._store?.address?.countryCode){return Xs(e)}async fetchOrderInternal(){let e=await(await ie.oR()).data();if(e.status!=="SUCCESS"||e.data.order.status!=="SUCCESS")throw e.message?.includes("User authentication required ")&&(m({type:"ERROR",data:{log:"Expired link",data:e.message}}),g.ERROR_CALLBACK("401","Invalid or Expired Link. Cannot proceed")),this.errorState=!0,m({type:"ERROR",data:{log:"Error in fetching order details"}}),new Error("Invalid or Expired Link. Cannot proceed");m({type:"ORDER_FETCHED",data:{orderId:e.data.order.data.order.orderId}}),m({type:"DATA_COLLECTOR",data:{...Ye(),orderId:e.data.order.data.order.orderId}});try{let r=e.data.order.data;this._order=Ze(r.order),this._merchant=Ze(r.merchant),this._store=Ze(r.store),this._branding=Ze(r.branding),r.order.isTokenizationEnabled&&(r.paymentMethods.supportedPaymentMethods=["CARD"]),this._paymentMethods=Ze(r.paymentMethods);let n=this._order.shippingPhone?.countryCode&&this._order.shippingPhone?.number?this._order.shippingPhone:null;this._customer=Ze({name:this._order.memberName,email:this._order.memberEmail,phone:this._order.memberPhone,billingAddress:this._order.billingAddress,shippingName:this._order.shippingName,shippingEmail:this._order.shippingEmail,shippingPhone:n,shippingAddress:this._order.shippingAddress}),delete this._order.memberEmail,delete this._order.memberPhone,delete this._order.billingAddress,this._order.amount=Ze(r.amount),g.PAYMENT_STATUS_CALLBACK({paymentStatus:this._order.orderStatus}),Fs(this),qs(this),Ws(this)}catch(r){throw m({type:"ORDER_FETCHING_FAILED",data:{message:`Fetching Order Failed ${r.message}`}}),new Error("Fetching Order Failed. Cannot proceed")}}get transactionsInfo(){return this._order.transactionInfo}get amount(){return this._order.amount}get order(){return this._order}get merchant(){return this._merchant}get branding(){return this._branding}get store(){return this._store}get paymentMethods(){return this._paymentMethods}get customer(){return this._customer}get isTokenizedOrder(){return this._order.isTokenizationEnabled??!1}get subscriptionData(){return this.order.subscriptionData}async addCustomerInformation(e){e.phone?.number&&["+46","46"].includes(e.phone.countryCode)&&(e.phone.number=e.phone.number.padStart(10,"0")),e.billingAddress&&(e.billingAddress.postalCode=e.billingAddress.postalCode?.replace(/[^a-zA-Z0-9]/g,"")),e.shippingAddress&&(e.shippingAddress.postalCode=e.shippingAddress.postalCode?.replace(/[^a-zA-Z0-9]/g,""));let r=await ie.cR(e);if(r.code)return m({type:"ERROR_ADDING_CUSTOMER_INFO",data:{log:"Falied to add customer details",data:r.message,orderId:this.order.orderId}}),F(r.code);let n=await r.data();if(n.status!=="SUCCESS"||n.data?.customer_details?.status!=="SUCCESS")return m({type:"ERROR_ADDING_CUSTOMER_INFO",data:{log:"Falied to add customer details",data:JSON.stringify(e),orderId:this.order.orderId}}),F("ON_008");fe("UPDATED_CUSTOMER_INFORMATION"),this._customer=Ze({phone:e.phone||this._customer?.phone,email:e.email||this._customer?.email,name:e.name||this._customer?.name,billingAddress:e.billingAddress||this._customer?.billingAddress,shippingAddress:e.shippingAddress||this._customer?.shippingAddress})}getApplicablePaymentMethods(){let e=this.paymentMethods.lockToPaymentMethods?this.paymentMethods.lockToPaymentMethods:this.paymentMethods.supportedPaymentMethods,r=e.indexOf("ACCTOACC"),n=r>-1,i=Va[this.order.totalOrderPriceCurrency]&&this._order.amount.totalAmountToBePaid<Va[this.order.totalOrderPriceCurrency];return n&&i&&e.splice(r,1),e}async initiatePayments(e,r={}){try{if(this.errorState===!0)throw m({type:"ERROR",data:{log:"Link is not ready for payment processing"}}),new Error("This link is not ready for payment processing");let n=p=>{this._pA=p},s={APPLE_PAY:"CARD",GOOGLE_PAY:"CARD"}[e]??e;if(m({type:"INFO_PAYMENT_METHODS",data:{supportedPaymentMethods:JSON.stringify(this.paymentMethods.supportedPaymentMethods),lockToPaymentMethods:JSON.stringify(this.paymentMethods.lockToPaymentMethods),selectedPaymentMethod:s,orderId:this.order.orderId}}),!this.paymentMethods.supportedPaymentMethods.includes(s)||this.paymentMethods.lockToPaymentMethods&&!this.paymentMethods.lockToPaymentMethods?.includes(s))return fe("NO_MATCHING_PAYMENT_METHODS_FOUND"),F("ON_010");if(this.order.orderStatus!=="PENDING")return fe("ORDER_NOT_PENDING"),F("ON_011");switch(e){case"CARD":let p=Ps();if($n(`${p.card}`)){let Xe="ONL_0041",Mt=await Ne.getStringValue(Xe);m({type:"ERROR_BLOCKED_CARD",data:{log:"Detected bin blocked card",data:{errorCode:Xe,errorMessage:Mt},orderId:this.order.orderId}})}if(g.STORED_CARD_FORM=await Vo(JSON.stringify(p)),Ce.getValidity()!==!0)return m({paymentId:this._pA?.paymentId,data:{fieldErrors:Ce.frameExternalObject(),orderId:this.order.orderId},type:"CARD_FIELD_VALIDATION"}),F("ON_016");if(!this._customer)return F("ON_017");if(!this._customer?.phone||!this._customer?.phone.number)return F("ON_009");if(!this._customer?.email)return F("ON_017");if(!this._customer?.billingAddress)return F("ON_018");try{Cs();let Xe=await ie.iR(e);if(Xe.code)return Xe;let Mt=await Xe.data();if(Mt.status==="ERROR"||Mt.data.status==="ERROR")return F("ON_012");let ot=Mt.data.paymentId,Rr=this.frameCardPaymentRequest(p);m({type:"CARD_PAYMENT_INITIATED",data:{orderId:this.order.orderId},paymentId:ot}),m({type:"DATA_COLLECTOR_AFTER_PAYMENT_INITIATION",data:{orderId:this.order.orderId,...Ye()},paymentId:ot});let Ot=await(await Lt(this,()=>ie.aR(ot,this.order.terminalId,Rr))).data(),xt=new xe(ot);if(n(xt),["THREE_DS_AUTH","CHALLENGE"].includes(Ot.step)){let et=new vr;m({type:"THREE_DS_AUTH_REQUESTED",data:{orderId:this.order.orderId},paymentId:ot});let Lr=await et.handlerThreeDs(Ot,{paymentId:ot,orderId:this.order.orderId,terminalId:this.order.terminalId},this);if(et.remove3DSModel(),["ERROR","PAYMENT_STATUS"].includes(Lr.step)&&(Or(),Lr.step==="ERROR"))return F("ON_019")}else if(Ot.step==="ERROR"){m({type:"CARD_PAYMENT_INITIATION_FAILED",data:{paymentRequestData:Ot,orderId:this.order.orderId},paymentId:ot}),Or();let et=Ot.data;return F((et?.errorCodes??et.errorCodes)[0]??"ON_016")}return xt}catch(Xe){return Or(),m({type:"PAYMENT_INITIATION_FAILED",data:{errorMessage:Xe.message,orderId:this.order.orderId}}),F("ON_013")}case"APPLE_PAY":return await Us(n);case"GOOGLE_PAY":return await js(this,n);case"ACCTOACC":if(!r.bic||!Qs(r.bic))return fe("ACCTOACC_INITIATION_FAILED",{log:"BIC required",orderId:this.order.orderId}),{code:"ON_012",message:"An error occurred while initiating payments. Please try again"};let h=await ie.iR(e,{bic:r.bic});if(h.code)return h;let b=await h.data();if(!b||!b.status||b.status==="ERROR"||b.data.status==="ERROR")return g.ERROR_CALLBACK("ON_012","An error occurred while initiating payments. Please try again"),fe("ACCTOACC_FAILED",{log:"An error occurred while initiating payments. Please try again",orderId:this.order.orderId}),{code:"ON_012",message:"An error occurred while initiating payments. Please try again"};let x=b.data.paymentUrl,R=b.data.paymentId;fe("DATA_COLLECTOR_AFTER_ACCTOACC_INITIATION",{orderId:this.order.orderId,...Ye(),url:x});let K=new xe(R,{paymentMethod:"ACCTOACC"});return Js(K,x),n(K),K;case"SSWISH":if(!this._customer?.phone||!this._customer?.phone.number)return F("ON_009");let V=await ie.iR(e);if(V.code)return V;let H=await V.data();if(!H||!H.status||H.status==="ERROR"||H.data.status==="ERROR")return g.ERROR_CALLBACK("ON_012","An error occurred while initiating payments. Please try again"),m({type:"SSWISH_FAILED",data:{log:"An error occurred while initiating payments. Please try again",orderId:this.order.orderId}}),{code:"ON_012",message:"An error occurred while initiating payments. Please try again"};let le=H.data.paymentId;m({type:"SSWISH_INITIATED",data:{orderId:this.order.orderId},paymentId:le}),m({type:"DATA_COLLECTOR_AFTER_SWISH_INITIATION",data:{orderId:this.order.orderId,...Ye()},paymentId:le});let me=new xe(le);return n(me),me;case"NSWISH":let Ae=await ie.iR(e);if(Ae.code)return Ae;let Ie=await Ae.data();if(!Ie||!Ie.status||Ie.status==="ERROR"||Ie.data.status==="ERROR")return g.ERROR_CALLBACK("ON_012","An error occurred while initiating payments. Please try again"),m({type:"NSWISH_FAILED",data:{log:"An error occurred while initiating payments. Please try again",orderId:this.order.orderId}}),{code:"ON_012",message:"An error occurred while initiating payments. Please try again"};let Pr=Ie.data.paymentId;m({type:"NSWISH_INITIATED",data:{orderId:this.order.orderId},paymentId:Pr}),m({type:"DATA_COLLECTOR_AFTER_NSWISH_INITIATION",data:{orderId:this.order.orderId,...Ye()},paymentId:Pr});let Vt=new xe(Pr,{nswishPaymentToken:Ie.data.paymentToken,nswishQRDataUrl:Ie.data.qrData});return n(Vt),Vt;case"CTOKEN":break;case"SVIPPS":case"SMOBILEPAY":if(!Cr.isInitialized())return g.ERROR_CALLBACK("ONL_0042",`Svea ${e} payment initiation failed`),m({type:`SVEA_${e.toUpperCase()}_FAILED`,data:{log:`Svea ${e} payment initiation failed, either Svea mount point is not mounted or Svea is not initialized properly`,orderId:this.order.orderId}}),F("ONL_0042");let Dt=await ie.iR(e);if(Dt.code)return Dt;let $e=await Dt.data();if(!$e||!$e.status||$e.status==="ERROR"||$e.data.status==="ERROR")return g.ERROR_CALLBACK("ON_012","An error occurred while initiating payments. Please try again"),m({type:`SVEA_${e.toUpperCase()}_FAILED`,data:{log:"An error occurred while initiating payments. Please try again",orderId:this.order.orderId}}),{code:"ON_012",message:"An error occurred while initiating payments. Please try again"};let Gt=$e.data.paymentId,on=$e.data.sveaInitiationParams;m({type:`SVEA_${e.toUpperCase()}_INITIATED`,data:{orderId:this.order.orderId},paymentId:Gt}),m({type:"DATA_COLLECTOR_AFTER_SWISH_INITIATION",data:{orderId:this.order.orderId,...Ye()},paymentId:Gt});let wr=new xe(Gt);return Cr.initiateSvea(Gt,on,e),n(wr),wr;case"KLARNA":if(!this._customer?.name)return F("ONL_0034");let ar=this._customer?.name.split(" ");if(ar?.length<2)return F("ONL_0035");if(`${ar?.pop()}`.length<2)return F("ONL_0036");if(!this._customer?.email)return F("ON_017");if(!this._customer?.billingAddress)return F("ON_018");if(!this._customer?.phone)return F("ON_009");let kt=await nr.initializePayment(this._customer,this.order.metaData?.extraMerchantData);return kt instanceof xe&&n(kt),kt}return F("ON_013")}catch(n){return console.error(n),m({type:"PAYMENT_INITIATION_FAILED",data:{errorMessage:n.message,orderId:this.order.orderId}}),F("ON_013")}}getReceiptInformation(){return null}frameCardPaymentRequest(e){let r=this.customer?.billingAddress,n=Ye(),i=`${e.expiryDate}`.replace("/","");return{billingAddress:{city:r?.city||"",country:r?.countryCode||"",line1:r?.addressLine1||"",zipCode:r?.postalCode||"",line2:r?.addressLine2||"",line3:r?.addressLine3||""},browser:{browserTZ:n.browserTZ,colorDepth:"32",javaEnabled:n.isJavaEnabled,jsEnabled:!0,language:n.language,screenHeight:n.screenHeight,screenWidth:n.screenWidth,userAgent:n.userAgent},cardholderName:e.name,email:this.customer?.email||"",expiry:{month:i.substring(0,2),year:i.substring(2,4)},mobile:{countryCode:this._customer?.phone?.countryCode,number:this._customer?.phone?.number},pan:e.card.replace(/\D/g,""),securityCode:e.cvc?.toString()}}};var td=t=>{let e=t.target,r=e.selectionStart,n=e.value.replace(/\D/g,""),i=n.slice(0,2),s=n.slice(2,4);if(i){let h=parseInt(i,10);h<1&&i.length>1?i="01":h>12&&(i="12")}if(s.length>1){let h=new Date().getFullYear()%100;parseInt(s,10)<h&&(s=h.toString())}let p=i;n.length>2&&(p+="/"+s),e.value=p,r===3&&t.data!=="/"&&n.length>2&&r++,e.setSelectionRange(r,r)},fu=t=>(t=t.replace(/\s+/g,""),/^4[0-9]{12}(?:[0-9]{3}){0,2}$/.test(t)?"visa":/^5[1-5][0-9]{14}$/.test(t)?"mastercard":/^3[47][0-9]{13}$/.test(t)?"amex":/^3(?:0[0-5]|[68][0-9])[0-9]{11}$/.test(t)?"diners":/^6(?:011|5[0-9]{2})[0-9]{12}$/.test(t)?"discover":/^(?:2131|1800|35\d{3})\d{11}$/.test(t)?"jcb":""),rd=t=>{let e=t.target,r=e.selectionStart,n=document.activeElement===e,s=e.value.replace(/\D/g,"").slice(0,19).match(/.{1,4}/g)?.join(" ")??"",p=fu(s),h=document.getElementById("sb-label_card");if(p){let b=document.createElement("img");b.id="sb-card-identifier-img",b.src=`https://content.surfboardpayments.com/hubfs/cards/${p}.svg`,b.width=40,b.height=47,b.setAttribute("style","position: absolute;right: 1rem;top: 50%;transform: translateY(-50%);"),h?.appendChild(b)}else{let b=document.getElementById("sb-card-identifier-img");b&&b.remove()}if(e.value=s,n&&r!=null){let b=s.slice(0,r).match(/ /g)?.length||0,x=r+b;e.setSelectionRange(x,x)}};var Wa=class{cardValidationListeners=[];cvvValidationListeners=[];expiryValidationListeners=[];nameValidationListeners=[];onCardValidation(e){this.cardValidationListeners.push(e)}onCVVValidation(e){this.cvvValidationListeners.push(e)}onExpiryValidation(e){this.expiryValidationListeners.push(e)}onNameValidation(e){this.nameValidationListeners.push(e)}emitCardValidation(e,r,n){this.cardValidationListeners.forEach(i=>{try{i(e,n)}catch(s){console.error("Error in card validation listener:",s)}})}emitCVVValidation(e,r,n){this.cvvValidationListeners.forEach(i=>{try{i(e,n)}catch(s){console.error("Error in CVV validation listener:",s)}})}emitNameValidation(e,r,n){this.nameValidationListeners.forEach(i=>{try{i(e,n)}catch(s){console.error("Error in CVV validation listener:",s)}})}emitExpiryValidation(e,r,n){this.expiryValidationListeners.forEach(i=>{try{i(e,n)}catch(s){console.error("Error in expiry validation listener:",s)}})}},He=new Wa;function rn(t,e){let r=null;return function(...i){r&&clearTimeout(r),r=setTimeout(()=>{t(...i).catch(console.error),r=null},e)}}async function sa(t){let r=he().ge(`sb-error-${t}`);r&&(r.innerText="")}var Ge=he(),hu="sb-py-3 sb-font-normal sb-px-4 sb-rounded-outer sb-border sb-border-primary sb-border-opacity-10 sb-bg-primary sb-bg-opacity-10 sb-w-full sb-text-base",yu=[],mu=rn(async t=>{try{let e=t.value.replace(/\s/g,""),r=zn(e);if(r){let n=await Ne.getStringValue(r);Ce.addError("name",r,n),He.emitNameValidation(!1,r,n)}else Ce.cleanErrors("name"),He.emitNameValidation(!0)}catch{He.emitNameValidation(!1,"Validation error occurred")}},350),gu=rn(async t=>{try{let e=t.value.replace(/\s/g,""),r=Gn(e);if($n(e)){let n="ONL_0041",i=await Ne.getStringValue(n);Ce.addError("card",n,i),m({type:"ERROR_BLOCKED_CARD",data:{log:`Detected bin blocked card, error code: ${n}`,data:{errorCode:n,errorMessage:i}}}),He.emitCardValidation(!1,n,i)}else if(r){let n=await Ne.getStringValue(r);Ce.addError("card",r,n),He.emitCardValidation(!1,r,n)}else Ce.cleanErrors("card"),He.emitCardValidation(!0)}catch{He.emitCardValidation(!1,"Validation error occurred")}},350),_u=rn(async(t,e)=>{try{let r=t.value,n=jn(r,e);if(n){let i=await Ne.getStringValue(n);Ce.addError("cvc",n,i),He.emitCVVValidation(!1,n,i)}else Ce.cleanErrors("cvc"),He.emitCVVValidation(!0)}catch{He.emitCVVValidation(!1,"Validation error occurred")}},350),Eu=rn(async t=>{try{let e=qn(t.value);if(e){let r=await Ne.getStringValue(e);Ce.addError("expiryDate",e,r),He.emitExpiryValidation(!1,e,r)}else Ce.cleanErrors("expiryDate"),He.emitExpiryValidation(!0)}catch{He.emitExpiryValidation(!1,"Validation error occurred")}},350),bu={card:{type:"text",fieldLabel:"card.number",pattern:"\\d{4} \\d{4} \\d{4} \\d{4}( \\d{3})?",minLength:"12",maxLength:"19",placeholder:"card.number",required:!0,autocomplete:"cc-number",fixedStyles:{position:"relative"},listeners:{input:t=>{rd(t),sa("card");let e=t.target;gu(e)},focus:()=>{m({type:"INPUT_EVENTS",data:{message:"User started entering in card field",field:"CARD"}});let t=Ge.ge("sb-card-elements");t&&(t.style.display="flex");let e=Ge.ge(`sb-card_${g.FIELD_NONCE}`);e&&e.classList.add("sb-rounded-b-none")},blur:()=>{m({type:"INPUT_EVENTS",data:{message:"User left the card field",field:"CARD"}})}},includeErrors:!0,inputMode:"numeric"},cvc:{type:"text",additionalClassNames:"sb-rounded-t-none sb-rounded-l-none sb-border-t-0 sb-border-l-0 cvc sb-border-b-0",fieldLabel:"card.cvv",minLength:"3",maxLength:"4",placeholder:"card.cvv",required:!0,pattern:"\\d{3,4}",includeErrors:!0,inputMode:"numeric",listeners:{input:t=>{sa("cvc");let e=t.target,r=Ge.ge(`sb-card_${g.FIELD_NONCE}`),n=r?Ka(r.value.replace(/\s/g,"")):void 0;_u(e,n)},focus:()=>{m({type:"INPUT_EVENTS",data:{message:"User started entering in CVC field",field:"CVC"}})},blur:()=>{m({type:"INPUT_EVENTS",data:{message:"User left CVC field",field:"CVC"}})}}},expiryDate:{type:"text",fieldLabel:"",minLength:"4",maxLength:"5",placeholder:"card.expiry",additionalClassNames:"sb-rounded-t-none sb-rounded-r-none sb-border-t-0 sb-border-b-0",required:!0,autocomplete:"cc-exp",pattern:"(0[1-9]|1[0-2])\\/[0-9]{2}",inputMode:"numeric",includeErrors:!0,listeners:{input:t=>{td(t),sa("expiryDate");let e=t.target;Eu(e)},focus:()=>{m({type:"INPUT_EVENTS",data:{message:"User started entering in Expiry Date field",field:"EXPIRY-DATE"}})},blur:()=>{m({type:"INPUT_EVENTS",data:{message:"User left Expiry Date field",field:"EXPIRY-DATE"}})}}},name:{type:"text",fieldLabel:"card.name",minLength:"3",maxLength:"50",placeholder:"card.name",required:!0,autocomplete:"cc-name",additionalClassNames:"sb-border-b-0",includeErrors:!0,inputMode:"text",listeners:{input:t=>{sa("name");let e=t.target;mu(e)},focus:()=>{m({type:"INPUT_EVENTS",data:{message:"User started entering in Name field",field:"NAME"}})},blur:()=>{m({type:"INPUT_EVENTS",data:{message:"User left Name field",field:"NAME"}})}}},storeInformation:{type:"checkbox",fieldLabel:"card.store",additionalClassNames:"sb-border-b-0",minLength:"1",maxLength:"1",subLabel:"card.store.detail",includeErrors:!0}};function nd(t){let e=Ge.ge(t),r=Ge.ce("div");e?.appendChild(r),r.setAttribute("id","sb-section--wrapper-card-details"),r.setAttribute("class","sb-wrapper"),Su(r),setTimeout(()=>Tu(),100)}async function Tu(){if(!(!g.STORED_CARD_FORM||g.STORED_CARD_FORM===null))try{let t=await Go(g.STORED_CARD_FORM),e=JSON.parse(t);["name","card","expiryDate"].forEach(n=>{let i=`sb-${n}_${g.FIELD_NONCE}`,s=Ge.ge(i);if(!s)return;let p=e[n];if(typeof p=="string"&&p.length<=100){let h=p.replace(/<[^>]*>/g,"").trim();s.value=h}}),g.STORED_CARD_FORM=null}catch{return}}function da(t){let e=Ge.ce(we.d),r=bu[t],n=r.fixedStyles;n&&Object.keys(n).forEach(h=>{e.style[h]=n[h]}),e.classList.add("sb-w-full"),e.classList.add(`sb-field-${t}`),e.id=`sb-field-wrapper-${t}`;let i=Ge.ce("label");i.id=`sb-label_${t}`,i.classList.add("sb-w-full"),i.classList.add("sb-relative"),i.classList.add(`sb-field-label-${t}`);let s=Ge.ce(we.i);if(s.id=`sb-${t}_${g.FIELD_NONCE}`,r.pattern&&(s.pattern=r.pattern),s.type=r.type,r.placeholder&&(s.placeholder=r.placeholder,Ne.registerPlaceHolderNodes(s,r.placeholder)),s.autocomplete=r.autocomplete,s.required=r.required??!1,r.inputMode&&(s.inputMode=r.inputMode),s.className=`${hu} ${r.additionalClassNames?r.additionalClassNames:""}`,s.autocorrect="off",r.minLength&&(s.minLength=parseInt(r.minLength)),r.maxLength&&(s.maxLength=parseInt(r.maxLength)),r.includeErrors===!0){let h=Ge.ce(we.p);h.setAttribute("id",`sb-error-${t}`),h.classList.add("sb-field--error"),h.classList.add(`error-${t}`),i.appendChild(s),e.appendChild(i),e.appendChild(h)}let p=r.listeners??{};return Object.keys(p).forEach(h=>{let b=p[h];s.addEventListener(h,b),yu.push({element:s,event:h,handler:b})}),Ce.registerField(t),e}function Su(t){let e=Ge.ce(we.f);e.setAttribute("style","display:flex;flex-direction:column;padding-left:8px; padding-right:8px"),e.id=`sb-card-details-form-${g.FIELD_NONCE}`;let r=da("card"),n=Ge.ce(we.d);n.id="sb-card-elements",n.classList.add("sb-w-full"),n.setAttribute("style","display:none;flex-direction:row;");let i=da("expiryDate"),s=da("cvc"),p=da("name");n.appendChild(i),n.appendChild(s),e.appendChild(r),e.appendChild(n);let h=Ge.ce(we.d);h.setAttribute("style","margin-top:8px;margin-bottom:8px"),h.appendChild(p),e.appendChild(h),t.appendChild(e),Au()}function Au(){At.getInstance().initialize({id:"sb-modal-challenge",showCloseButton:!1,backdropBlur:!0,defaultBranding:{backgroundColor:"#FFFFFF",fontFamily:"system-ui, -apple-system, sans-serif",primaryColor:"#000000"}});let e=Ge.ce(we.d);e.className="sb-flex sb-flex-col sb-bg-opacity-100 sb-bg-white sb-modal-challenge-content",e.id="sb-modal-challenge-content"}function ad(t){let e=Ge.de;e.style.setProperty("--bgColor",t?.backgroundColor),e.style.setProperty("--brandColor",t?.brandColor),e.style.setProperty("--accentColor",t?.accentColor),t?.fontType==="mono"?(e.style.setProperty("--fontTypeHeadline","IBM Plex Mono, monospace"),e.style.setProperty("--fontTypeBody","IBM Plex Mono, monospace")):t?.fontType==="serif"?(e.style.setProperty("--fontTypeHeadline","IBM Plex Serif, sans-serif"),e.style.setProperty("--fontTypeBody","IBM Plex Serif, serif")):(e.style.setProperty("--fontTypeHeadline","REM, sans-serif"),e.style.setProperty("--fontTypeBody","IBM Plex Sans, sans-serif")),t?.rectShape.toLowerCase()==="edgy"?(e.style.setProperty("--rectShape","0rem"),e.style.setProperty("--buttonShape","0rem")):t?.rectShape.toLowerCase()==="pill"?(e.style.setProperty("--rectShape",".5rem"),e.style.setProperty("--buttonShape","200rem")):(e.style.setProperty("--rectShape",".5rem"),e.style.setProperty("--buttonShape",".5rem"))}function id(){let t=document.createElement("style");t.type="text/css",t.appendChild(document.createTextNode(".sb-wrapper{font-family:var(--fontTypeBody);margin:0;padding:0}.sb-wrapper .sb-rounded-outer{border-radius:var(--rectShape)}.sb-wrapper .sb-rounded-l-none,.sb-wrapper .sb-rounded-t-none,.sb-wrapper .sb-rounded-tl-none{border-top-left-radius:0}.sb-wrapper .sb-rounded-r-none,.sb-wrapper .sb-rounded-tr-none{border-top-right-radius:0}.sb-wrapper .sb-rounded-b-none,.sb-wrapper .sb-rounded-br-none{border-bottom-right-radius:0}.sb-wrapper .sb-rounded-bl-none{border-bottom-left-radius:0}.sb-wrapper .sb-bg-backdrop{background-color:var(--bgColor);background-color:rgb(from var(--bgColor) r g b / var(--tw-bg-opacity));background-color:rgba(var(--bgColor),var(--tw-bg-opacity))}.sb-wrapper .sb-rounded-button{border-radius:var(--buttonShape)}.sb-wrapper .sb-bg-primary{background-color:var(--brandColor);background-color:rgb(from var(--brandColor) r g b / var(--tw-bg-opacity));background-color:rgba(var(--brandColorRgb),var(--tw-bg-opacity))}.sb-wrapper .sb-bg-accent{background-color:var(--accentColor);background-color:rgb(from var(--accentColor) r g b / var(--tw-bg-opacity));background-color:rgba(var(--accentColorRgb),var(--tw-bg-opacity))}.sb-wrapper .sb-border-primary{border-color:var(--brandColor);border-color:rgb(from var(--brandColor) r g b / var(--tw-border-opacity));border-color:rgba(var(--brandColorRgb),var(--tw-border-opacity))}.sb-wrapper .sb-border-accent{border-color:var(--accentColor);border-color:rgb(from var(--accentColor) r g b / var(--tw-border-opacity));border-color:rgba(var(--accentColorRgb),var(--tw-border-opacity))}.sb-wrapper .sb-text-white{color:#fff}.sb-wrapper .sb-relative{position:relative}.sb-wrapper .sb-fixed{position:fixed}.sb-wrapper .sb-flex{display:flex}.sb-wrapper .sb-block{display:block}.sb-wrapper .sb-flex-col{flex-direction:column}.sb-wrapper .sb-flex-row{flex-direction:row}.sb-wrapper .sb-flex-1{flex:1 1 0%}.sb-wrapper .sb-px-1{padding-left:.25rem;padding-right:.25rem}.sb-wrapper .sb-gap-4{gap:1rem}.sb-wrapper .sb-font-bold{font-weight:800}.sb-wrapper .sb-font-semibold{font-weight:600}.sb-wrapper .sb-text-sm{font-size:.875rem;line-height:1.25rem}.sb-wrapper .sb-text-xs{font-size:.75rem;line-height:1rem}.sb-wrapper .sb-mb-1{margin-bottom:.25rem}.sb-wrapper .sb-mb-2{margin-bottom:.5rem}.sb-wrapper .sb-mt-1{margin-top:.25rem}.sb-wrapper .sb-mt-2{margin-top:.5rem}.sb-wrapper .sb-w-full{width:100%}.sb-wrapper .sb-bg-white{--tw-bg-opacity:1;background-color:rgb(255 255 255 / 1);background-color:rgb(255 255 255 / var(--tw-bg-opacity));background-color:rgba(255,255,255,var(--tw-bg-opacity))}.sb-wrapper .sb-py-3{padding-top:.75rem;padding-bottom:.75rem}.sb-wrapper .sb-py-5{padding-top:1.25rem;padding-bottom:1.25rem}.sb-wrapper .sb-px-4{padding-left:1rem;padding-right:1rem}.sb-wrapper .sb-font-normal{font-weight:400}.sb-wrapper .sb-hidden{display:none}.sb-wrapper button,.sb-wrapper input,.sb-wrapper select,.sb-wrapper textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;color:inherit;margin:0;padding:0;border:0;transition:75ms}.sb-wrapper .sb-border-l{border-left-width:1px;border-left-style:solid}.sb-wrapper .sb-border-t{border-top-width:1px;border-top-style:solid}.sb-wrapper .sb-border-r{border-right-width:1px;border-right-style:solid}.sb-wrapper .sb-border-b{border-bottom-width:1px;border-bottom-style:solid}.sb-wrapper .sb-border{border-width:1px;border-style:solid}.sb-wrapper .sb-bg-opacity-10{--tw-bg-opacity:0.1}.sb-wrapper .sb-bg-opacity-20{--tw-bg-opacity:0.2}.sb-wrapper .sb-bg-opacity-30{--tw-bg-opacity:0.3}.sb-wrapper .sb-bg-opacity-50,.sb-wrapper .sb-hover:bg-opacity-50:hover{--tw-bg-opacity:0.5}.sb-wrapper .sb-bg-opacity-100{--tw-bg-opacity:1}.sb-wrapper .sb-bg-opacity-90{--tw-bg-opacity:0.9}.sb-wrapper .sb-border-opacity-10{--tw-border-opacity:0.1}.sb-wrapper .sb-border-opacity-20{--tw-border-opacity:0.2}.sb-wrapper .sb-border-opacity-30{--tw-border-opacity:0.3}.sb-wrapper .sb-border-opacity-50{--tw-border-opacity:0.5}.sb-wrapper .sb-border-opacity-100{--tw-border-opacity:1}.sb-wrapper .sb-items-center{align-items:center}.sb-wrapper .sb-justify-center{justify-content:center}.sb-wrapper .sb-w-screen{width:100vw}.sb-wrapper .sb-h-screen{height:100vh}.sb-wrapper .sb-h-full{height:100%}.sb-wrapper .sb-gray{filter:grayscale(1) brightness(3)}.sb-wrapper .sb-loader{width:48px;height:48px;display:inline-block;position:relative}.sb-wrapper .sb-loader::after,.sb-wrapper .sb-loader::before{content:'';box-sizing:border-box;width:48px;height:48px;border-radius:50%;border:2px solid #0e44e1;position:absolute;left:0;top:0;animation:2s linear infinite sb-animloader}.sb-wrapper .sb-loader::after{animation-delay:1s}@keyframes sb-animloader{0%{transform:scale(0);opacity:1}100%{transform:scale(1);opacity:0}}.sb-wrapper .sb-border-t-0{border-top:0}.sb-wrapper .sb-border-r-0{border-right:0}.sb-wrapper .sb-border-b-0{border-bottom:0}.sb-wrapper .sb-border-l-0{border-left:0}.sb-wrapper .sb-field--error{color:red;font-size:12px}.sb-wrapper .sb-text-base{font-size:1rem;line-height:1.5rem}.sb-wrapper .sb-modal-challenge-content{width:800px;height:500px;z-index:20}@media (max-width:640px){.sb-wrapper .sb-klarna-container{width:100%;height:100%;max-width:100%;max-height:100%}.sb-wrapper .modal-center{display:block}.sb-wrapper .sb-modal-challenge-content{width:100%;height:100%;z-index:20}}.sb-wrapper .sb-klarna-go-back-button,.sb-wrapper .sb-klarna-proceed-button{height:40px;font-size:18px;font-weight:200;cursor:pointer}.sb-wrapper .sb-klarna-bottom-section{display:flex;flex-direction:row;padding:10px;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:16px;margin-top:16px;max-width:600px;margin-left:auto;margin-right:auto;width:100%}@media (min-width:1024px){.sb-wrapper .sb-klarna-go-back-button,.sb-wrapper .sb-klarna-proceed-button{max-width:200px}}.sb-wrapper .sb-klarna-go-back-button{border-radius:10px;background-color:rgba(11,5,29,.1);border:none;color:#0b051d}.sb-wrapper .sb-klarna-proceed-button{border-radius:10px;background-color:#0b051d;border:none;color:#fff;box-shadow:4px 6px rgba(0,0,0,.1)}.sb-wrapper .sb-klarna-widget-div{width:100%;height:full;margin-top:30px;display:flex;justify-content:center}.sb-wrapper .sb-klarna-logo-image{margin:20px auto;width:80px;height:50px}.sb-wrapper .sb-klarna-container{width:800px;display:flex;flex-direction:column;position:relative;height:400px}")),document.getElementsByTagName("head")[0].appendChild(t)}function od(t){fe("MOUNT_CALLED"),g.MOUNT_POINTS=t,sd(t)}function sd(t){t.mountCardWidget&&nd(t.mountCardWidget),t.mountApplePayWidget&&qa(t.mountApplePayWidget),t.mountGooglePayWidget&&za(t.mountGooglePayWidget),nr.mountKlarna()}async function Ja(t){let e=he().ge(t.mountApplePayWidget);e&&la(e);let r=he().ge(t.mountGooglePayWidget);r&&(la(r),Yt.reset())}async function ed(t){fe("REMOUNT_CALLED");let e=he().ge(t.mountCardWidget);e&&la(e),Ja(t),sd(t);let r=window.SurfboardOnlineSDK.order;if(r&&r.getPaymentAttempt()&&(await r.fetchOrderInternal(),r.getApplicablePaymentMethods().includes("CARD")||r.getApplicablePaymentMethods().includes("CTOKEN")))try{fe("SECURE_INITIALISATION_RESTARTED"),jr(),await Er(g._PUBLIC_KEY,g._ORDERID,3)}catch{throw fe("SECURE_INITIALISATION_RESTART_FAILED"),new Ht("Surfboard SDK initialisation failed - Secure Channel")}}function dd(t,e){fe("ALL_WIDGETS_REMOVED"),t.forEach(r=>{if(e[r]){let n=he().ge(e[r]);la(n)}})}function la(t){for(;t.firstChild;)t.removeChild(t.firstChild)}function Ou(){}function xu(){}async function Iu(t,e){return await ld.Client.RSA.encrypt(e,t)}var nn=class{constructor(){}_API_URL="https://gw2.surfgw.com";_AGW_URL="https://tg2.pcisurf.com";_CAMOUFLAGE_URL="https://camouflage.surfgw.com";_PI_URLS=[];_FORM_NONCE="Zdv11rNW1ZMk";_IS_INITIALISED="";_ORDERID="";_TERMINALID="";_NONCE="";_ERROR_CALLBACK=null;_PAYMENT_STATUS_CALLBACK=null;_CURRENT_DOMAIN="";_TOP_DOMAIN="";_SDK_UI_MOUNT="";_SDK_LANGUAGE="en";_PUBLIC_KEY="";_KLARNA_MOUNT_POINT="";_MONOTONIC_START_TIME=0;_MONOTONIC_CLIENT_ID="";_STORED_CARD_FORM=null;mountPoints=null;terminalCallbacks=[];asyncThrottle=new Fn({maxThreshold:3,delayExecutions:1e3});get throttle(){return this.asyncThrottle}get PUBLIC_KEY(){return this._PUBLIC_KEY}set PUBLIC_KEY(e){if(!this._PUBLIC_KEY||this._PUBLIC_KEY==="")this._PUBLIC_KEY=e;else throw new ve("Constant Value cannot be reassigned after initialisation")}get MONOTONIC_START_TIME(){return this._MONOTONIC_START_TIME}set MONOTONIC_START_TIME(e){if(!this._MONOTONIC_START_TIME||this._MONOTONIC_START_TIME===0)this._MONOTONIC_START_TIME=e;else throw new ve("Monotonic start time cannot be reassigned after initialisation")}get MONOTONIC_CLIENT_ID(){return this._MONOTONIC_CLIENT_ID}set MONOTONIC_CLIENT_ID(e){if(!this._MONOTONIC_CLIENT_ID||this._MONOTONIC_CLIENT_ID==="")this._MONOTONIC_CLIENT_ID=e;else throw new ve("Monotonic client ID cannot be reassigned after initialisation")}get KLARNA_MOUNT_POINT(){return this._KLARNA_MOUNT_POINT}set KLARNA_MOUNT_POINT(e){this._KLARNA_MOUNT_POINT=e}get TERMINAL_PAYMENT_STATUSES(){return["PAYMENT_COMPLETED","PAYMENT_CANCELLED","PAYMENT_FAILED"]}get MAXIMUM_CHECKS(){return 700}get CAMOUFLAGE_URL(){return this._CAMOUFLAGE_URL}set API_URL(e){if(!this._API_URL||this._API_URL==="")this._API_URL=e;else throw new ve("Constant Value cannot be reassigned after initialisation")}get API_URL(){return this._API_URL}set AGW_URL(e){if(!this._AGW_URL||this._AGW_URL==="")this._AGW_URL=e;else throw new ve("Constant Value cannot be reassigned after initialisation")}get AGW_URL(){return this._AGW_URL}set IS_INITIALISED(e){if(!this._IS_INITIALISED||this._IS_INITIALISED==="")this._IS_INITIALISED=e;else throw new ve("Constant Value cannot be reassigned after initialisation")}get IS_INITIALISED(){return this._IS_INITIALISED}set ORDER_ID(e){if(!this._ORDERID||this._ORDERID==="")this._ORDERID=e;else throw new ve("You are attempting to modify the orderId")}set TERMINAL_ID(e){if(!this._TERMINALID||this._TERMINALID==="")this._TERMINALID=e;else throw new ve("You are attempting to modify the orderId")}get TERMINAL_ID(){return this._TERMINALID}get ORDER_ID(){return this._ORDERID}set NONCE(e){if(!this._NONCE||this._NONCE==="")this._NONCE=e;else throw new ve("You are attempting to modify the nonce")}set PI_URLS(e){if(!this._PI_URLS||this._PI_URLS.length===0)this._PI_URLS=e;else throw new ve("You are attempting to modify the pi urls")}get PI_URLS(){return this._PI_URLS}get NONCE(){return this._NONCE}set ERROR_CALLBACK(e){if(!this._ERROR_CALLBACK)this._ERROR_CALLBACK=e;else throw new ve("You are attempting to modify the change function")}get ERROR_CALLBACK(){return this._ERROR_CALLBACK??Ou}set PAYMENT_STATUS_CALLBACK(e){if(!this._PAYMENT_STATUS_CALLBACK)this._PAYMENT_STATUS_CALLBACK=e;else throw new ve("You are attempting to modify the payment status callback")}get PAYMENT_STATUS_CALLBACK(){return this._PAYMENT_STATUS_CALLBACK??xu}set CURRENT_DOMAIN(e){if(!this._CURRENT_DOMAIN||this._CURRENT_DOMAIN==="")this._CURRENT_DOMAIN=e;else throw new ve("You are attempting to modify the current domain")}set MOUNT_POINTS(e){e&&this.mountPoints&&dd(Object.keys(e),this.mountPoints),this.mountPoints=e}get CURRENT_DOMAIN(){return this._CURRENT_DOMAIN}set TOP_DOMAIN(e){if(!this._TOP_DOMAIN||this._TOP_DOMAIN==="")this._TOP_DOMAIN=e;else throw new ve("You are attempting to modify the Top level domain")}get TOP_DOMAIN(){return this._TOP_DOMAIN}set SDK_LANGUAGE(e){this._SDK_LANGUAGE=e}get SDK_LANGUAGE(){return this._SDK_LANGUAGE}get FIELD_NONCE(){return this._FORM_NONCE}get CHECK_PARAM(){return Iu(this._PUBLIC_KEY,`${this._CURRENT_DOMAIN}||${this._TOP_DOMAIN}`)}get MOUNT_POINTS(){return this.mountPoints}get STORED_CARD_FORM(){return this._STORED_CARD_FORM}set STORED_CARD_FORM(e){this._STORED_CARD_FORM=e}ADD_TERMINAL_CALLBACK(e){this.terminalCallbacks.push(e)}get TERMINAL_CALLBACKS(){return this.terminalCallbacks}};var Za={en:()=>Promise.resolve().then(()=>ht(cd())),sv:()=>Promise.resolve().then(()=>ht(ud())),fi:()=>Promise.resolve().then(()=>ht(pd())),da:()=>Promise.resolve().then(()=>ht(fd())),no:()=>Promise.resolve().then(()=>ht(hd()))};var an=class{TEXT_RENDER_REGISTRY=[];PLACEHOLDER_REGISTRY=[];registerPlaceHolderNodes(e,r){this.PLACEHOLDER_REGISTRY.push({inputFieldNode:e,textId:r}),this.setPlaceHolderValues()}registerAndSetDynamicLabels(e,r){this.TEXT_RENDER_REGISTRY.push({labelNode:e,labelId:r}),this.setFieldValues()}async setPlaceHolderValues(){for(let e=0;e<this.PLACEHOLDER_REGISTRY.length;e++){let r=this.PLACEHOLDER_REGISTRY[e],n=await this.getStringValue(r.textId);r.inputFieldNode.placeholder=n}}async setFieldValues(){for(let e=0;e<this.TEXT_RENDER_REGISTRY.length;e++){let r=this.TEXT_RENDER_REGISTRY[e],n=await this.getStringValue(r.labelId);r.labelNode&&(r.labelNode.innerText=n)}}async getStringValue(e){let r=g.SDK_LANGUAGE;return Object.keys(Za).includes(r)||(r="en"),(await Za[r]()).default[e]??""}changeLanguage(e){g.SDK_LANGUAGE=e,this.setFieldValues(),this.setPlaceHolderValues(),g.MOUNT_POINTS&&Ja(g.MOUNT_POINTS)}};var Qa=class{_instance;constructor(){return this._instance=new nn,new Proxy(this,{get(e,r){return r==="resetInstance"?e.resetInstance.bind(e):e._instance[r]},set(e,r,n){return r==="_instance"?!1:e._instance[r]=n}})}resetInstance(){this._instance=new nn}},Xa=class{_instance;constructor(){return this._instance=new an,new Proxy(this,{get(e,r){return r==="resetInstance"?e.resetInstance.bind(e):e._instance[r]},set(e,r,n){return r==="_instance"?!1:e._instance[r]=n}})}resetInstance(){this._instance=new an}},g=new Qa,Ne=new Xa;function yd(){g.resetInstance(),Ne.resetInstance()}function md(){let t=window.location.host,e=window.top?.location.host;g.CURRENT_DOMAIN=t,g.TOP_DOMAIN=e}function gd(t){let{publicKey:e,orderId:r,nonce:n}=t,i=/[0-9A-Fa-f]/g;if(!e.match(i)||e.length<780||e.length>1e3)throw new Bt("Public key validation failed");return Is(r),vs(n),!0}function ca(){return!(typeof window>"u")}async function ei(t){if(!ca)throw new Zt("Surfboard SDK cannot function in the given environment");if(!t)throw new Ht("Surfboard SDK initialisation failed");md();try{gd(t)}catch(r){throw fe("INITIALISATION_VALIDATION_FAILED",{errorDescription:r,orderId:t.orderId}),r}Io(t.orderId),g.NONCE=t.nonce,g.ORDER_ID=t.orderId,g.PUBLIC_KEY=t.publicKey,g.IS_INITIALISED="TRUE";let e=new tn;if(await e.fetchOrderInternal(),g.TERMINAL_ID=e.order.terminalId,rs(),fe("ONLINE_PAGE_INITIALISED"),e.getApplicablePaymentMethods().includes("CARD")||e.getApplicablePaymentMethods().includes("CTOKEN"))try{await Er(t.publicKey,t.orderId,3),fe("SECURE_CHANNEL_INITIALISED")}catch(r){throw fe("SECURE_CHANNEL_INITIALISATION_FAILED",{errorDescription:r,orderId:t.orderId}),new Ht("Surfboard SDK initialisation failed - Secure Channel")}ea(e).then().catch(),window.SurfboardOnlineSDK.changeLocale=Ru,window.SurfboardOnlineSDK.order=e,window.SurfboardOnlineSDK.merchant=e.merchant,window.SurfboardOnlineSDK.branding=e.branding,window.SurfboardOnlineSDK.store=e.store,window.SurfboardOnlineSDK.paymentMethods=e.paymentMethods,window.SurfboardOnlineSDK.customer=e.customer,window.SurfboardOnlineSDK.saveEvents=wt,window.SurfboardOnlineSDK.PaymentAttempt=xe,window.SurfboardOnlineSDK.fieldEvents=He,window.SurfboardOnlineSDK.getMonotonicTime=Bn,window.SurfboardOnlineSDK.getMonotonicClientId=Hn,window.SurfboardOnlineSDK.getStringValue=Ne.getStringValue,window.SurfboardOnlineSDK.mount=od,window.SurfboardOnlineSDK.taskScheduler=pt,e.order.subscriptionData?window.SurfboardOnlineSDK.payButtonType="pay.subscribe":window.SurfboardOnlineSDK.payButtonType="pay.pay",id(),ad(e.branding),fe("WINDOW_FUNCTIONS_ATTACHED")}function Ru(t){Ne.changeLanguage(t)}async function _d(t){g.ERROR_CALLBACK=t}async function Ed(t){g.PAYMENT_STATUS_CALLBACK=t}async function bd(t){if(g.IS_INITIALISED!=="TRUE")throw m({data:{errorDescription:"Remount without initialisation",orderId:t.orderId},type:"REMOUND_WITHOUT_INITIALISATION"}),new Ht("Surfboard SDK initialisation failed - Remount without initialisation");yd(),await ei(t)}(function(){if(ca()){if(window.SurfboardOnlineSDK)throw new Error("Invalid instance of SurfboardOnlineSDK found");window.SurfboardOnlineSDK={initialiseOnlineSDK:ei,errorCallback:_d,paymentStatusCallback:Ed,remountOnlineSDK:bd}}})();})();
