skapi-js 1.2.14-beta.3 → 1.2.14-beta.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/dist/bundle-report-commonjs.html +2 -2
  2. package/dist/bundle-report-esm.html +2 -2
  3. package/dist/bundle-report-node-esm.html +2 -2
  4. package/dist/bundle-report.html +2 -2
  5. package/dist/skapi.cjs +1 -1
  6. package/dist/skapi.cjs.map +1 -1
  7. package/dist/skapi.js +1 -1
  8. package/dist/skapi.js.map +1 -1
  9. package/dist/skapi.mjs +1 -1
  10. package/dist/skapi.mjs.map +1 -1
  11. package/dist/skapi.node.mjs +1 -1
  12. package/dist/skapi.node.mjs.map +1 -1
  13. package/js/package.json +6 -5
  14. package/js/src/Types.d.ts +40 -2
  15. package/js/src/main/skapi.d.ts +41 -29
  16. package/js/src/main/skapi.js +48 -60
  17. package/js/src/main/skapi.js.map +1 -1
  18. package/js/src/methods/admin.d.ts +2 -4
  19. package/js/src/methods/database.d.ts +8 -0
  20. package/js/src/methods/database.js +285 -8
  21. package/js/src/methods/database.js.map +1 -1
  22. package/js/src/methods/param_restrictions.d.ts +8 -4
  23. package/js/src/methods/param_restrictions.js +72 -6
  24. package/js/src/methods/param_restrictions.js.map +1 -1
  25. package/js/src/methods/request.js +1 -1
  26. package/js/src/methods/request.js.map +1 -1
  27. package/js/src/methods/subscription.d.ts +0 -6
  28. package/js/src/methods/subscription.js +0 -28
  29. package/js/src/methods/subscription.js.map +1 -1
  30. package/js/src/methods/vivian.d.ts +18 -3
  31. package/js/src/methods/vivian.js +20 -10
  32. package/js/src/methods/vivian.js.map +1 -1
  33. package/js/src/utils/network.js +16 -11
  34. package/js/src/utils/network.js.map +1 -1
  35. package/js/src/utils/utils.d.ts +3 -1
  36. package/js/src/utils/utils.js +15 -3
  37. package/js/src/utils/utils.js.map +1 -1
  38. package/package.json +6 -5
  39. package/js/Main.d.ts +0 -6
  40. package/js/Main.js +0 -6
  41. package/js/Main.js.map +0 -1
  42. package/js/Types.d.ts +0 -305
  43. package/js/Types.js +0 -2
  44. package/js/Types.js.map +0 -1
  45. package/js/main/error.d.ts +0 -9
  46. package/js/main/error.js +0 -46
  47. package/js/main/error.js.map +0 -1
  48. package/js/main/skapi.d.ts +0 -443
  49. package/js/main/skapi.js +0 -853
  50. package/js/main/skapi.js.map +0 -1
  51. package/js/methods/admin.d.ts +0 -61
  52. package/js/methods/admin.js +0 -325
  53. package/js/methods/admin.js.map +0 -1
  54. package/js/methods/database.d.ts +0 -65
  55. package/js/methods/database.js +0 -947
  56. package/js/methods/database.js.map +0 -1
  57. package/js/methods/notification.d.ts +0 -21
  58. package/js/methods/notification.js +0 -81
  59. package/js/methods/notification.js.map +0 -1
  60. package/js/methods/param_restrictions.d.ts +0 -21
  61. package/js/methods/param_restrictions.js +0 -144
  62. package/js/methods/param_restrictions.js.map +0 -1
  63. package/js/methods/realtime.d.ts +0 -35
  64. package/js/methods/realtime.js +0 -408
  65. package/js/methods/realtime.js.map +0 -1
  66. package/js/methods/request.d.ts +0 -43
  67. package/js/methods/request.js +0 -132
  68. package/js/methods/request.js.map +0 -1
  69. package/js/methods/subscription.d.ts +0 -53
  70. package/js/methods/subscription.js +0 -337
  71. package/js/methods/subscription.js.map +0 -1
  72. package/js/methods/user.d.ts +0 -176
  73. package/js/methods/user.js +0 -1120
  74. package/js/methods/user.js.map +0 -1
  75. package/js/methods/vivian.d.ts +0 -3
  76. package/js/methods/vivian.js +0 -36
  77. package/js/methods/vivian.js.map +0 -1
  78. package/js/methods/webrtc.d.ts +0 -26
  79. package/js/methods/webrtc.js +0 -608
  80. package/js/methods/webrtc.js.map +0 -1
  81. package/js/polyfills/global.d.ts +0 -3
  82. package/js/polyfills/global.js +0 -235
  83. package/js/polyfills/global.js.map +0 -1
  84. package/js/utils/network.d.ts +0 -24
  85. package/js/utils/network.js +0 -707
  86. package/js/utils/network.js.map +0 -1
  87. package/js/utils/utils.d.ts +0 -40
  88. package/js/utils/utils.js +0 -651
  89. package/js/utils/utils.js.map +0 -1
  90. package/js/utils/validator.d.ts +0 -24
  91. package/js/utils/validator.js +0 -293
  92. package/js/utils/validator.js.map +0 -1
package/dist/skapi.js CHANGED
@@ -1,3 +1,3 @@
1
1
  /*! For license information please see skapi.js.LICENSE.txt */
2
- !function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var n=t();for(var r in n)("object"==typeof exports?exports:e)[r]=n[r]}}(self,()=>(()=>{var e={602(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RawSha256=void 0;var r=n(494),i=function(){function e(){this.state=Int32Array.from(r.INIT),this.temp=new Int32Array(64),this.buffer=new Uint8Array(64),this.bufferLength=0,this.bytesHashed=0,this.finished=!1}return e.prototype.update=function(e){if(this.finished)throw new Error("Attempted to update an already finished hash.");var t=0,n=e.byteLength;if(this.bytesHashed+=n,8*this.bytesHashed>r.MAX_HASHABLE_LENGTH)throw new Error("Cannot hash more than 2^53 - 1 bits");for(;n>0;)this.buffer[this.bufferLength++]=e[t++],n--,this.bufferLength===r.BLOCK_SIZE&&(this.hashBuffer(),this.bufferLength=0)},e.prototype.digest=function(){if(!this.finished){var e=8*this.bytesHashed,t=new DataView(this.buffer.buffer,this.buffer.byteOffset,this.buffer.byteLength),n=this.bufferLength;if(t.setUint8(this.bufferLength++,128),n%r.BLOCK_SIZE>=r.BLOCK_SIZE-8){for(var i=this.bufferLength;i<r.BLOCK_SIZE;i++)t.setUint8(i,0);this.hashBuffer(),this.bufferLength=0}for(i=this.bufferLength;i<r.BLOCK_SIZE-8;i++)t.setUint8(i,0);t.setUint32(r.BLOCK_SIZE-8,Math.floor(e/4294967296),!0),t.setUint32(r.BLOCK_SIZE-4,e),this.hashBuffer(),this.finished=!0}var s=new Uint8Array(r.DIGEST_LENGTH);for(i=0;i<8;i++)s[4*i]=this.state[i]>>>24&255,s[4*i+1]=this.state[i]>>>16&255,s[4*i+2]=this.state[i]>>>8&255,s[4*i+3]=this.state[i]>>>0&255;return s},e.prototype.hashBuffer=function(){for(var e=this.buffer,t=this.state,n=t[0],i=t[1],s=t[2],o=t[3],a=t[4],c=t[5],u=t[6],l=t[7],h=0;h<r.BLOCK_SIZE;h++){if(h<16)this.temp[h]=(255&e[4*h])<<24|(255&e[4*h+1])<<16|(255&e[4*h+2])<<8|255&e[4*h+3];else{var d=this.temp[h-2],f=(d>>>17|d<<15)^(d>>>19|d<<13)^d>>>10,p=((d=this.temp[h-15])>>>7|d<<25)^(d>>>18|d<<14)^d>>>3;this.temp[h]=(f+this.temp[h-7]|0)+(p+this.temp[h-16]|0)}var g=(((a>>>6|a<<26)^(a>>>11|a<<21)^(a>>>25|a<<7))+(a&c^~a&u)|0)+(l+(r.KEY[h]+this.temp[h]|0)|0)|0,_=((n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10))+(n&i^n&s^i&s)|0;l=u,u=c,c=a,a=o+g|0,o=s,s=i,i=n,n=g+_|0}t[0]+=n,t[1]+=i,t[2]+=s,t[3]+=o,t[4]+=a,t[5]+=c,t[6]+=u,t[7]+=l},e}();t.RawSha256=i},494(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MAX_HASHABLE_LENGTH=t.INIT=t.KEY=t.DIGEST_LENGTH=t.BLOCK_SIZE=void 0,t.BLOCK_SIZE=64,t.DIGEST_LENGTH=32,t.KEY=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),t.INIT=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],t.MAX_HASHABLE_LENGTH=Math.pow(2,53)-1},523(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),(0,n(215).__exportStar)(n(871),t)},871(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Sha256=void 0;var r=n(215),i=n(494),s=n(602),o=n(388),a=function(){function e(e){if(this.hash=new s.RawSha256,e){this.outer=new s.RawSha256;var t=function(e){var t=(0,o.convertToBuffer)(e);if(t.byteLength>i.BLOCK_SIZE){var n=new s.RawSha256;n.update(t),t=n.digest()}var r=new Uint8Array(i.BLOCK_SIZE);return r.set(t),r}(e),n=new Uint8Array(i.BLOCK_SIZE);n.set(t);for(var r=0;r<i.BLOCK_SIZE;r++)t[r]^=54,n[r]^=92;for(this.hash.update(t),this.outer.update(n),r=0;r<t.byteLength;r++)t[r]=0}}return e.prototype.update=function(e){if(!(0,o.isEmptyData)(e)&&!this.error)try{this.hash.update((0,o.convertToBuffer)(e))}catch(e){this.error=e}},e.prototype.digestSync=function(){if(this.error)throw this.error;return this.outer?(this.outer.finished||this.outer.update(this.hash.digest()),this.outer.digest()):this.hash.digest()},e.prototype.digest=function(){return(0,r.__awaiter)(this,void 0,void 0,function(){return(0,r.__generator)(this,function(e){return[2,this.digestSync()]})})},e}();t.Sha256=a},24(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.convertToBuffer=void 0;var r=n(6),i="undefined"!=typeof Buffer&&Buffer.from?function(e){return Buffer.from(e,"utf8")}:r.fromUtf8;t.convertToBuffer=function(e){return e instanceof Uint8Array?e:"string"==typeof e?i(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(e)}},388(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uint32ArrayFrom=t.numToUint8=t.isEmptyData=t.convertToBuffer=void 0;var r=n(24);Object.defineProperty(t,"convertToBuffer",{enumerable:!0,get:function(){return r.convertToBuffer}});var i=n(165);Object.defineProperty(t,"isEmptyData",{enumerable:!0,get:function(){return i.isEmptyData}});var s=n(413);Object.defineProperty(t,"numToUint8",{enumerable:!0,get:function(){return s.numToUint8}});var o=n(110);Object.defineProperty(t,"uint32ArrayFrom",{enumerable:!0,get:function(){return o.uint32ArrayFrom}})},165(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isEmptyData=void 0,t.isEmptyData=function(e){return"string"==typeof e?0===e.length:0===e.byteLength}},413(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.numToUint8=void 0,t.numToUint8=function(e){return new Uint8Array([(4278190080&e)>>24,(16711680&e)>>16,(65280&e)>>8,255&e])}},110(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uint32ArrayFrom=void 0,t.uint32ArrayFrom=function(e){if(!Array.from){for(var t=new Uint32Array(e.length);0<e.length;)t[0]=e[0];return t}return Uint32Array.from(e)}},6(e,t,n){"use strict";n.r(t),n.d(t,{fromUtf8:()=>r,toUtf8:()=>i});const r=e=>"function"==typeof TextEncoder?function(e){return(new TextEncoder).encode(e)}(e):(e=>{const t=[];for(let n=0,r=e.length;n<r;n++){const r=e.charCodeAt(n);if(r<128)t.push(r);else if(r<2048)t.push(r>>6|192,63&r|128);else if(n+1<e.length&&55296==(64512&r)&&56320==(64512&e.charCodeAt(n+1))){const i=65536+((1023&r)<<10)+(1023&e.charCodeAt(++n));t.push(i>>18|240,i>>12&63|128,i>>6&63|128,63&i|128)}else t.push(r>>12|224,r>>6&63|128,63&r|128)}return Uint8Array.from(t)})(e),i=e=>"function"==typeof TextDecoder?function(e){return new TextDecoder("utf-8").decode(e)}(e):(e=>{let t="";for(let n=0,r=e.length;n<r;n++){const r=e[n];if(r<128)t+=String.fromCharCode(r);else if(192<=r&&r<224){const i=e[++n];t+=String.fromCharCode((31&r)<<6|63&i)}else if(240<=r&&r<365){const i="%"+[r,e[++n],e[++n],e[++n]].map(e=>e.toString(16)).join("%");t+=decodeURIComponent(i)}else t+=String.fromCharCode((15&r)<<12|(63&e[++n])<<6|63&e[++n])}return t})(e)},526(e,t){"use strict";t.byteLength=function(e){var t=a(e),n=t[0],r=t[1];return 3*(n+r)/4-r},t.toByteArray=function(e){var t,n,s=a(e),o=s[0],c=s[1],u=new i(function(e,t,n){return 3*(t+n)/4-n}(0,o,c)),l=0,h=c>0?o-4:o;for(n=0;n<h;n+=4)t=r[e.charCodeAt(n)]<<18|r[e.charCodeAt(n+1)]<<12|r[e.charCodeAt(n+2)]<<6|r[e.charCodeAt(n+3)],u[l++]=t>>16&255,u[l++]=t>>8&255,u[l++]=255&t;return 2===c&&(t=r[e.charCodeAt(n)]<<2|r[e.charCodeAt(n+1)]>>4,u[l++]=255&t),1===c&&(t=r[e.charCodeAt(n)]<<10|r[e.charCodeAt(n+1)]<<4|r[e.charCodeAt(n+2)]>>2,u[l++]=t>>8&255,u[l++]=255&t),u},t.fromByteArray=function(e){for(var t,r=e.length,i=r%3,s=[],o=16383,a=0,c=r-i;a<c;a+=o)s.push(u(e,a,a+o>c?c:a+o));return 1===i?(t=e[r-1],s.push(n[t>>2]+n[t<<4&63]+"==")):2===i&&(t=(e[r-2]<<8)+e[r-1],s.push(n[t>>10]+n[t>>4&63]+n[t<<2&63]+"=")),s.join("")};for(var n=[],r=[],i="undefined"!=typeof Uint8Array?Uint8Array:Array,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",o=0;o<64;++o)n[o]=s[o],r[s.charCodeAt(o)]=o;function a(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var n=e.indexOf("=");return-1===n&&(n=t),[n,n===t?0:4-n%4]}function c(e){return n[e>>18&63]+n[e>>12&63]+n[e>>6&63]+n[63&e]}function u(e,t,n){for(var r,i=[],s=t;s<n;s+=3)r=(e[s]<<16&16711680)+(e[s+1]<<8&65280)+(255&e[s+2]),i.push(c(r));return i.join("")}r["-".charCodeAt(0)]=62,r["_".charCodeAt(0)]=63},287(e,t,n){"use strict";var r=n(526),i=n(251),s=n(634);function o(){return c.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function a(e,t){if(o()<t)throw new RangeError("Invalid typed array length");return c.TYPED_ARRAY_SUPPORT?(e=new Uint8Array(t)).__proto__=c.prototype:(null===e&&(e=new c(t)),e.length=t),e}function c(e,t,n){if(!(c.TYPED_ARRAY_SUPPORT||this instanceof c))return new c(e,t,n);if("number"==typeof e){if("string"==typeof t)throw new Error("If encoding is specified then the first argument must be a string");return h(this,e)}return u(this,e,t,n)}function u(e,t,n,r){if("number"==typeof t)throw new TypeError('"value" argument must not be a number');return"undefined"!=typeof ArrayBuffer&&t instanceof ArrayBuffer?function(e,t,n,r){if(t.byteLength,n<0||t.byteLength<n)throw new RangeError("'offset' is out of bounds");if(t.byteLength<n+(r||0))throw new RangeError("'length' is out of bounds");return t=void 0===n&&void 0===r?new Uint8Array(t):void 0===r?new Uint8Array(t,n):new Uint8Array(t,n,r),c.TYPED_ARRAY_SUPPORT?(e=t).__proto__=c.prototype:e=d(e,t),e}(e,t,n,r):"string"==typeof t?function(e,t,n){if("string"==typeof n&&""!==n||(n="utf8"),!c.isEncoding(n))throw new TypeError('"encoding" must be a valid string encoding');var r=0|p(t,n),i=(e=a(e,r)).write(t,n);return i!==r&&(e=e.slice(0,i)),e}(e,t,n):function(e,t){if(c.isBuffer(t)){var n=0|f(t.length);return 0===(e=a(e,n)).length||t.copy(e,0,0,n),e}if(t){if("undefined"!=typeof ArrayBuffer&&t.buffer instanceof ArrayBuffer||"length"in t)return"number"!=typeof t.length||(r=t.length)!=r?a(e,0):d(e,t);if("Buffer"===t.type&&s(t.data))return d(e,t.data)}var r;throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")}(e,t)}function l(e){if("number"!=typeof e)throw new TypeError('"size" argument must be a number');if(e<0)throw new RangeError('"size" argument must not be negative')}function h(e,t){if(l(t),e=a(e,t<0?0:0|f(t)),!c.TYPED_ARRAY_SUPPORT)for(var n=0;n<t;++n)e[n]=0;return e}function d(e,t){var n=t.length<0?0:0|f(t.length);e=a(e,n);for(var r=0;r<n;r+=1)e[r]=255&t[r];return e}function f(e){if(e>=o())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+o().toString(16)+" bytes");return 0|e}function p(e,t){if(c.isBuffer(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!=typeof e&&(e=""+e);var n=e.length;if(0===n)return 0;for(var r=!1;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":case void 0:return B(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return $(e).length;default:if(r)return B(e).length;t=(""+t).toLowerCase(),r=!0}}function g(e,t,n){var r=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if((n>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return P(this,t,n);case"utf8":case"utf-8":return T(this,t,n);case"ascii":return U(this,t,n);case"latin1":case"binary":return D(this,t,n);case"base64":return I(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return C(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function _(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function m(e,t,n,r,i){if(0===e.length)return-1;if("string"==typeof n?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),n=+n,isNaN(n)&&(n=i?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(i)return-1;n=e.length-1}else if(n<0){if(!i)return-1;n=0}if("string"==typeof t&&(t=c.from(t,r)),c.isBuffer(t))return 0===t.length?-1:y(e,t,n,r,i);if("number"==typeof t)return t&=255,c.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):y(e,[t],n,r,i);throw new TypeError("val must be string, number or Buffer")}function y(e,t,n,r,i){var s,o=1,a=e.length,c=t.length;if(void 0!==r&&("ucs2"===(r=String(r).toLowerCase())||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(e.length<2||t.length<2)return-1;o=2,a/=2,c/=2,n/=2}function u(e,t){return 1===o?e[t]:e.readUInt16BE(t*o)}if(i){var l=-1;for(s=n;s<a;s++)if(u(e,s)===u(t,-1===l?0:s-l)){if(-1===l&&(l=s),s-l+1===c)return l*o}else-1!==l&&(s-=s-l),l=-1}else for(n+c>a&&(n=a-c),s=n;s>=0;s--){for(var h=!0,d=0;d<c;d++)if(u(e,s+d)!==u(t,d)){h=!1;break}if(h)return s}return-1}function w(e,t,n,r){n=Number(n)||0;var i=e.length-n;r?(r=Number(r))>i&&(r=i):r=i;var s=t.length;if(s%2!=0)throw new TypeError("Invalid hex string");r>s/2&&(r=s/2);for(var o=0;o<r;++o){var a=parseInt(t.substr(2*o,2),16);if(isNaN(a))return o;e[n+o]=a}return o}function b(e,t,n,r){return j(B(t,e.length-n),e,n,r)}function A(e,t,n,r){return j(function(e){for(var t=[],n=0;n<e.length;++n)t.push(255&e.charCodeAt(n));return t}(t),e,n,r)}function v(e,t,n,r){return A(e,t,n,r)}function S(e,t,n,r){return j($(t),e,n,r)}function E(e,t,n,r){return j(function(e,t){for(var n,r,i,s=[],o=0;o<e.length&&!((t-=2)<0);++o)r=(n=e.charCodeAt(o))>>8,i=n%256,s.push(i),s.push(r);return s}(t,e.length-n),e,n,r)}function I(e,t,n){return 0===t&&n===e.length?r.fromByteArray(e):r.fromByteArray(e.slice(t,n))}function T(e,t,n){n=Math.min(e.length,n);for(var r=[],i=t;i<n;){var s,o,a,c,u=e[i],l=null,h=u>239?4:u>223?3:u>191?2:1;if(i+h<=n)switch(h){case 1:u<128&&(l=u);break;case 2:128==(192&(s=e[i+1]))&&(c=(31&u)<<6|63&s)>127&&(l=c);break;case 3:s=e[i+1],o=e[i+2],128==(192&s)&&128==(192&o)&&(c=(15&u)<<12|(63&s)<<6|63&o)>2047&&(c<55296||c>57343)&&(l=c);break;case 4:s=e[i+1],o=e[i+2],a=e[i+3],128==(192&s)&&128==(192&o)&&128==(192&a)&&(c=(15&u)<<18|(63&s)<<12|(63&o)<<6|63&a)>65535&&c<1114112&&(l=c)}null===l?(l=65533,h=1):l>65535&&(l-=65536,r.push(l>>>10&1023|55296),l=56320|1023&l),r.push(l),i+=h}return function(e){var t=e.length;if(t<=R)return String.fromCharCode.apply(String,e);for(var n="",r=0;r<t;)n+=String.fromCharCode.apply(String,e.slice(r,r+=R));return n}(r)}t.hp=c,t.IS=50,c.TYPED_ARRAY_SUPPORT=void 0!==n.g.TYPED_ARRAY_SUPPORT?n.g.TYPED_ARRAY_SUPPORT:function(){try{var e=new Uint8Array(1);return e.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===e.foo()&&"function"==typeof e.subarray&&0===e.subarray(1,1).byteLength}catch(e){return!1}}(),o(),c.poolSize=8192,c._augment=function(e){return e.__proto__=c.prototype,e},c.from=function(e,t,n){return u(null,e,t,n)},c.TYPED_ARRAY_SUPPORT&&(c.prototype.__proto__=Uint8Array.prototype,c.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&c[Symbol.species]===c&&Object.defineProperty(c,Symbol.species,{value:null,configurable:!0})),c.alloc=function(e,t,n){return function(e,t,n,r){return l(t),t<=0?a(e,t):void 0!==n?"string"==typeof r?a(e,t).fill(n,r):a(e,t).fill(n):a(e,t)}(null,e,t,n)},c.allocUnsafe=function(e){return h(null,e)},c.allocUnsafeSlow=function(e){return h(null,e)},c.isBuffer=function(e){return!(null==e||!e._isBuffer)},c.compare=function(e,t){if(!c.isBuffer(e)||!c.isBuffer(t))throw new TypeError("Arguments must be Buffers");if(e===t)return 0;for(var n=e.length,r=t.length,i=0,s=Math.min(n,r);i<s;++i)if(e[i]!==t[i]){n=e[i],r=t[i];break}return n<r?-1:r<n?1:0},c.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},c.concat=function(e,t){if(!s(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return c.alloc(0);var n;if(void 0===t)for(t=0,n=0;n<e.length;++n)t+=e[n].length;var r=c.allocUnsafe(t),i=0;for(n=0;n<e.length;++n){var o=e[n];if(!c.isBuffer(o))throw new TypeError('"list" argument must be an Array of Buffers');o.copy(r,i),i+=o.length}return r},c.byteLength=p,c.prototype._isBuffer=!0,c.prototype.swap16=function(){var e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var t=0;t<e;t+=2)_(this,t,t+1);return this},c.prototype.swap32=function(){var e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var t=0;t<e;t+=4)_(this,t,t+3),_(this,t+1,t+2);return this},c.prototype.swap64=function(){var e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var t=0;t<e;t+=8)_(this,t,t+7),_(this,t+1,t+6),_(this,t+2,t+5),_(this,t+3,t+4);return this},c.prototype.toString=function(){var e=0|this.length;return 0===e?"":0===arguments.length?T(this,0,e):g.apply(this,arguments)},c.prototype.equals=function(e){if(!c.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===c.compare(this,e)},c.prototype.inspect=function(){var e="",n=t.IS;return this.length>0&&(e=this.toString("hex",0,n).match(/.{2}/g).join(" "),this.length>n&&(e+=" ... ")),"<Buffer "+e+">"},c.prototype.compare=function(e,t,n,r,i){if(!c.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===r&&(r=0),void 0===i&&(i=this.length),t<0||n>e.length||r<0||i>this.length)throw new RangeError("out of range index");if(r>=i&&t>=n)return 0;if(r>=i)return-1;if(t>=n)return 1;if(this===e)return 0;for(var s=(i>>>=0)-(r>>>=0),o=(n>>>=0)-(t>>>=0),a=Math.min(s,o),u=this.slice(r,i),l=e.slice(t,n),h=0;h<a;++h)if(u[h]!==l[h]){s=u[h],o=l[h];break}return s<o?-1:o<s?1:0},c.prototype.includes=function(e,t,n){return-1!==this.indexOf(e,t,n)},c.prototype.indexOf=function(e,t,n){return m(this,e,t,n,!0)},c.prototype.lastIndexOf=function(e,t,n){return m(this,e,t,n,!1)},c.prototype.write=function(e,t,n,r){if(void 0===t)r="utf8",n=this.length,t=0;else if(void 0===n&&"string"==typeof t)r=t,n=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t|=0,isFinite(n)?(n|=0,void 0===r&&(r="utf8")):(r=n,n=void 0)}var i=this.length-t;if((void 0===n||n>i)&&(n=i),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");for(var s=!1;;)switch(r){case"hex":return w(this,e,t,n);case"utf8":case"utf-8":return b(this,e,t,n);case"ascii":return A(this,e,t,n);case"latin1":case"binary":return v(this,e,t,n);case"base64":return S(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return E(this,e,t,n);default:if(s)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),s=!0}},c.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var R=4096;function U(e,t,n){var r="";n=Math.min(e.length,n);for(var i=t;i<n;++i)r+=String.fromCharCode(127&e[i]);return r}function D(e,t,n){var r="";n=Math.min(e.length,n);for(var i=t;i<n;++i)r+=String.fromCharCode(e[i]);return r}function P(e,t,n){var r=e.length;(!t||t<0)&&(t=0),(!n||n<0||n>r)&&(n=r);for(var i="",s=t;s<n;++s)i+=q(e[s]);return i}function C(e,t,n){for(var r=e.slice(t,n),i="",s=0;s<r.length;s+=2)i+=String.fromCharCode(r[s]+256*r[s+1]);return i}function k(e,t,n){if(e%1!=0||e<0)throw new RangeError("offset is not uint");if(e+t>n)throw new RangeError("Trying to access beyond buffer length")}function N(e,t,n,r,i,s){if(!c.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||t<s)throw new RangeError('"value" argument is out of bounds');if(n+r>e.length)throw new RangeError("Index out of range")}function L(e,t,n,r){t<0&&(t=65535+t+1);for(var i=0,s=Math.min(e.length-n,2);i<s;++i)e[n+i]=(t&255<<8*(r?i:1-i))>>>8*(r?i:1-i)}function O(e,t,n,r){t<0&&(t=4294967295+t+1);for(var i=0,s=Math.min(e.length-n,4);i<s;++i)e[n+i]=t>>>8*(r?i:3-i)&255}function M(e,t,n,r,i,s){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function V(e,t,n,r,s){return s||M(e,0,n,4),i.write(e,t,n,r,23,4),n+4}function x(e,t,n,r,s){return s||M(e,0,n,8),i.write(e,t,n,r,52,8),n+8}c.prototype.slice=function(e,t){var n,r=this.length;if((e=~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),(t=void 0===t?r:~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),t<e&&(t=e),c.TYPED_ARRAY_SUPPORT)(n=this.subarray(e,t)).__proto__=c.prototype;else{var i=t-e;n=new c(i,void 0);for(var s=0;s<i;++s)n[s]=this[s+e]}return n},c.prototype.readUIntLE=function(e,t,n){e|=0,t|=0,n||k(e,t,this.length);for(var r=this[e],i=1,s=0;++s<t&&(i*=256);)r+=this[e+s]*i;return r},c.prototype.readUIntBE=function(e,t,n){e|=0,t|=0,n||k(e,t,this.length);for(var r=this[e+--t],i=1;t>0&&(i*=256);)r+=this[e+--t]*i;return r},c.prototype.readUInt8=function(e,t){return t||k(e,1,this.length),this[e]},c.prototype.readUInt16LE=function(e,t){return t||k(e,2,this.length),this[e]|this[e+1]<<8},c.prototype.readUInt16BE=function(e,t){return t||k(e,2,this.length),this[e]<<8|this[e+1]},c.prototype.readUInt32LE=function(e,t){return t||k(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},c.prototype.readUInt32BE=function(e,t){return t||k(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},c.prototype.readIntLE=function(e,t,n){e|=0,t|=0,n||k(e,t,this.length);for(var r=this[e],i=1,s=0;++s<t&&(i*=256);)r+=this[e+s]*i;return r>=(i*=128)&&(r-=Math.pow(2,8*t)),r},c.prototype.readIntBE=function(e,t,n){e|=0,t|=0,n||k(e,t,this.length);for(var r=t,i=1,s=this[e+--r];r>0&&(i*=256);)s+=this[e+--r]*i;return s>=(i*=128)&&(s-=Math.pow(2,8*t)),s},c.prototype.readInt8=function(e,t){return t||k(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},c.prototype.readInt16LE=function(e,t){t||k(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},c.prototype.readInt16BE=function(e,t){t||k(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},c.prototype.readInt32LE=function(e,t){return t||k(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},c.prototype.readInt32BE=function(e,t){return t||k(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},c.prototype.readFloatLE=function(e,t){return t||k(e,4,this.length),i.read(this,e,!0,23,4)},c.prototype.readFloatBE=function(e,t){return t||k(e,4,this.length),i.read(this,e,!1,23,4)},c.prototype.readDoubleLE=function(e,t){return t||k(e,8,this.length),i.read(this,e,!0,52,8)},c.prototype.readDoubleBE=function(e,t){return t||k(e,8,this.length),i.read(this,e,!1,52,8)},c.prototype.writeUIntLE=function(e,t,n,r){e=+e,t|=0,n|=0,r||N(this,e,t,n,Math.pow(2,8*n)-1,0);var i=1,s=0;for(this[t]=255&e;++s<n&&(i*=256);)this[t+s]=e/i&255;return t+n},c.prototype.writeUIntBE=function(e,t,n,r){e=+e,t|=0,n|=0,r||N(this,e,t,n,Math.pow(2,8*n)-1,0);var i=n-1,s=1;for(this[t+i]=255&e;--i>=0&&(s*=256);)this[t+i]=e/s&255;return t+n},c.prototype.writeUInt8=function(e,t,n){return e=+e,t|=0,n||N(this,e,t,1,255,0),c.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},c.prototype.writeUInt16LE=function(e,t,n){return e=+e,t|=0,n||N(this,e,t,2,65535,0),c.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):L(this,e,t,!0),t+2},c.prototype.writeUInt16BE=function(e,t,n){return e=+e,t|=0,n||N(this,e,t,2,65535,0),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):L(this,e,t,!1),t+2},c.prototype.writeUInt32LE=function(e,t,n){return e=+e,t|=0,n||N(this,e,t,4,4294967295,0),c.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):O(this,e,t,!0),t+4},c.prototype.writeUInt32BE=function(e,t,n){return e=+e,t|=0,n||N(this,e,t,4,4294967295,0),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):O(this,e,t,!1),t+4},c.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t|=0,!r){var i=Math.pow(2,8*n-1);N(this,e,t,n,i-1,-i)}var s=0,o=1,a=0;for(this[t]=255&e;++s<n&&(o*=256);)e<0&&0===a&&0!==this[t+s-1]&&(a=1),this[t+s]=(e/o|0)-a&255;return t+n},c.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t|=0,!r){var i=Math.pow(2,8*n-1);N(this,e,t,n,i-1,-i)}var s=n-1,o=1,a=0;for(this[t+s]=255&e;--s>=0&&(o*=256);)e<0&&0===a&&0!==this[t+s+1]&&(a=1),this[t+s]=(e/o|0)-a&255;return t+n},c.prototype.writeInt8=function(e,t,n){return e=+e,t|=0,n||N(this,e,t,1,127,-128),c.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},c.prototype.writeInt16LE=function(e,t,n){return e=+e,t|=0,n||N(this,e,t,2,32767,-32768),c.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):L(this,e,t,!0),t+2},c.prototype.writeInt16BE=function(e,t,n){return e=+e,t|=0,n||N(this,e,t,2,32767,-32768),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):L(this,e,t,!1),t+2},c.prototype.writeInt32LE=function(e,t,n){return e=+e,t|=0,n||N(this,e,t,4,2147483647,-2147483648),c.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):O(this,e,t,!0),t+4},c.prototype.writeInt32BE=function(e,t,n){return e=+e,t|=0,n||N(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):O(this,e,t,!1),t+4},c.prototype.writeFloatLE=function(e,t,n){return V(this,e,t,!0,n)},c.prototype.writeFloatBE=function(e,t,n){return V(this,e,t,!1,n)},c.prototype.writeDoubleLE=function(e,t,n){return x(this,e,t,!0,n)},c.prototype.writeDoubleBE=function(e,t,n){return x(this,e,t,!1,n)},c.prototype.copy=function(e,t,n,r){if(n||(n=0),r||0===r||(r=this.length),t>=e.length&&(t=e.length),t||(t=0),r>0&&r<n&&(r=n),r===n)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(n<0||n>=this.length)throw new RangeError("sourceStart out of bounds");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-t<r-n&&(r=e.length-t+n);var i,s=r-n;if(this===e&&n<t&&t<r)for(i=s-1;i>=0;--i)e[i+t]=this[i+n];else if(s<1e3||!c.TYPED_ARRAY_SUPPORT)for(i=0;i<s;++i)e[i+t]=this[i+n];else Uint8Array.prototype.set.call(e,this.subarray(n,n+s),t);return s},c.prototype.fill=function(e,t,n,r){if("string"==typeof e){if("string"==typeof t?(r=t,t=0,n=this.length):"string"==typeof n&&(r=n,n=this.length),1===e.length){var i=e.charCodeAt(0);i<256&&(e=i)}if(void 0!==r&&"string"!=typeof r)throw new TypeError("encoding must be a string");if("string"==typeof r&&!c.isEncoding(r))throw new TypeError("Unknown encoding: "+r)}else"number"==typeof e&&(e&=255);if(t<0||this.length<t||this.length<n)throw new RangeError("Out of range index");if(n<=t)return this;var s;if(t>>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(s=t;s<n;++s)this[s]=e;else{var o=c.isBuffer(e)?e:B(new c(e,r).toString()),a=o.length;for(s=0;s<n-t;++s)this[s+t]=o[s%a]}return this};var F=/[^+\/0-9A-Za-z-_]/g;function q(e){return e<16?"0"+e.toString(16):e.toString(16)}function B(e,t){var n;t=t||1/0;for(var r=e.length,i=null,s=[],o=0;o<r;++o){if((n=e.charCodeAt(o))>55295&&n<57344){if(!i){if(n>56319){(t-=3)>-1&&s.push(239,191,189);continue}if(o+1===r){(t-=3)>-1&&s.push(239,191,189);continue}i=n;continue}if(n<56320){(t-=3)>-1&&s.push(239,191,189),i=n;continue}n=65536+(i-55296<<10|n-56320)}else i&&(t-=3)>-1&&s.push(239,191,189);if(i=null,n<128){if((t-=1)<0)break;s.push(n)}else if(n<2048){if((t-=2)<0)break;s.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;s.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;s.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return s}function $(e){return r.toByteArray(function(e){if((e=function(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}(e).replace(F,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function j(e,t,n,r){for(var i=0;i<r&&!(i+n>=t.length||i>=e.length);++i)t[i+n]=e[i];return i}},251(e,t){t.read=function(e,t,n,r,i){var s,o,a=8*i-r-1,c=(1<<a)-1,u=c>>1,l=-7,h=n?i-1:0,d=n?-1:1,f=e[t+h];for(h+=d,s=f&(1<<-l)-1,f>>=-l,l+=a;l>0;s=256*s+e[t+h],h+=d,l-=8);for(o=s&(1<<-l)-1,s>>=-l,l+=r;l>0;o=256*o+e[t+h],h+=d,l-=8);if(0===s)s=1-u;else{if(s===c)return o?NaN:1/0*(f?-1:1);o+=Math.pow(2,r),s-=u}return(f?-1:1)*o*Math.pow(2,s-r)},t.write=function(e,t,n,r,i,s){var o,a,c,u=8*s-i-1,l=(1<<u)-1,h=l>>1,d=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,f=r?0:s-1,p=r?1:-1,g=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,o=l):(o=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-o))<1&&(o--,c*=2),(t+=o+h>=1?d/c:d*Math.pow(2,1-h))*c>=2&&(o++,c/=2),o+h>=l?(a=0,o=l):o+h>=1?(a=(t*c-1)*Math.pow(2,i),o+=h):(a=t*Math.pow(2,h-1)*Math.pow(2,i),o=0));i>=8;e[n+f]=255&a,f+=p,a/=256,i-=8);for(o=o<<i|a,u+=i;u>0;e[n+f]=255&o,f+=p,o/=256,u-=8);e[n+f-p]|=128*g}},634(e){var t={}.toString;e.exports=Array.isArray||function(e){return"[object Array]"==t.call(e)}},916(e,t,n){e.exports=self.fetch||(self.fetch=n(782).default||n(782))},596(e,t,n){var r,i,s;s=function(){function e(){for(var e=0,t={};e<arguments.length;e++){var n=arguments[e];for(var r in n)t[r]=n[r]}return t}function t(e){return e.replace(/(%[0-9A-Z]{2})+/g,decodeURIComponent)}return function n(r){function i(){}function s(t,n,s){if("undefined"!=typeof document){"number"==typeof(s=e({path:"/"},i.defaults,s)).expires&&(s.expires=new Date(1*new Date+864e5*s.expires)),s.expires=s.expires?s.expires.toUTCString():"";try{var o=JSON.stringify(n);/^[\{\[]/.test(o)&&(n=o)}catch(e){}n=r.write?r.write(n,t):encodeURIComponent(String(n)).replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g,decodeURIComponent),t=encodeURIComponent(String(t)).replace(/%(23|24|26|2B|5E|60|7C)/g,decodeURIComponent).replace(/[\(\)]/g,escape);var a="";for(var c in s)s[c]&&(a+="; "+c,!0!==s[c]&&(a+="="+s[c].split(";")[0]));return document.cookie=t+"="+n+a}}function o(e,n){if("undefined"!=typeof document){for(var i={},s=document.cookie?document.cookie.split("; "):[],o=0;o<s.length;o++){var a=s[o].split("="),c=a.slice(1).join("=");n||'"'!==c.charAt(0)||(c=c.slice(1,-1));try{var u=t(a[0]);if(c=(r.read||r)(c,u)||t(c),n)try{c=JSON.parse(c)}catch(e){}if(i[u]=c,e===u)break}catch(e){}}return e?i[e]:i}}return i.set=s,i.get=function(e){return o(e,!1)},i.getJSON=function(e){return o(e,!0)},i.remove=function(t,n){s(t,"",e(n,{expires:-1}))},i.defaults={},i.withConverter=n,i}(function(){})},void 0===(i="function"==typeof(r=s)?r.call(t,n,t,e):r)||(e.exports=i),e.exports=s()},284(e,t,n){"use strict";const r="undefined"!=typeof globalThis?globalThis:void 0,i=r?.window;if(i)i.global=i,i.global._runningInNodeJS=!1;else if(r&&(r.global=r,void 0===r.window)){class e{constructor(){this.result=null,this.error=null,this.onload=null,this.onloadend=null,this.onerror=null}readAsDataURL(e){e.arrayBuffer().then(t=>{const n=function(e){if(Buffer)return Buffer.from(e).toString("base64");let t="";const n=new Uint8Array(e);for(let e=0;e<n.length;e+=32768){const r=n.subarray(e,e+32768);t+=String.fromCharCode.apply(null,Array.from(r))}if("function"==typeof btoa)return btoa(t);throw new Error("No base64 encoder available in this environment.")}(t),r=e.type||"application/octet-stream";this.result=`data:${r};base64,${n}`,this.onload&&this.onload({target:this}),this.onloadend&&this.onloadend({target:this})}).catch(e=>{this.error=e,this.onerror&&this.onerror({target:this})})}readAsArrayBuffer(e){e.arrayBuffer().then(e=>{this.result=e,this.onload&&this.onload({target:this}),this.onloadend&&this.onloadend({target:this})}).catch(e=>{this.error=e,this.onerror&&this.onerror({target:this})})}readAsText(e,t="utf-8"){e.text().then(e=>{this.result=e,this.onload&&this.onload({target:this}),this.onloadend&&this.onloadend({target:this})}).catch(e=>{this.error=e,this.onerror&&this.onerror({target:this})})}}r.FileReader=e;class t{constructor(){this.status=0,this.statusText="",this.readyState=0,this.responseText="",this.response=null,this.responseType="",this.responseURL="",this.timeout=0,this.withCredentials=!1,this.onload=null,this.onerror=null,this.onabort=null,this.ontimeout=null,this.onprogress=null,this.onreadystatechange=null,this.upload={onprogress:null},this._method="GET",this._url="",this._headers={},this._aborted=!1}open(e,t){this._method=e,this._url=t,this.readyState=1}setRequestHeader(e,t){this._headers[e]=t}getResponseHeader(e){return null}abort(){this._aborted=!0,this.onabort&&this.onabort({})}send(e){if(this._aborted)return;const t={method:this._method,headers:this._headers};e&&"GET"!==this._method&&"HEAD"!==this._method&&(t.body=e),fetch(this._url,t).then(async e=>{if(!this._aborted){if(this.status=e.status,this.statusText=e.statusText,this.responseURL=e.url,this.readyState=4,"blob"===this.responseType)this.response=await e.blob();else if("json"===this.responseType)try{this.response=await e.json()}catch{this.response=null}else"arraybuffer"===this.responseType?this.response=await e.arrayBuffer():(this.responseText=await e.text(),this.response=this.responseText);this.onload&&this.onload({})}}).catch(e=>{this._aborted||this.onerror&&this.onerror(e)})}}r.XMLHttpRequest=t,r.window={_runningInNodeJS:!0,alert:e=>console.error("[Alert]",e),sessionStorage:{getItem:e=>null,setItem:(e,t)=>{},removeItem:e=>{}},localStorage:{getItem:e=>{const t=n(132),r=n(300);try{const n=r.resolve(process.cwd(),"states","localStorage",`${e}.skapi`);return t.existsSync(n)?t.readFileSync(n,"utf8"):null}catch(e){return null}},setItem:(e,t)=>{const r=n(132),i=n(300);try{const n=i.resolve(process.cwd(),"states","localStorage");r.existsSync(n)||r.mkdirSync(n,{recursive:!0});const s=i.resolve(n,`${e}.skapi`);r.writeFileSync(s,t,"utf8")}catch(e){}},removeItem:e=>{const t=n(132),r=n(300);try{const n=r.resolve(process.cwd(),"states","localStorage",`${e}.skapi`);t.existsSync(n)&&t.unlinkSync(n)}catch(e){}}},location:{href:"",origin:"",hostname:"",protocol:"",replace:e=>{}},navigator:{userAgent:`nodejs/${r?.process?.versions?.node||"unknown"}`,mediaDevices:{getUserMedia:async e=>{throw new Error("getUserMedia is not supported in Node.js environment.")}}},addEventListener:()=>{},removeEventListener:()=>{}}}},215(e,t,n){"use strict";n.r(t),n.d(t,{__assign:()=>s,__asyncDelegator:()=>b,__asyncGenerator:()=>w,__asyncValues:()=>A,__await:()=>y,__awaiter:()=>l,__classPrivateFieldGet:()=>I,__classPrivateFieldSet:()=>T,__createBinding:()=>d,__decorate:()=>a,__exportStar:()=>f,__extends:()=>i,__generator:()=>h,__importDefault:()=>E,__importStar:()=>S,__makeTemplateObject:()=>v,__metadata:()=>u,__param:()=>c,__read:()=>g,__rest:()=>o,__spread:()=>_,__spreadArrays:()=>m,__values:()=>p});var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])},r(e,t)};function i(e,t){function n(){this.constructor=e}r(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}var s=function(){return s=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},s.apply(this,arguments)};function o(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]])}return n}function a(e,t,n,r){var i,s=arguments.length,o=s<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,n,o):i(t,n))||o);return s>3&&o&&Object.defineProperty(t,n,o),o}function c(e,t){return function(n,r){t(n,r,e)}}function u(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}function l(e,t,n,r){return new(n||(n=Promise))(function(i,s){function o(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(o,a)}c((r=r.apply(e,t||[])).next())})}function h(e,t){var n,r,i,s,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(s){return function(a){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;o;)try{if(n=1,r&&(i=2&s[0]?r.return:s[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,s[1])).done)return i;switch(r=0,i&&(s=[2&s[0],i.value]),s[0]){case 0:case 1:i=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,r=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!((i=(i=o.trys).length>0&&i[i.length-1])||6!==s[0]&&2!==s[0])){o=0;continue}if(3===s[0]&&(!i||s[1]>i[0]&&s[1]<i[3])){o.label=s[1];break}if(6===s[0]&&o.label<i[1]){o.label=i[1],i=s;break}if(i&&o.label<i[2]){o.label=i[2],o.ops.push(s);break}i[2]&&o.ops.pop(),o.trys.pop();continue}s=t.call(e,o)}catch(e){s=[6,e],r=0}finally{n=i=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,a])}}}function d(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}function f(e,t){for(var n in e)"default"===n||t.hasOwnProperty(n)||(t[n]=e[n])}function p(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function g(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,i,s=n.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(r=s.next()).done;)o.push(r.value)}catch(e){i={error:e}}finally{try{r&&!r.done&&(n=s.return)&&n.call(s)}finally{if(i)throw i.error}}return o}function _(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(g(arguments[t]));return e}function m(){for(var e=0,t=0,n=arguments.length;t<n;t++)e+=arguments[t].length;var r=Array(e),i=0;for(t=0;t<n;t++)for(var s=arguments[t],o=0,a=s.length;o<a;o++,i++)r[i]=s[o];return r}function y(e){return this instanceof y?(this.v=e,this):new y(e)}function w(e,t,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r,i=n.apply(e,t||[]),s=[];return r={},o("next"),o("throw"),o("return"),r[Symbol.asyncIterator]=function(){return this},r;function o(e){i[e]&&(r[e]=function(t){return new Promise(function(n,r){s.push([e,t,n,r])>1||a(e,t)})})}function a(e,t){try{(n=i[e](t)).value instanceof y?Promise.resolve(n.value.v).then(c,u):l(s[0][2],n)}catch(e){l(s[0][3],e)}var n}function c(e){a("next",e)}function u(e){a("throw",e)}function l(e,t){e(t),s.shift(),s.length&&a(s[0][0],s[0][1])}}function b(e){var t,n;return t={},r("next"),r("throw",function(e){throw e}),r("return"),t[Symbol.iterator]=function(){return this},t;function r(r,i){t[r]=e[r]?function(t){return(n=!n)?{value:y(e[r](t)),done:"return"===r}:i?i(t):t}:i}}function A(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,n=e[Symbol.asyncIterator];return n?n.call(e):(e=p(e),t={},r("next"),r("throw"),r("return"),t[Symbol.asyncIterator]=function(){return this},t);function r(n){t[n]=e[n]&&function(t){return new Promise(function(r,i){!function(e,t,n,r){Promise.resolve(r).then(function(t){e({value:t,done:n})},t)}(r,i,(t=e[n](t)).done,t.value)})}}}function v(e,t){return Object.defineProperty?Object.defineProperty(e,"raw",{value:t}):e.raw=t,e}function S(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t}function E(e){return e&&e.__esModule?e:{default:e}}function I(e,t){if(!t.has(e))throw new TypeError("attempted to get private field on non-instance");return t.get(e)}function T(e,t,n){if(!t.has(e))throw new TypeError("attempted to set private field on non-instance");return t.set(e,n),n}},782(e,t,n){"use strict";function r(e,t){return t=t||{},new Promise(function(n,r){var i=new XMLHttpRequest,s=[],o=[],a={},c=function(){return{ok:2==(i.status/100|0),statusText:i.statusText,status:i.status,url:i.responseURL,text:function(){return Promise.resolve(i.responseText)},json:function(){return Promise.resolve(i.responseText).then(JSON.parse)},blob:function(){return Promise.resolve(new Blob([i.response]))},clone:c,headers:{keys:function(){return s},entries:function(){return o},get:function(e){return a[e.toLowerCase()]},has:function(e){return e.toLowerCase()in a}}}};for(var u in i.open(t.method||"get",e,!0),i.onload=function(){i.getAllResponseHeaders().replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm,function(e,t,n){s.push(t=t.toLowerCase()),o.push([t,n]),a[t]=a[t]?a[t]+","+n:n}),n(c())},i.onerror=r,i.withCredentials="include"==t.credentials,t.headers)i.setRequestHeader(u,t.headers[u]);i.send(t.body||null)})}n.r(t),n.d(t,{default:()=>r})},682(){},132(){},300(){}},t={};function n(r){var i=t[r];if(void 0!==i)return i.exports;var s=t[r]={exports:{}};return e[r](s,s.exports,n),s.exports}n.d=(e,t)=>{for(var r in t)n.o(t,r)&&!n.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var r={};return(()=>{"use strict";n.r(r),n.d(r,{Skapi:()=>rr,SkapiError:()=>te,Types:()=>e});var e={};n.r(e),n(284);var t,i=function(){function e(e){var t=e||{},n=t.ValidationData,r=t.Username,i=t.Password,s=t.AuthParameters,o=t.ClientMetadata;this.validationData=n||{},this.authParameters=s||{},this.clientMetadata=o||{},this.username=r,this.password=i}var t=e.prototype;return t.getUsername=function(){return this.username},t.getPassword=function(){return this.password},t.getValidationData=function(){return this.validationData},t.getAuthParameters=function(){return this.authParameters},t.getClientMetadata=function(){return this.clientMetadata},e}(),s=n(287);if("undefined"!=typeof window&&window.crypto&&(t=window.crypto),!t&&"undefined"!=typeof window&&window.msCrypto&&(t=window.msCrypto),!t&&void 0!==n.g&&n.g.crypto&&(t=n.g.crypto),!t)try{t=n(682)}catch(e){}function o(){if(t){if("function"==typeof t.getRandomValues)try{return t.getRandomValues(new Uint32Array(1))[0]}catch(e){}if("function"==typeof t.randomBytes)try{return t.randomBytes(4).readInt32LE()}catch(e){}}throw new Error("Native crypto module could not be used to get secure random number.")}var a=function(){function e(e,t){e=this.words=e||[],this.sigBytes=null!=t?t:4*e.length}var t=e.prototype;return t.random=function(t){for(var n=[],r=0;r<t;r+=4)n.push(o());return new e(n,t)},t.toString=function(){return function(e){for(var t=e.words,n=e.sigBytes,r=[],i=0;i<n;i++){var s=t[i>>>2]>>>24-i%4*8&255;r.push((s>>>4).toString(16)),r.push((15&s).toString(16))}return r.join("")}(this)},e}(),c=n(523);const u=l;function l(e,t){null!=e&&this.fromString(e,t)}function h(){return new l(null)}var d,f="undefined"!=typeof navigator;f&&"Microsoft Internet Explorer"==navigator.appName?(l.prototype.am=function(e,t,n,r,i,s){for(var o=32767&t,a=t>>15;--s>=0;){var c=32767&this[e],u=this[e++]>>15,l=a*c+u*o;i=((c=o*c+((32767&l)<<15)+n[r]+(1073741823&i))>>>30)+(l>>>15)+a*u+(i>>>30),n[r++]=1073741823&c}return i},d=30):f&&"Netscape"!=navigator.appName?(l.prototype.am=function(e,t,n,r,i,s){for(;--s>=0;){var o=t*this[e++]+n[r]+i;i=Math.floor(o/67108864),n[r++]=67108863&o}return i},d=26):(l.prototype.am=function(e,t,n,r,i,s){for(var o=16383&t,a=t>>14;--s>=0;){var c=16383&this[e],u=this[e++]>>14,l=a*c+u*o;i=((c=o*c+((16383&l)<<14)+n[r]+i)>>28)+(l>>14)+a*u,n[r++]=268435455&c}return i},d=28),l.prototype.DB=d,l.prototype.DM=(1<<d)-1,l.prototype.DV=1<<d,l.prototype.FV=Math.pow(2,52),l.prototype.F1=52-d,l.prototype.F2=2*d-52;var p,g,_=new Array;for(p="0".charCodeAt(0),g=0;g<=9;++g)_[p++]=g;for(p="a".charCodeAt(0),g=10;g<36;++g)_[p++]=g;for(p="A".charCodeAt(0),g=10;g<36;++g)_[p++]=g;function m(e){return"0123456789abcdefghijklmnopqrstuvwxyz".charAt(e)}function y(e,t){var n=_[e.charCodeAt(t)];return null==n?-1:n}function w(e){var t=h();return t.fromInt(e),t}function b(e){var t,n=1;return 0!=(t=e>>>16)&&(e=t,n+=16),0!=(t=e>>8)&&(e=t,n+=8),0!=(t=e>>4)&&(e=t,n+=4),0!=(t=e>>2)&&(e=t,n+=2),0!=(t=e>>1)&&(e=t,n+=1),n}function A(e){this.m=e,this.mp=e.invDigit(),this.mpl=32767&this.mp,this.mph=this.mp>>15,this.um=(1<<e.DB-15)-1,this.mt2=2*e.t}function v(e){return s.hp.from((new a).random(e).toString(),"hex")}A.prototype.convert=function(e){var t=h();return e.abs().dlShiftTo(this.m.t,t),t.divRemTo(this.m,null,t),e.s<0&&t.compareTo(l.ZERO)>0&&this.m.subTo(t,t),t},A.prototype.revert=function(e){var t=h();return e.copyTo(t),this.reduce(t),t},A.prototype.reduce=function(e){for(;e.t<=this.mt2;)e[e.t++]=0;for(var t=0;t<this.m.t;++t){var n=32767&e[t],r=n*this.mpl+((n*this.mph+(e[t]>>15)*this.mpl&this.um)<<15)&e.DM;for(e[n=t+this.m.t]+=this.m.am(0,r,e,t,0,this.m.t);e[n]>=e.DV;)e[n]-=e.DV,e[++n]++}e.clamp(),e.drShiftTo(this.m.t,e),e.compareTo(this.m)>=0&&e.subTo(this.m,e)},A.prototype.mulTo=function(e,t,n){e.multiplyTo(t,n),this.reduce(n)},A.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)},l.prototype.copyTo=function(e){for(var t=this.t-1;t>=0;--t)e[t]=this[t];e.t=this.t,e.s=this.s},l.prototype.fromInt=function(e){this.t=1,this.s=e<0?-1:0,e>0?this[0]=e:e<-1?this[0]=e+this.DV:this.t=0},l.prototype.fromString=function(e,t){var n;if(16==t)n=4;else if(8==t)n=3;else if(2==t)n=1;else if(32==t)n=5;else{if(4!=t)throw new Error("Only radix 2, 4, 8, 16, 32 are supported");n=2}this.t=0,this.s=0;for(var r=e.length,i=!1,s=0;--r>=0;){var o=y(e,r);o<0?"-"==e.charAt(r)&&(i=!0):(i=!1,0==s?this[this.t++]=o:s+n>this.DB?(this[this.t-1]|=(o&(1<<this.DB-s)-1)<<s,this[this.t++]=o>>this.DB-s):this[this.t-1]|=o<<s,(s+=n)>=this.DB&&(s-=this.DB))}this.clamp(),i&&l.ZERO.subTo(this,this)},l.prototype.clamp=function(){for(var e=this.s&this.DM;this.t>0&&this[this.t-1]==e;)--this.t},l.prototype.dlShiftTo=function(e,t){var n;for(n=this.t-1;n>=0;--n)t[n+e]=this[n];for(n=e-1;n>=0;--n)t[n]=0;t.t=this.t+e,t.s=this.s},l.prototype.drShiftTo=function(e,t){for(var n=e;n<this.t;++n)t[n-e]=this[n];t.t=Math.max(this.t-e,0),t.s=this.s},l.prototype.lShiftTo=function(e,t){var n,r=e%this.DB,i=this.DB-r,s=(1<<i)-1,o=Math.floor(e/this.DB),a=this.s<<r&this.DM;for(n=this.t-1;n>=0;--n)t[n+o+1]=this[n]>>i|a,a=(this[n]&s)<<r;for(n=o-1;n>=0;--n)t[n]=0;t[o]=a,t.t=this.t+o+1,t.s=this.s,t.clamp()},l.prototype.rShiftTo=function(e,t){t.s=this.s;var n=Math.floor(e/this.DB);if(n>=this.t)t.t=0;else{var r=e%this.DB,i=this.DB-r,s=(1<<r)-1;t[0]=this[n]>>r;for(var o=n+1;o<this.t;++o)t[o-n-1]|=(this[o]&s)<<i,t[o-n]=this[o]>>r;r>0&&(t[this.t-n-1]|=(this.s&s)<<i),t.t=this.t-n,t.clamp()}},l.prototype.subTo=function(e,t){for(var n=0,r=0,i=Math.min(e.t,this.t);n<i;)r+=this[n]-e[n],t[n++]=r&this.DM,r>>=this.DB;if(e.t<this.t){for(r-=e.s;n<this.t;)r+=this[n],t[n++]=r&this.DM,r>>=this.DB;r+=this.s}else{for(r+=this.s;n<e.t;)r-=e[n],t[n++]=r&this.DM,r>>=this.DB;r-=e.s}t.s=r<0?-1:0,r<-1?t[n++]=this.DV+r:r>0&&(t[n++]=r),t.t=n,t.clamp()},l.prototype.multiplyTo=function(e,t){var n=this.abs(),r=e.abs(),i=n.t;for(t.t=i+r.t;--i>=0;)t[i]=0;for(i=0;i<r.t;++i)t[i+n.t]=n.am(0,r[i],t,i,0,n.t);t.s=0,t.clamp(),this.s!=e.s&&l.ZERO.subTo(t,t)},l.prototype.squareTo=function(e){for(var t=this.abs(),n=e.t=2*t.t;--n>=0;)e[n]=0;for(n=0;n<t.t-1;++n){var r=t.am(n,t[n],e,2*n,0,1);(e[n+t.t]+=t.am(n+1,2*t[n],e,2*n+1,r,t.t-n-1))>=t.DV&&(e[n+t.t]-=t.DV,e[n+t.t+1]=1)}e.t>0&&(e[e.t-1]+=t.am(n,t[n],e,2*n,0,1)),e.s=0,e.clamp()},l.prototype.divRemTo=function(e,t,n){var r=e.abs();if(!(r.t<=0)){var i=this.abs();if(i.t<r.t)return null!=t&&t.fromInt(0),void(null!=n&&this.copyTo(n));null==n&&(n=h());var s=h(),o=this.s,a=e.s,c=this.DB-b(r[r.t-1]);c>0?(r.lShiftTo(c,s),i.lShiftTo(c,n)):(r.copyTo(s),i.copyTo(n));var u=s.t,d=s[u-1];if(0!=d){var f=d*(1<<this.F1)+(u>1?s[u-2]>>this.F2:0),p=this.FV/f,g=(1<<this.F1)/f,_=1<<this.F2,m=n.t,y=m-u,w=null==t?h():t;for(s.dlShiftTo(y,w),n.compareTo(w)>=0&&(n[n.t++]=1,n.subTo(w,n)),l.ONE.dlShiftTo(u,w),w.subTo(s,s);s.t<u;)s[s.t++]=0;for(;--y>=0;){var A=n[--m]==d?this.DM:Math.floor(n[m]*p+(n[m-1]+_)*g);if((n[m]+=s.am(0,A,n,y,0,u))<A)for(s.dlShiftTo(y,w),n.subTo(w,n);n[m]<--A;)n.subTo(w,n)}null!=t&&(n.drShiftTo(u,t),o!=a&&l.ZERO.subTo(t,t)),n.t=u,n.clamp(),c>0&&n.rShiftTo(c,n),o<0&&l.ZERO.subTo(n,n)}}},l.prototype.invDigit=function(){if(this.t<1)return 0;var e=this[0];if(!(1&e))return 0;var t=3&e;return(t=(t=(t=(t=t*(2-(15&e)*t)&15)*(2-(255&e)*t)&255)*(2-((65535&e)*t&65535))&65535)*(2-e*t%this.DV)%this.DV)>0?this.DV-t:-t},l.prototype.addTo=function(e,t){for(var n=0,r=0,i=Math.min(e.t,this.t);n<i;)r+=this[n]+e[n],t[n++]=r&this.DM,r>>=this.DB;if(e.t<this.t){for(r+=e.s;n<this.t;)r+=this[n],t[n++]=r&this.DM,r>>=this.DB;r+=this.s}else{for(r+=this.s;n<e.t;)r+=e[n],t[n++]=r&this.DM,r>>=this.DB;r+=e.s}t.s=r<0?-1:0,r>0?t[n++]=r:r<-1&&(t[n++]=this.DV+r),t.t=n,t.clamp()},l.prototype.toString=function(e){if(this.s<0)return"-"+this.negate().toString(e);var t;if(16==e)t=4;else if(8==e)t=3;else if(2==e)t=1;else if(32==e)t=5;else{if(4!=e)throw new Error("Only radix 2, 4, 8, 16, 32 are supported");t=2}var n,r=(1<<t)-1,i=!1,s="",o=this.t,a=this.DB-o*this.DB%t;if(o-- >0)for(a<this.DB&&(n=this[o]>>a)>0&&(i=!0,s=m(n));o>=0;)a<t?(n=(this[o]&(1<<a)-1)<<t-a,n|=this[--o]>>(a+=this.DB-t)):(n=this[o]>>(a-=t)&r,a<=0&&(a+=this.DB,--o)),n>0&&(i=!0),i&&(s+=m(n));return i?s:"0"},l.prototype.negate=function(){var e=h();return l.ZERO.subTo(this,e),e},l.prototype.abs=function(){return this.s<0?this.negate():this},l.prototype.compareTo=function(e){var t=this.s-e.s;if(0!=t)return t;var n=this.t;if(0!=(t=n-e.t))return this.s<0?-t:t;for(;--n>=0;)if(0!=(t=this[n]-e[n]))return t;return 0},l.prototype.bitLength=function(){return this.t<=0?0:this.DB*(this.t-1)+b(this[this.t-1]^this.s&this.DM)},l.prototype.mod=function(e){var t=h();return this.abs().divRemTo(e,null,t),this.s<0&&t.compareTo(l.ZERO)>0&&e.subTo(t,t),t},l.prototype.equals=function(e){return 0==this.compareTo(e)},l.prototype.add=function(e){var t=h();return this.addTo(e,t),t},l.prototype.subtract=function(e){var t=h();return this.subTo(e,t),t},l.prototype.multiply=function(e){var t=h();return this.multiplyTo(e,t),t},l.prototype.divide=function(e){var t=h();return this.divRemTo(e,t,null),t},l.prototype.modPow=function(e,t,n){var r,i=e.bitLength(),s=w(1),o=new A(t);if(i<=0)return s;r=i<18?1:i<48?3:i<144?4:i<768?5:6;var a=new Array,c=3,u=r-1,l=(1<<r)-1;if(a[1]=o.convert(this),r>1){var d=h();for(o.sqrTo(a[1],d);c<=l;)a[c]=h(),o.mulTo(d,a[c-2],a[c]),c+=2}var f,p,g=e.t-1,_=!0,m=h();for(i=b(e[g])-1;g>=0;){for(i>=u?f=e[g]>>i-u&l:(f=(e[g]&(1<<i+1)-1)<<u-i,g>0&&(f|=e[g-1]>>this.DB+i-u)),c=r;!(1&f);)f>>=1,--c;if((i-=c)<0&&(i+=this.DB,--g),_)a[f].copyTo(s),_=!1;else{for(;c>1;)o.sqrTo(s,m),o.sqrTo(m,s),c-=2;c>0?o.sqrTo(s,m):(p=s,s=m,m=p),o.mulTo(m,a[f],s)}for(;g>=0&&!(e[g]&1<<i);)o.sqrTo(s,m),p=s,s=m,m=p,--i<0&&(i=this.DB-1,--g)}var y=o.revert(s);return n(null,y),y},l.ZERO=w(0),l.ONE=w(1);var S=/^[89a-f]/i,E=function(){function e(e){this.N=new u("FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200CBBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF",16),this.g=new u("2",16),this.k=new u(this.hexHash(""+this.padHex(this.N)+this.padHex(this.g)),16),this.smallAValue=this.generateRandomSmallA(),this.getLargeAValue(function(){}),this.infoBits=s.hp.from("Caldera Derived Key","utf8"),this.poolName=e}var t=e.prototype;return t.getSmallAValue=function(){return this.smallAValue},t.getLargeAValue=function(e){var t=this;this.largeAValue?e(null,this.largeAValue):this.calculateA(this.smallAValue,function(n,r){n&&e(n,null),t.largeAValue=r,e(null,t.largeAValue)})},t.generateRandomSmallA=function(){var e=v(128).toString("hex");return new u(e,16)},t.generateRandomString=function(){return v(40).toString("base64")},t.getRandomPassword=function(){return this.randomPassword},t.getSaltDevices=function(){return this.SaltToHashDevices},t.getVerifierDevices=function(){return this.verifierDevices},t.generateHashDevice=function(e,t,n){var r=this;this.randomPassword=this.generateRandomString();var i=""+e+t+":"+this.randomPassword,s=this.hash(i),o=v(16).toString("hex");this.SaltToHashDevices=this.padHex(new u(o,16)),this.g.modPow(new u(this.hexHash(this.SaltToHashDevices+s),16),this.N,function(e,t){e&&n(e,null),r.verifierDevices=r.padHex(t),n(null,null)})},t.calculateA=function(e,t){var n=this;this.g.modPow(e,this.N,function(e,r){e&&t(e,null),r.mod(n.N).equals(u.ZERO)&&t(new Error("Illegal paramater. A mod N cannot be 0."),null),t(null,r)})},t.calculateU=function(e,t){return this.UHexHash=this.hexHash(this.padHex(e)+this.padHex(t)),new u(this.UHexHash,16)},t.hash=function(e){var t=new c.Sha256;t.update(e);var n=t.digestSync(),r=s.hp.from(n).toString("hex");return new Array(64-r.length).join("0")+r},t.hexHash=function(e){return this.hash(s.hp.from(e,"hex"))},t.computehkdf=function(e,t){var n=s.hp.concat([this.infoBits,s.hp.from(String.fromCharCode(1),"utf8")]),r=new c.Sha256(t);r.update(e);var i=r.digestSync(),o=new c.Sha256(i);return o.update(n),o.digestSync().slice(0,16)},t.getPasswordAuthenticationKey=function(e,t,n,r,i){var o=this;if(n.mod(this.N).equals(u.ZERO))throw new Error("B cannot be zero.");if(this.UValue=this.calculateU(this.largeAValue,n),this.UValue.equals(u.ZERO))throw new Error("U cannot be zero.");var a=""+this.poolName+e+":"+t,c=this.hash(a),l=new u(this.hexHash(this.padHex(r)+c),16);this.calculateS(l,n,function(e,t){e&&i(e,null);var n=o.computehkdf(s.hp.from(o.padHex(t),"hex"),s.hp.from(o.padHex(o.UValue),"hex"));i(null,n)})},t.calculateS=function(e,t,n){var r=this;this.g.modPow(e,this.N,function(i,s){i&&n(i,null),t.subtract(r.k.multiply(s)).modPow(r.smallAValue.add(r.UValue.multiply(e)),r.N,function(e,t){e&&n(e,null),n(null,t.mod(r.N))})})},t.getNewPasswordRequiredChallengeUserAttributePrefix=function(){return"userAttributes."},t.padHex=function(e){if(!(e instanceof u))throw new Error("Not a BigInteger");var t=e.compareTo(u.ZERO)<0,n=e.abs().toString(16);if(n=n.length%2!=0?"0"+n:n,n=S.test(n)?"00"+n:n,t){var r=n.split("").map(function(e){var t=15&~parseInt(e,16);return"0123456789ABCDEF".charAt(t)}).join("");(n=new u(r,16).add(u.ONE).toString(16)).toUpperCase().startsWith("FF8")&&(n=n.substring(2))}return n},e}(),I=function(){function e(e){this.jwtToken=e||"",this.payload=this.decodePayload()}var t=e.prototype;return t.getJwtToken=function(){return this.jwtToken},t.getExpiration=function(){return this.payload.exp},t.getIssuedAt=function(){return this.payload.iat},t.decodePayload=function(){var e=this.jwtToken.split(".")[1];try{return JSON.parse(s.hp.from(e,"base64").toString("utf8"))}catch(e){return{}}},e}();function T(e,t){return T=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},T(e,t)}var R=function(e){function t(t){var n=(void 0===t?{}:t).AccessToken;return e.call(this,n||"")||this}var n,r;return r=e,(n=t).prototype=Object.create(r.prototype),n.prototype.constructor=n,T(n,r),t}(I);function U(e,t){return U=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},U(e,t)}var D=function(e){function t(t){var n=(void 0===t?{}:t).IdToken;return e.call(this,n||"")||this}var n,r;return r=e,(n=t).prototype=Object.create(r.prototype),n.prototype.constructor=n,U(n,r),t}(I),P=function(){function e(e){var t=(void 0===e?{}:e).RefreshToken;this.token=t||""}return e.prototype.getToken=function(){return this.token},e}(),C="aws-amplify/5.0.4",k="undefined"!=typeof navigator&&"ReactNative"===navigator.product,N=function(){function e(e){var t=void 0===e?{}:e,n=t.IdToken,r=t.RefreshToken,i=t.AccessToken,s=t.ClockDrift;if(null==i||null==n)throw new Error("Id token and Access Token must be present.");this.idToken=n,this.refreshToken=r,this.accessToken=i,this.clockDrift=void 0===s?this.calculateClockDrift():s}var t=e.prototype;return t.getIdToken=function(){return this.idToken},t.getRefreshToken=function(){return this.refreshToken},t.getAccessToken=function(){return this.accessToken},t.getClockDrift=function(){return this.clockDrift},t.calculateClockDrift=function(){return Math.floor(new Date/1e3)-Math.min(this.accessToken.getIssuedAt(),this.idToken.getIssuedAt())},t.isValid=function(){var e=Math.floor(new Date/1e3)-this.clockDrift;return e<this.accessToken.getExpiration()&&e<this.idToken.getExpiration()},e}(),L=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],O=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],M=function(){function e(){}return e.prototype.getNowString=function(){var e=new Date,t=O[e.getUTCDay()],n=L[e.getUTCMonth()],r=e.getUTCDate(),i=e.getUTCHours();i<10&&(i="0"+i);var s=e.getUTCMinutes();s<10&&(s="0"+s);var o=e.getUTCSeconds();return o<10&&(o="0"+o),t+" "+n+" "+r+" "+i+":"+s+":"+o+" UTC "+e.getUTCFullYear()},e}(),V=function(){function e(e){var t=void 0===e?{}:e,n=t.Name,r=t.Value;this.Name=n||"",this.Value=r||""}var t=e.prototype;return t.getValue=function(){return this.Value},t.setValue=function(e){return this.Value=e,this},t.getName=function(){return this.Name},t.setName=function(e){return this.Name=e,this},t.toString=function(){return JSON.stringify(this)},t.toJSON=function(){return{Name:this.Name,Value:this.Value}},e}(),x={},F=function(){function e(){}return e.setItem=function(e,t){return x[e]=t,x[e]},e.getItem=function(e){return Object.prototype.hasOwnProperty.call(x,e)?x[e]:void 0},e.removeItem=function(e){return delete x[e]},e.clear=function(){return x={}},e}(),q=function(){function e(){try{this.storageWindow=window.localStorage,this.storageWindow.setItem("aws.cognito.test-ls",1),this.storageWindow.removeItem("aws.cognito.test-ls")}catch(e){this.storageWindow=F}}return e.prototype.getStorage=function(){return this.storageWindow},e}(),B="undefined"!=typeof navigator?k?"react-native":navigator.userAgent:"nodejs",$=function(){function e(e){if(null==e||null==e.Username||null==e.Pool)throw new Error("Username and Pool information are required.");this.username=e.Username||"",this.pool=e.Pool,this.Session=null,this.client=e.Pool.client,this.signInUserSession=null,this.authenticationFlowType="USER_SRP_AUTH",this.storage=e.Storage||(new q).getStorage(),this.keyPrefix="CognitoIdentityServiceProvider."+this.pool.getClientId(),this.userDataKey=this.keyPrefix+"."+this.username+".userData"}var t=e.prototype;return t.setSignInUserSession=function(e){this.clearCachedUserData(),this.signInUserSession=e,this.cacheTokens()},t.getSignInUserSession=function(){return this.signInUserSession},t.getUsername=function(){return this.username},t.getAuthenticationFlowType=function(){return this.authenticationFlowType},t.setAuthenticationFlowType=function(e){this.authenticationFlowType=e},t.initiateAuth=function(e,t){var n=this,r=e.getAuthParameters();r.USERNAME=this.username;var i=0!==Object.keys(e.getValidationData()).length?e.getValidationData():e.getClientMetadata(),s={AuthFlow:"CUSTOM_AUTH",ClientId:this.pool.getClientId(),AuthParameters:r,ClientMetadata:i};this.getUserContextData()&&(s.UserContextData=this.getUserContextData()),this.client.request("InitiateAuth",s,function(e,r){if(e)return t.onFailure(e);var i=r.ChallengeName,s=r.ChallengeParameters;return"CUSTOM_CHALLENGE"===i?(n.Session=r.Session,t.customChallenge(s)):(n.signInUserSession=n.getCognitoUserSession(r.AuthenticationResult),n.cacheTokens(),t.onSuccess(n.signInUserSession))})},t.authenticateUser=function(e,t){return"USER_PASSWORD_AUTH"===this.authenticationFlowType?this.authenticateUserPlainUsernamePassword(e,t):"USER_SRP_AUTH"===this.authenticationFlowType||"CUSTOM_AUTH"===this.authenticationFlowType?this.authenticateUserDefaultAuth(e,t):t.onFailure(new Error("Authentication flow type is invalid."))},t.authenticateUserDefaultAuth=function(e,t){var n,r,i=this,o=new E(this.pool.getUserPoolName()),a=new M,l={};null!=this.deviceKey&&(l.DEVICE_KEY=this.deviceKey),l.USERNAME=this.username,o.getLargeAValue(function(h,d){h&&t.onFailure(h),l.SRP_A=d.toString(16),"CUSTOM_AUTH"===i.authenticationFlowType&&(l.CHALLENGE_NAME="SRP_A");var f=0!==Object.keys(e.getValidationData()).length?e.getValidationData():e.getClientMetadata(),p={AuthFlow:i.authenticationFlowType,ClientId:i.pool.getClientId(),AuthParameters:l,ClientMetadata:f};i.getUserContextData(i.username)&&(p.UserContextData=i.getUserContextData(i.username)),i.client.request("InitiateAuth",p,function(l,h){if(l)return t.onFailure(l);var d=h.ChallengeParameters;i.username=d.USER_ID_FOR_SRP,i.userDataKey=i.keyPrefix+"."+i.username+".userData",n=new u(d.SRP_B,16),r=new u(d.SALT,16),i.getCachedDeviceKeyAndPassword(),o.getPasswordAuthenticationKey(i.username,e.getPassword(),n,r,function(e,n){e&&t.onFailure(e);var r=a.getNowString(),u=s.hp.concat([s.hp.from(i.pool.getUserPoolName(),"utf8"),s.hp.from(i.username,"utf8"),s.hp.from(d.SECRET_BLOCK,"base64"),s.hp.from(r,"utf8")]),l=new c.Sha256(n);l.update(u);var p=l.digestSync(),g=s.hp.from(p).toString("base64"),_={};_.USERNAME=i.username,_.PASSWORD_CLAIM_SECRET_BLOCK=d.SECRET_BLOCK,_.TIMESTAMP=r,_.PASSWORD_CLAIM_SIGNATURE=g,null!=i.deviceKey&&(_.DEVICE_KEY=i.deviceKey);var m=function(e,t){return i.client.request("RespondToAuthChallenge",e,function(n,r){return n&&"ResourceNotFoundException"===n.code&&-1!==n.message.toLowerCase().indexOf("device")?(_.DEVICE_KEY=null,i.deviceKey=null,i.randomPassword=null,i.deviceGroupKey=null,i.clearCachedDeviceKeyAndPassword(),m(e,t)):t(n,r)})},y={ChallengeName:"PASSWORD_VERIFIER",ClientId:i.pool.getClientId(),ChallengeResponses:_,Session:h.Session,ClientMetadata:f};i.getUserContextData()&&(y.UserContextData=i.getUserContextData()),m(y,function(e,n){return e?t.onFailure(e):i.authenticateUserInternal(n,o,t)})})})})},t.authenticateUserPlainUsernamePassword=function(e,t){var n=this,r={};if(r.USERNAME=this.username,r.PASSWORD=e.getPassword(),r.PASSWORD){var i=new E(this.pool.getUserPoolName());this.getCachedDeviceKeyAndPassword(),null!=this.deviceKey&&(r.DEVICE_KEY=this.deviceKey);var s=0!==Object.keys(e.getValidationData()).length?e.getValidationData():e.getClientMetadata(),o={AuthFlow:"USER_PASSWORD_AUTH",ClientId:this.pool.getClientId(),AuthParameters:r,ClientMetadata:s};this.getUserContextData(this.username)&&(o.UserContextData=this.getUserContextData(this.username)),this.client.request("InitiateAuth",o,function(e,r){return e?t.onFailure(e):n.authenticateUserInternal(r,i,t)})}else t.onFailure(new Error("PASSWORD parameter is required"))},t.authenticateUserInternal=function(e,t,n){var r=this,i=e.ChallengeName,o=e.ChallengeParameters;if("SMS_MFA"===i)return this.Session=e.Session,n.mfaRequired(i,o);if("SELECT_MFA_TYPE"===i)return this.Session=e.Session,n.selectMFAType(i,o);if("MFA_SETUP"===i)return this.Session=e.Session,n.mfaSetup(i,o);if("SOFTWARE_TOKEN_MFA"===i)return this.Session=e.Session,n.totpRequired(i,o);if("CUSTOM_CHALLENGE"===i)return this.Session=e.Session,n.customChallenge(o);if("NEW_PASSWORD_REQUIRED"===i){this.Session=e.Session;var a=null,c=null,u=[],l=t.getNewPasswordRequiredChallengeUserAttributePrefix();if(o&&(a=JSON.parse(e.ChallengeParameters.userAttributes),c=JSON.parse(e.ChallengeParameters.requiredAttributes)),c)for(var h=0;h<c.length;h++)u[h]=c[h].substr(l.length);return n.newPasswordRequired(a,u)}if("DEVICE_SRP_AUTH"===i)return this.Session=e.Session,void this.getDeviceResponse(n);this.signInUserSession=this.getCognitoUserSession(e.AuthenticationResult),this.challengeName=i,this.cacheTokens();var d=e.AuthenticationResult.NewDeviceMetadata;if(null==d)return n.onSuccess(this.signInUserSession);t.generateHashDevice(e.AuthenticationResult.NewDeviceMetadata.DeviceGroupKey,e.AuthenticationResult.NewDeviceMetadata.DeviceKey,function(i){if(i)return n.onFailure(i);var o={Salt:s.hp.from(t.getSaltDevices(),"hex").toString("base64"),PasswordVerifier:s.hp.from(t.getVerifierDevices(),"hex").toString("base64")};r.verifierDevices=o.PasswordVerifier,r.deviceGroupKey=d.DeviceGroupKey,r.randomPassword=t.getRandomPassword(),r.client.request("ConfirmDevice",{DeviceKey:d.DeviceKey,AccessToken:r.signInUserSession.getAccessToken().getJwtToken(),DeviceSecretVerifierConfig:o,DeviceName:B},function(t,i){return t?n.onFailure(t):(r.deviceKey=e.AuthenticationResult.NewDeviceMetadata.DeviceKey,r.cacheDeviceKeyAndPassword(),!0===i.UserConfirmationNecessary?n.onSuccess(r.signInUserSession,i.UserConfirmationNecessary):n.onSuccess(r.signInUserSession))})})},t.completeNewPasswordChallenge=function(e,t,n,r){var i=this;if(!e)return n.onFailure(new Error("New password is required."));var s=new E(this.pool.getUserPoolName()),o=s.getNewPasswordRequiredChallengeUserAttributePrefix(),a={};t&&Object.keys(t).forEach(function(e){a[o+e]=t[e]}),a.NEW_PASSWORD=e,a.USERNAME=this.username;var c={ChallengeName:"NEW_PASSWORD_REQUIRED",ClientId:this.pool.getClientId(),ChallengeResponses:a,Session:this.Session,ClientMetadata:r};this.getUserContextData()&&(c.UserContextData=this.getUserContextData()),this.client.request("RespondToAuthChallenge",c,function(e,t){return e?n.onFailure(e):i.authenticateUserInternal(t,s,n)})},t.getDeviceResponse=function(e,t){var n=this,r=new E(this.deviceGroupKey),i=new M,o={};o.USERNAME=this.username,o.DEVICE_KEY=this.deviceKey,r.getLargeAValue(function(a,l){a&&e.onFailure(a),o.SRP_A=l.toString(16);var h={ChallengeName:"DEVICE_SRP_AUTH",ClientId:n.pool.getClientId(),ChallengeResponses:o,ClientMetadata:t,Session:n.Session};n.getUserContextData()&&(h.UserContextData=n.getUserContextData()),n.client.request("RespondToAuthChallenge",h,function(t,o){if(t)return e.onFailure(t);var a=o.ChallengeParameters,l=new u(a.SRP_B,16),h=new u(a.SALT,16);r.getPasswordAuthenticationKey(n.deviceKey,n.randomPassword,l,h,function(t,r){if(t)return e.onFailure(t);var u=i.getNowString(),l=s.hp.concat([s.hp.from(n.deviceGroupKey,"utf8"),s.hp.from(n.deviceKey,"utf8"),s.hp.from(a.SECRET_BLOCK,"base64"),s.hp.from(u,"utf8")]),h=new c.Sha256(r);h.update(l);var d=h.digestSync(),f=s.hp.from(d).toString("base64"),p={};p.USERNAME=n.username,p.PASSWORD_CLAIM_SECRET_BLOCK=a.SECRET_BLOCK,p.TIMESTAMP=u,p.PASSWORD_CLAIM_SIGNATURE=f,p.DEVICE_KEY=n.deviceKey;var g={ChallengeName:"DEVICE_PASSWORD_VERIFIER",ClientId:n.pool.getClientId(),ChallengeResponses:p,Session:o.Session};n.getUserContextData()&&(g.UserContextData=n.getUserContextData()),n.client.request("RespondToAuthChallenge",g,function(t,r){return t?e.onFailure(t):(n.signInUserSession=n.getCognitoUserSession(r.AuthenticationResult),n.cacheTokens(),e.onSuccess(n.signInUserSession))})})})})},t.confirmRegistration=function(e,t,n,r){var i={ClientId:this.pool.getClientId(),ConfirmationCode:e,Username:this.username,ForceAliasCreation:t,ClientMetadata:r};this.getUserContextData()&&(i.UserContextData=this.getUserContextData()),this.client.request("ConfirmSignUp",i,function(e){return e?n(e,null):n(null,"SUCCESS")})},t.sendCustomChallengeAnswer=function(e,t,n){var r=this,i={};i.USERNAME=this.username,i.ANSWER=e;var s=new E(this.pool.getUserPoolName());this.getCachedDeviceKeyAndPassword(),null!=this.deviceKey&&(i.DEVICE_KEY=this.deviceKey);var o={ChallengeName:"CUSTOM_CHALLENGE",ChallengeResponses:i,ClientId:this.pool.getClientId(),Session:this.Session,ClientMetadata:n};this.getUserContextData()&&(o.UserContextData=this.getUserContextData()),this.client.request("RespondToAuthChallenge",o,function(e,n){return e?t.onFailure(e):r.authenticateUserInternal(n,s,t)})},t.sendMFACode=function(e,t,n,r){var i=this,o={};o.USERNAME=this.username,o.SMS_MFA_CODE=e;var a=n||"SMS_MFA";"SOFTWARE_TOKEN_MFA"===a&&(o.SOFTWARE_TOKEN_MFA_CODE=e),null!=this.deviceKey&&(o.DEVICE_KEY=this.deviceKey);var c={ChallengeName:a,ChallengeResponses:o,ClientId:this.pool.getClientId(),Session:this.Session,ClientMetadata:r};this.getUserContextData()&&(c.UserContextData=this.getUserContextData()),this.client.request("RespondToAuthChallenge",c,function(e,n){if(e)return t.onFailure(e);if("DEVICE_SRP_AUTH"!==n.ChallengeName){if(i.signInUserSession=i.getCognitoUserSession(n.AuthenticationResult),i.cacheTokens(),null==n.AuthenticationResult.NewDeviceMetadata)return t.onSuccess(i.signInUserSession);var r=new E(i.pool.getUserPoolName());r.generateHashDevice(n.AuthenticationResult.NewDeviceMetadata.DeviceGroupKey,n.AuthenticationResult.NewDeviceMetadata.DeviceKey,function(e){if(e)return t.onFailure(e);var o={Salt:s.hp.from(r.getSaltDevices(),"hex").toString("base64"),PasswordVerifier:s.hp.from(r.getVerifierDevices(),"hex").toString("base64")};i.verifierDevices=o.PasswordVerifier,i.deviceGroupKey=n.AuthenticationResult.NewDeviceMetadata.DeviceGroupKey,i.randomPassword=r.getRandomPassword(),i.client.request("ConfirmDevice",{DeviceKey:n.AuthenticationResult.NewDeviceMetadata.DeviceKey,AccessToken:i.signInUserSession.getAccessToken().getJwtToken(),DeviceSecretVerifierConfig:o,DeviceName:B},function(e,r){return e?t.onFailure(e):(i.deviceKey=n.AuthenticationResult.NewDeviceMetadata.DeviceKey,i.cacheDeviceKeyAndPassword(),!0===r.UserConfirmationNecessary?t.onSuccess(i.signInUserSession,r.UserConfirmationNecessary):t.onSuccess(i.signInUserSession))})})}else i.getDeviceResponse(t)})},t.changePassword=function(e,t,n,r){if(null==this.signInUserSession||!this.signInUserSession.isValid())return n(new Error("User is not authenticated"),null);this.client.request("ChangePassword",{PreviousPassword:e,ProposedPassword:t,AccessToken:this.signInUserSession.getAccessToken().getJwtToken(),ClientMetadata:r},function(e){return e?n(e,null):n(null,"SUCCESS")})},t.enableMFA=function(e){if(null==this.signInUserSession||!this.signInUserSession.isValid())return e(new Error("User is not authenticated"),null);var t=[];t.push({DeliveryMedium:"SMS",AttributeName:"phone_number"}),this.client.request("SetUserSettings",{MFAOptions:t,AccessToken:this.signInUserSession.getAccessToken().getJwtToken()},function(t){return t?e(t,null):e(null,"SUCCESS")})},t.setUserMfaPreference=function(e,t,n){if(null==this.signInUserSession||!this.signInUserSession.isValid())return n(new Error("User is not authenticated"),null);this.client.request("SetUserMFAPreference",{SMSMfaSettings:e,SoftwareTokenMfaSettings:t,AccessToken:this.signInUserSession.getAccessToken().getJwtToken()},function(e){return e?n(e,null):n(null,"SUCCESS")})},t.disableMFA=function(e){if(null==this.signInUserSession||!this.signInUserSession.isValid())return e(new Error("User is not authenticated"),null);this.client.request("SetUserSettings",{MFAOptions:[],AccessToken:this.signInUserSession.getAccessToken().getJwtToken()},function(t){return t?e(t,null):e(null,"SUCCESS")})},t.deleteUser=function(e,t){var n=this;if(null==this.signInUserSession||!this.signInUserSession.isValid())return e(new Error("User is not authenticated"),null);this.client.request("DeleteUser",{AccessToken:this.signInUserSession.getAccessToken().getJwtToken(),ClientMetadata:t},function(t){return t?e(t,null):(n.clearCachedUser(),e(null,"SUCCESS"))})},t.updateAttributes=function(e,t,n){var r=this;if(null==this.signInUserSession||!this.signInUserSession.isValid())return t(new Error("User is not authenticated"),null);this.client.request("UpdateUserAttributes",{AccessToken:this.signInUserSession.getAccessToken().getJwtToken(),UserAttributes:e,ClientMetadata:n},function(e,n){return e?t(e,null):r.getUserData(function(){return t(null,"SUCCESS",n)},{bypassCache:!0})})},t.getUserAttributes=function(e){if(null==this.signInUserSession||!this.signInUserSession.isValid())return e(new Error("User is not authenticated"),null);this.client.request("GetUser",{AccessToken:this.signInUserSession.getAccessToken().getJwtToken()},function(t,n){if(t)return e(t,null);for(var r=[],i=0;i<n.UserAttributes.length;i++){var s={Name:n.UserAttributes[i].Name,Value:n.UserAttributes[i].Value},o=new V(s);r.push(o)}return e(null,r)})},t.getMFAOptions=function(e){if(null==this.signInUserSession||!this.signInUserSession.isValid())return e(new Error("User is not authenticated"),null);this.client.request("GetUser",{AccessToken:this.signInUserSession.getAccessToken().getJwtToken()},function(t,n){return t?e(t,null):e(null,n.MFAOptions)})},t.createGetUserRequest=function(){return this.client.promisifyRequest("GetUser",{AccessToken:this.signInUserSession.getAccessToken().getJwtToken()})},t.refreshSessionIfPossible=function(e){var t=this;return void 0===e&&(e={}),new Promise(function(n){var r=t.signInUserSession.getRefreshToken();r&&r.getToken()?t.refreshSession(r,n,e.clientMetadata):n()})},t.getUserData=function(e,t){var n=this;if(null==this.signInUserSession||!this.signInUserSession.isValid())return this.clearCachedUserData(),e(new Error("User is not authenticated"),null);var r=this.getUserDataFromCache();if(r)if(this.isFetchUserDataAndTokenRequired(t))this.fetchUserData().then(function(e){return n.refreshSessionIfPossible(t).then(function(){return e})}).then(function(t){return e(null,t)}).catch(e);else try{return void e(null,JSON.parse(r))}catch(t){return this.clearCachedUserData(),void e(t,null)}else this.fetchUserData().then(function(t){e(null,t)}).catch(e)},t.getUserDataFromCache=function(){return this.storage.getItem(this.userDataKey)},t.isFetchUserDataAndTokenRequired=function(e){var t=(e||{}).bypassCache;return void 0!==t&&t},t.fetchUserData=function(){var e=this;return this.createGetUserRequest().then(function(t){return e.cacheUserData(t),t})},t.deleteAttributes=function(e,t){var n=this;if(null==this.signInUserSession||!this.signInUserSession.isValid())return t(new Error("User is not authenticated"),null);this.client.request("DeleteUserAttributes",{UserAttributeNames:e,AccessToken:this.signInUserSession.getAccessToken().getJwtToken()},function(e){return e?t(e,null):n.getUserData(function(){return t(null,"SUCCESS")},{bypassCache:!0})})},t.resendConfirmationCode=function(e,t){var n={ClientId:this.pool.getClientId(),Username:this.username,ClientMetadata:t};this.client.request("ResendConfirmationCode",n,function(t,n){return t?e(t,null):e(null,n)})},t.getSession=function(e,t){if(void 0===t&&(t={}),null==this.username)return e(new Error("Username is null. Cannot retrieve a new session"),null);if(null!=this.signInUserSession&&this.signInUserSession.isValid())return e(null,this.signInUserSession);var n="CognitoIdentityServiceProvider."+this.pool.getClientId()+"."+this.username,r=n+".idToken",i=n+".accessToken",s=n+".refreshToken",o=n+".clockDrift";if(this.storage.getItem(r)){var a=new D({IdToken:this.storage.getItem(r)}),c=new R({AccessToken:this.storage.getItem(i)}),u=new P({RefreshToken:this.storage.getItem(s)}),l=parseInt(this.storage.getItem(o),0)||0,h=new N({IdToken:a,AccessToken:c,RefreshToken:u,ClockDrift:l});if(h.isValid())return this.signInUserSession=h,e(null,this.signInUserSession);if(!u.getToken())return e(new Error("Cannot retrieve a new session. Please authenticate."),null);this.refreshSession(u,e,t.clientMetadata)}else e(new Error("Local storage is missing an ID Token, Please authenticate"),null)},t.refreshSession=function(e,t,n){var r=this,i=this.pool.wrapRefreshSessionCallback?this.pool.wrapRefreshSessionCallback(t):t,s={};s.REFRESH_TOKEN=e.getToken();var o="CognitoIdentityServiceProvider."+this.pool.getClientId(),a=o+".LastAuthUser";if(this.storage.getItem(a)){this.username=this.storage.getItem(a);var c=o+"."+this.username+".deviceKey";this.deviceKey=this.storage.getItem(c),s.DEVICE_KEY=this.deviceKey}var u={ClientId:this.pool.getClientId(),AuthFlow:"REFRESH_TOKEN_AUTH",AuthParameters:s,ClientMetadata:n};this.getUserContextData()&&(u.UserContextData=this.getUserContextData()),this.client.requestWithRetry("InitiateAuth",u,function(t,n){if(t)return"NotAuthorizedException"===t.code&&r.clearCachedUser(),i(t,null);if(n){var s=n.AuthenticationResult;return Object.prototype.hasOwnProperty.call(s,"RefreshToken")||(s.RefreshToken=e.getToken()),r.signInUserSession=r.getCognitoUserSession(s),r.cacheTokens(),i(null,r.signInUserSession)}})},t.cacheTokens=function(){var e="CognitoIdentityServiceProvider."+this.pool.getClientId(),t=e+"."+this.username+".idToken",n=e+"."+this.username+".accessToken",r=e+"."+this.username+".refreshToken",i=e+"."+this.username+".clockDrift",s=e+".LastAuthUser";this.storage.setItem(t,this.signInUserSession.getIdToken().getJwtToken()),this.storage.setItem(n,this.signInUserSession.getAccessToken().getJwtToken()),this.storage.setItem(r,this.signInUserSession.getRefreshToken().getToken()),this.storage.setItem(i,""+this.signInUserSession.getClockDrift()),this.storage.setItem(s,this.username)},t.cacheUserData=function(e){this.storage.setItem(this.userDataKey,JSON.stringify(e))},t.clearCachedUserData=function(){this.storage.removeItem(this.userDataKey)},t.clearCachedUser=function(){this.clearCachedTokens(),this.clearCachedUserData()},t.cacheDeviceKeyAndPassword=function(){var e="CognitoIdentityServiceProvider."+this.pool.getClientId()+"."+this.username,t=e+".deviceKey",n=e+".randomPasswordKey",r=e+".deviceGroupKey";this.storage.setItem(t,this.deviceKey),this.storage.setItem(n,this.randomPassword),this.storage.setItem(r,this.deviceGroupKey)},t.getCachedDeviceKeyAndPassword=function(){var e="CognitoIdentityServiceProvider."+this.pool.getClientId()+"."+this.username,t=e+".deviceKey",n=e+".randomPasswordKey",r=e+".deviceGroupKey";this.storage.getItem(t)&&(this.deviceKey=this.storage.getItem(t),this.randomPassword=this.storage.getItem(n),this.deviceGroupKey=this.storage.getItem(r))},t.clearCachedDeviceKeyAndPassword=function(){var e="CognitoIdentityServiceProvider."+this.pool.getClientId()+"."+this.username,t=e+".deviceKey",n=e+".randomPasswordKey",r=e+".deviceGroupKey";this.storage.removeItem(t),this.storage.removeItem(n),this.storage.removeItem(r)},t.clearCachedTokens=function(){var e="CognitoIdentityServiceProvider."+this.pool.getClientId(),t=e+"."+this.username+".idToken",n=e+"."+this.username+".accessToken",r=e+"."+this.username+".refreshToken",i=e+".LastAuthUser",s=e+"."+this.username+".clockDrift";this.storage.removeItem(t),this.storage.removeItem(n),this.storage.removeItem(r),this.storage.removeItem(i),this.storage.removeItem(s)},t.getCognitoUserSession=function(e){var t=new D(e),n=new R(e),r=new P(e);return new N({IdToken:t,AccessToken:n,RefreshToken:r})},t.forgotPassword=function(e,t){var n={ClientId:this.pool.getClientId(),Username:this.username,ClientMetadata:t};this.getUserContextData()&&(n.UserContextData=this.getUserContextData()),this.client.request("ForgotPassword",n,function(t,n){return t?e.onFailure(t):"function"==typeof e.inputVerificationCode?e.inputVerificationCode(n):e.onSuccess(n)})},t.confirmPassword=function(e,t,n,r){var i={ClientId:this.pool.getClientId(),Username:this.username,ConfirmationCode:e,Password:t,ClientMetadata:r};this.getUserContextData()&&(i.UserContextData=this.getUserContextData()),this.client.request("ConfirmForgotPassword",i,function(e){return e?n.onFailure(e):n.onSuccess("SUCCESS")})},t.getAttributeVerificationCode=function(e,t,n){if(null==this.signInUserSession||!this.signInUserSession.isValid())return t.onFailure(new Error("User is not authenticated"));this.client.request("GetUserAttributeVerificationCode",{AttributeName:e,AccessToken:this.signInUserSession.getAccessToken().getJwtToken(),ClientMetadata:n},function(e,n){return e?t.onFailure(e):"function"==typeof t.inputVerificationCode?t.inputVerificationCode(n):t.onSuccess("SUCCESS")})},t.verifyAttribute=function(e,t,n){if(null==this.signInUserSession||!this.signInUserSession.isValid())return n.onFailure(new Error("User is not authenticated"));this.client.request("VerifyUserAttribute",{AttributeName:e,Code:t,AccessToken:this.signInUserSession.getAccessToken().getJwtToken()},function(e){return e?n.onFailure(e):n.onSuccess("SUCCESS")})},t.getDevice=function(e){if(null==this.signInUserSession||!this.signInUserSession.isValid())return e.onFailure(new Error("User is not authenticated"));this.client.request("GetDevice",{AccessToken:this.signInUserSession.getAccessToken().getJwtToken(),DeviceKey:this.deviceKey},function(t,n){return t?e.onFailure(t):e.onSuccess(n)})},t.forgetSpecificDevice=function(e,t){if(null==this.signInUserSession||!this.signInUserSession.isValid())return t.onFailure(new Error("User is not authenticated"));this.client.request("ForgetDevice",{AccessToken:this.signInUserSession.getAccessToken().getJwtToken(),DeviceKey:e},function(e){return e?t.onFailure(e):t.onSuccess("SUCCESS")})},t.forgetDevice=function(e){var t=this;this.forgetSpecificDevice(this.deviceKey,{onFailure:e.onFailure,onSuccess:function(n){return t.deviceKey=null,t.deviceGroupKey=null,t.randomPassword=null,t.clearCachedDeviceKeyAndPassword(),e.onSuccess(n)}})},t.setDeviceStatusRemembered=function(e){if(null==this.signInUserSession||!this.signInUserSession.isValid())return e.onFailure(new Error("User is not authenticated"));this.client.request("UpdateDeviceStatus",{AccessToken:this.signInUserSession.getAccessToken().getJwtToken(),DeviceKey:this.deviceKey,DeviceRememberedStatus:"remembered"},function(t){return t?e.onFailure(t):e.onSuccess("SUCCESS")})},t.setDeviceStatusNotRemembered=function(e){if(null==this.signInUserSession||!this.signInUserSession.isValid())return e.onFailure(new Error("User is not authenticated"));this.client.request("UpdateDeviceStatus",{AccessToken:this.signInUserSession.getAccessToken().getJwtToken(),DeviceKey:this.deviceKey,DeviceRememberedStatus:"not_remembered"},function(t){return t?e.onFailure(t):e.onSuccess("SUCCESS")})},t.listDevices=function(e,t,n){if(null==this.signInUserSession||!this.signInUserSession.isValid())return n.onFailure(new Error("User is not authenticated"));var r={AccessToken:this.signInUserSession.getAccessToken().getJwtToken(),Limit:e};t&&(r.PaginationToken=t),this.client.request("ListDevices",r,function(e,t){return e?n.onFailure(e):n.onSuccess(t)})},t.globalSignOut=function(e){var t=this;if(null==this.signInUserSession||!this.signInUserSession.isValid())return e.onFailure(new Error("User is not authenticated"));this.client.request("GlobalSignOut",{AccessToken:this.signInUserSession.getAccessToken().getJwtToken()},function(n){return n?e.onFailure(n):(t.clearCachedUser(),e.onSuccess("SUCCESS"))})},t.signOut=function(e){var t=this;e&&"function"==typeof e?this.getSession(function(n,r){if(n)return e(n);t.revokeTokens(function(n){t.cleanClientData(),e(n)})}):this.cleanClientData()},t.revokeTokens=function(e){if(void 0===e&&(e=function(){}),"function"!=typeof e)throw new Error("Invalid revokeTokenCallback. It should be a function.");if(!this.signInUserSession)return e(new Error("User is not authenticated"));if(!this.signInUserSession.getAccessToken())return e(new Error("No Access token available"));var t=this.signInUserSession.getRefreshToken().getToken(),n=this.signInUserSession.getAccessToken();if(this.isSessionRevocable(n)&&t)return this.revokeToken({token:t,callback:e});e()},t.isSessionRevocable=function(e){if(e&&"function"==typeof e.decodePayload)try{return!!e.decodePayload().origin_jti}catch(e){}return!1},t.cleanClientData=function(){this.signInUserSession=null,this.clearCachedUser()},t.revokeToken=function(e){var t=e.token,n=e.callback;this.client.requestWithRetry("RevokeToken",{Token:t,ClientId:this.pool.getClientId()},function(e){if(e)return n(e);n()})},t.sendMFASelectionAnswer=function(e,t){var n=this,r={};r.USERNAME=this.username,r.ANSWER=e;var i={ChallengeName:"SELECT_MFA_TYPE",ChallengeResponses:r,ClientId:this.pool.getClientId(),Session:this.Session};this.getUserContextData()&&(i.UserContextData=this.getUserContextData()),this.client.request("RespondToAuthChallenge",i,function(r,i){return r?t.onFailure(r):(n.Session=i.Session,"SMS_MFA"===e?t.mfaRequired(i.ChallengeName,i.ChallengeParameters):"SOFTWARE_TOKEN_MFA"===e?t.totpRequired(i.ChallengeName,i.ChallengeParameters):void 0)})},t.getUserContextData=function(){return this.pool.getUserContextData(this.username)},t.associateSoftwareToken=function(e){var t=this;null!=this.signInUserSession&&this.signInUserSession.isValid()?this.client.request("AssociateSoftwareToken",{AccessToken:this.signInUserSession.getAccessToken().getJwtToken()},function(t,n){return t?e.onFailure(t):e.associateSecretCode(n.SecretCode)}):this.client.request("AssociateSoftwareToken",{Session:this.Session},function(n,r){return n?e.onFailure(n):(t.Session=r.Session,e.associateSecretCode(r.SecretCode))})},t.verifySoftwareToken=function(e,t,n){var r=this;null!=this.signInUserSession&&this.signInUserSession.isValid()?this.client.request("VerifySoftwareToken",{AccessToken:this.signInUserSession.getAccessToken().getJwtToken(),UserCode:e,FriendlyDeviceName:t},function(e,t){return e?n.onFailure(e):n.onSuccess(t)}):this.client.request("VerifySoftwareToken",{Session:this.Session,UserCode:e,FriendlyDeviceName:t},function(e,t){if(e)return n.onFailure(e);r.Session=t.Session;var i={};i.USERNAME=r.username;var s={ChallengeName:"MFA_SETUP",ClientId:r.pool.getClientId(),ChallengeResponses:i,Session:r.Session};r.getUserContextData()&&(s.UserContextData=r.getUserContextData()),r.client.request("RespondToAuthChallenge",s,function(e,t){return e?n.onFailure(e):(r.signInUserSession=r.getCognitoUserSession(t.AuthenticationResult),r.cacheTokens(),n.onSuccess(r.signInUserSession))})})},e}();function j(){}function K(e){var t="function"==typeof Map?new Map:void 0;return K=function(e){if(null===e||!function(e){try{return-1!==Function.toString.call(e).indexOf("[native code]")}catch(t){return"function"==typeof e}}(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,n)}function n(){return function(e,t,n){if(J())return Reflect.construct.apply(null,arguments);var r=[null];r.push.apply(r,t);var i=new(e.bind.apply(e,r));return n&&H(i,n.prototype),i}(e,arguments,W(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),H(n,e)},K(e)}function J(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(J=function(){return!!e})()}function H(e,t){return H=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},H(e,t)}function W(e){return W=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},W(e)}n(916),j.prototype.userAgent=C;var Q=function(e){function t(t,n,r,i){var s;return(s=e.call(this,t)||this).code=n,s.name=r,s.statusCode=i,s}return r=e,(n=t).prototype=Object.create(r.prototype),n.prototype.constructor=n,H(n,r),t;var n,r}(K(Error)),z=function(){function e(e,t,n){this.endpoint=t||"https://cognito-idp."+e+".amazonaws.com/";var r=(n||{}).credentials;this.fetchOptions=r?{credentials:r}:{}}var t=e.prototype;return t.promisifyRequest=function(e,t){var n=this;return new Promise(function(r,i){n.request(e,t,function(e,t){e?i(new Q(e.message,e.code,e.name,e.statusCode)):r(t)})})},t.requestWithRetry=function(e,t,n){var r,i,s=this;(r=[t],i=5e3,void 0===i&&(i=X),Z(function(t){return new Promise(function(n,r){s.request(e,t,function(e,t){e?r(e):n(t)})})},r,function(e){return function(t){var n=100*Math.pow(2,t)+100*Math.random();return!(n>e)&&n}}(i))).then(function(e){return n(null,e)}).catch(function(e){return n(e)})},t.request=function(e,t,n){var r,i,s,o={"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":"AWSCognitoIdentityProviderService."+e,"X-Amz-User-Agent":(r=j.category?" "+j.category:"",i=j.framework?" framework/"+j.framework:"",""+j.prototype.userAgent+r+i),"Cache-Control":"no-store"},a=Object.assign({},this.fetchOptions,{headers:o,method:"POST",mode:"cors",body:JSON.stringify(t)});fetch(this.endpoint,a).then(function(e){return s=e,e},function(e){if(e instanceof TypeError)throw new Error("Network error");throw e}).then(function(e){return e.json().catch(function(){return{}})}).then(function(e){if(s.ok)return n(null,e);var t=(e.__type||e.code).split("#").pop(),r=new Error(e.message||e.Message||null);return r.name=t,r.code=t,n(r)}).catch(function(e){if(s&&s.headers&&s.headers.get("x-amzn-errortype"))try{var t=s.headers.get("x-amzn-errortype").split(":")[0],r=new Error(s.status?s.status.toString():null);return r.code=t,r.name=t,r.statusCode=s.status,n(r)}catch(t){return n(e)}else e instanceof Error&&"Network error"===e.message&&(e.code="NetworkError");return n(e)})},e}(),G={debug:function(){}},Y=function(e){return e&&e.nonRetryable};function Z(e,t,n,r){if(void 0===r&&(r=1),"function"!=typeof e)throw Error("functionToRetry must be a function");return G.debug(e.name+" attempt #"+r+" with args: "+JSON.stringify(t)),e.apply(void 0,t).catch(function(i){if(G.debug("error on "+e.name,i),Y(i))throw G.debug(e.name+" non retryable error",i),i;var s=n(r,t,i);if(G.debug(e.name+" retrying in "+s+" ms"),!1!==s)return new Promise(function(e){return setTimeout(e,s)}).then(function(){return Z(e,t,n,r+1)});throw i})}var X=3e5,ee=function(){function e(e,t){var n=e||{},r=n.UserPoolId,i=n.ClientId,s=n.endpoint,o=n.fetchOptions,a=n.AdvancedSecurityDataCollectionFlag;if(!r||!i)throw new Error("Both UserPoolId and ClientId are required.");if(r.length>55||!/^[\w-]+_[0-9a-zA-Z]+$/.test(r))throw new Error("Invalid UserPoolId format.");var c=r.split("_")[0];this.userPoolId=r,this.clientId=i,this.client=new z(c,s,o),this.advancedSecurityDataCollectionFlag=!1!==a,this.storage=e.Storage||(new q).getStorage(),t&&(this.wrapRefreshSessionCallback=t)}var t=e.prototype;return t.getUserPoolId=function(){return this.userPoolId},t.getUserPoolName=function(){return this.getUserPoolId().split("_")[1]},t.getClientId=function(){return this.clientId},t.signUp=function(e,t,n,r,i,s){var o=this,a={ClientId:this.clientId,Username:e,Password:t,UserAttributes:n,ValidationData:r,ClientMetadata:s};this.getUserContextData(e)&&(a.UserContextData=this.getUserContextData(e)),this.client.request("SignUp",a,function(t,n){if(t)return i(t,null);var r={Username:e,Pool:o,Storage:o.storage},s={user:new $(r),userConfirmed:n.UserConfirmed,userSub:n.UserSub,codeDeliveryDetails:n.CodeDeliveryDetails};return i(null,s)})},t.getCurrentUser=function(){var e="CognitoIdentityServiceProvider."+this.clientId+".LastAuthUser",t=this.storage.getItem(e);if(t){var n={Username:t,Pool:this,Storage:this.storage};return new $(n)}return null},t.getUserContextData=function(e){if("undefined"!=typeof AmazonCognitoAdvancedSecurityData){var t=AmazonCognitoAdvancedSecurityData;if(this.advancedSecurityDataCollectionFlag){var n=t.getData(e,this.userPoolId,this.clientId);if(n)return{EncodedData:n}}return{}}},e}();n(596);class te extends Error{constructor(e,t){if(Array.isArray(e)&&e.length<=2){let n=e[1];if(e.length>2)for(let t=2;t<e.length&&"string"==typeof e[t];t++)n+=e[t];super((n||"Something went wrong.").trim()),this.name=t?.name||"SKAPI",this.code=t?.code||e[0]||"ERROR",t?.cause&&(this.cause=t.cause)}else super((e?.message||("string"==typeof e?e:"Something went wrong.")).trim()),"string"==typeof e?(this.name=t?.name||"SKAPI",this.code=t?.code||"ERROR",t?.cause&&(this.cause=t.cause)):e instanceof Error?(this.cause=e,this.name=e.name,e.hasOwnProperty("code")&&(this.code=e.code)):"object"==typeof e&&e?.code&&e?.message&&(this.name=t?.name||"SKAPI",this.code=t?.code||"ERROR",this.cause=e?.cause)}}const ne="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",re=BigInt(62);class ie{static hash(e){"string"!=typeof e&&(console.warn("coercing non-string value to empty string"),e="");const t=ie.sb(e);let n,r,i,s,o=1732584193,a=-271733879,c=-1732584194,u=271733878;for(let e=0;e<t.length;e+=16)n=o,r=a,i=c,s=u,o=ie.ff(o,a,c,u,t[e],7,-680876936),u=ie.ff(u,o,a,c,t[e+1],12,-389564586),c=ie.ff(c,u,o,a,t[e+2],17,606105819),a=ie.ff(a,c,u,o,t[e+3],22,-1044525330),o=ie.ff(o,a,c,u,t[e+4],7,-176418897),u=ie.ff(u,o,a,c,t[e+5],12,1200080426),c=ie.ff(c,u,o,a,t[e+6],17,-1473231341),a=ie.ff(a,c,u,o,t[e+7],22,-45705983),o=ie.ff(o,a,c,u,t[e+8],7,1770035416),u=ie.ff(u,o,a,c,t[e+9],12,-1958414417),c=ie.ff(c,u,o,a,t[e+10],17,-42063),a=ie.ff(a,c,u,o,t[e+11],22,-1990404162),o=ie.ff(o,a,c,u,t[e+12],7,1804603682),u=ie.ff(u,o,a,c,t[e+13],12,-40341101),c=ie.ff(c,u,o,a,t[e+14],17,-1502002290),a=ie.ff(a,c,u,o,t[e+15],22,1236535329),o=ie.gg(o,a,c,u,t[e+1],5,-165796510),u=ie.gg(u,o,a,c,t[e+6],9,-1069501632),c=ie.gg(c,u,o,a,t[e+11],14,643717713),a=ie.gg(a,c,u,o,t[e],20,-373897302),o=ie.gg(o,a,c,u,t[e+5],5,-701558691),u=ie.gg(u,o,a,c,t[e+10],9,38016083),c=ie.gg(c,u,o,a,t[e+15],14,-660478335),a=ie.gg(a,c,u,o,t[e+4],20,-405537848),o=ie.gg(o,a,c,u,t[e+9],5,568446438),u=ie.gg(u,o,a,c,t[e+14],9,-1019803690),c=ie.gg(c,u,o,a,t[e+3],14,-187363961),a=ie.gg(a,c,u,o,t[e+8],20,1163531501),o=ie.gg(o,a,c,u,t[e+13],5,-1444681467),u=ie.gg(u,o,a,c,t[e+2],9,-51403784),c=ie.gg(c,u,o,a,t[e+7],14,1735328473),a=ie.gg(a,c,u,o,t[e+12],20,-1926607734),o=ie.hh(o,a,c,u,t[e+5],4,-378558),u=ie.hh(u,o,a,c,t[e+8],11,-2022574463),c=ie.hh(c,u,o,a,t[e+11],16,1839030562),a=ie.hh(a,c,u,o,t[e+14],23,-35309556),o=ie.hh(o,a,c,u,t[e+1],4,-1530992060),u=ie.hh(u,o,a,c,t[e+4],11,1272893353),c=ie.hh(c,u,o,a,t[e+7],16,-155497632),a=ie.hh(a,c,u,o,t[e+10],23,-1094730640),o=ie.hh(o,a,c,u,t[e+13],4,681279174),u=ie.hh(u,o,a,c,t[e],11,-358537222),c=ie.hh(c,u,o,a,t[e+3],16,-722521979),a=ie.hh(a,c,u,o,t[e+6],23,76029189),o=ie.hh(o,a,c,u,t[e+9],4,-640364487),u=ie.hh(u,o,a,c,t[e+12],11,-421815835),c=ie.hh(c,u,o,a,t[e+15],16,530742520),a=ie.hh(a,c,u,o,t[e+2],23,-995338651),o=ie.ii(o,a,c,u,t[e],6,-198630844),u=ie.ii(u,o,a,c,t[e+7],10,1126891415),c=ie.ii(c,u,o,a,t[e+14],15,-1416354905),a=ie.ii(a,c,u,o,t[e+5],21,-57434055),o=ie.ii(o,a,c,u,t[e+12],6,1700485571),u=ie.ii(u,o,a,c,t[e+3],10,-1894986606),c=ie.ii(c,u,o,a,t[e+10],15,-1051523),a=ie.ii(a,c,u,o,t[e+1],21,-2054922799),o=ie.ii(o,a,c,u,t[e+8],6,1873313359),u=ie.ii(u,o,a,c,t[e+15],10,-30611744),c=ie.ii(c,u,o,a,t[e+6],15,-1560198380),a=ie.ii(a,c,u,o,t[e+13],21,1309151649),o=ie.ii(o,a,c,u,t[e+4],6,-145523070),u=ie.ii(u,o,a,c,t[e+11],10,-1120210379),c=ie.ii(c,u,o,a,t[e+2],15,718787259),a=ie.ii(a,c,u,o,t[e+9],21,-343485551),o=ie.ad(o,n),a=ie.ad(a,r),c=ie.ad(c,i),u=ie.ad(u,s);return ie.rh(o)+ie.rh(a)+ie.rh(c)+ie.rh(u)}static rh(e){let t="";for(let n=0;n<=3;n++)t+=ie.alphabet.charAt(e>>8*n+4&15)+ie.alphabet.charAt(e>>8*n&15);return t}static ad(e,t){const n=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(n>>16)<<16|65535&n}static rl(e,t){return e<<t|e>>>32-t}static cm(e,t,n,r,i,s){return ie.ad(ie.rl(ie.ad(ie.ad(t,e),ie.ad(r,s)),i),n)}static ff(e,t,n,r,i,s,o){return ie.cm(t&n|~t&r,e,t,i,s,o)}static gg(e,t,n,r,i,s,o){return ie.cm(t&r|n&~r,e,t,i,s,o)}static hh(e,t,n,r,i,s,o){return ie.cm(t^n^r,e,t,i,s,o)}static ii(e,t,n,r,i,s,o){return ie.cm(n^(t|~r),e,t,i,s,o)}static sb(e){let t;const n=1+(e.length+8>>6),r=new Array(16*n);for(t=0;t<16*n;t++)r[t]=0;for(t=0;t<e.length;t++)r[t>>2]|=e.charCodeAt(t)<<t%4*8;return r[t>>2]|=128<<t%4*8,r[16*n-2]=8*e.length,r}}function se(e){if(0===e)return ne[0];let t="";for(;e>0;)t=ne[e%62]+t,e=Math.floor(e/62);return t}function oe(e){return e.split("").reverse().reduce((e,t,n)=>e+ne.indexOf(t)*62**n,0)}function ae(e=6){let t="";let n=0;for(;n<e;)t+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".charAt(Math.floor(62*Math.random())),n+=1;return t}ie.alphabet="0123456789abcdef";const ce="undefined"!=typeof window&&void 0!==window.document,ue="undefined"!=typeof SubmitEvent,le="undefined"!=typeof HTMLFormElement;function he(e,t,n){let r={},i=[];function s(e){let t;try{t=JSON.stringify(e)}catch(e){throw new te("Invalid data type.",{code:"INVALID_REQUEST"})}return new Blob([t]).size}function o(e,r,i){if(t?.ignoreEmpty&&""===i)return;if(t?.nullIfEmpty&&""===i&&(i=null),"function"==typeof n){let e=n(r,i);void 0!==e&&(i=e)}let s=r.split("[").map(e=>{let t=e.replace("]",""),n=Number(t);return isNaN(n)||t.includes(".")?('"'===t[0]&&'"'===t[t.length-1]||"'"===t[0]&&"'"===t[t.length-1])&&(t=t.replace(/"/g,"").replace(/'/g,"")):t=n,t}),o=e;if("number"==typeof s[0])throw new te("Form key cannot start with an array index.",{code:"INVALID_REQUEST"});for(let e=0;e<s.length;e++){let t=s[e];if(e<s.length-1){if(void 0===o[t]){let n=s[e+1];o[t]="number"==typeof n?[]:{}}o=o[t]}else void 0===o[t]?o[t]=i:Array.isArray(o[t])?o[t].push(i):o[t]=[o[t],i]}}function a(e,t,n){if(n instanceof File)e.push({name:t,file:n});else if(n instanceof FileList&&n&&n.length>0)for(let r=0;r<=n.length-1;r++){let i=n.item(r);i&&e.push({name:t,file:i})}}let c=e=>{e.name&&("number"===e.type?e.value&&o(r,e.name,Number(e.value)):"checkbox"===e.type||"radio"===e.type?e.checked?""===e.value&&"checkbox"===e.type||"on"===e.value||"true"===e.value?o(r,e.name,!0):"false"===e.value?o(r,e.name,!1):e.value&&o(r,e.name,e.value):"checkbox"===e.type&&(""===e.value||"on"===e.value||"true"===e.value?o(r,e.name,!1):"false"===e.value&&o(r,e.name,!0)):"file"===e.type?e.files&&e.files.length>0&&a(i,e.name,e.files):o(r,e.name,e.value))};if(ce&&(e instanceof HTMLInputElement||e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement)){if(c(e),s(r)>2097152)throw new te("Data should not exceed 2MB",{code:"INVALID_REQUEST"});return{data:r,files:i}}if(ce&&e instanceof FormData){for(let t of e.entries()){let e=t[0],n=t[1];if(n instanceof File||n instanceof FileList)a(i,e,n);else if(n instanceof Blob){let t=n;if("application/json"===t.type)try{let n=JSON.parse(t.text());o(r,e,n)}catch(n){o(r,e,t)}}else o(r,e,n)}if(s(r)>2097152)throw new te("Data should not exceed 2MB",{code:"INVALID_REQUEST"});return{data:r,files:i}}if(ce&&ue&&e instanceof SubmitEvent&&(e=e.target),ce&&le&&e instanceof HTMLFormElement){let t=e.querySelectorAll("input"),n=e.querySelectorAll("select"),a=e.querySelectorAll("textarea");for(let e=0;e<n.length;e++){let t=n[e];t.name&&o(r,t.name,t.value)}for(let e=0;e<a.length;e++){let t=a[e];t.name&&o(r,t.name,t.value)}for(let e=0;e<t.length;e++)c(t[e]);if(s(r)>2097152)throw new te("Data should not exceed 2MB",{code:"INVALID_REQUEST"});return{data:r,files:i}}if(s(e)>2097152)throw new te("Data should not exceed 2MB",{code:"INVALID_REQUEST"});return{data:e,files:i}}function de(e){let t={};for(let n in e){let r=e[n],i={auth_time:"log",sub:"user_id"};if(!["aud","cognito:username","event_id","exp","iat","iss","jti","origin_jti","secret_key","token_use"].includes(n))if(i[n])t[i[n]]=r;else if(n.includes("custom:"))t[n.replace("custom:","")]=r;else if("address"===n){let e=r;if(e&&"object"==typeof e&&Object.keys(e).length){if(e?.formatted)try{t[n]=JSON.parse(e.formatted)}catch(r){t[n]=e.formatted}}else t[n]=e}else t[n]=r}for(let e of["address_public","birthdate_public","email_public","gender_public","phone_number_public","access_group"])e.includes("_public")?t.hasOwnProperty(e.split("_")[0])?t[e]=!!t.hasOwnProperty(e)&&!!Number(t[e]):delete t[e]:t[e]=t.hasOwnProperty(e)?Number(t[e]):0;for(let e of["email","phone_number"])t.hasOwnProperty(e)?t[e+"_verified"]=!0===t[e+"_verified"]:delete t[e+"_verified"];return t}function fe(e){if(7===(e=function(e){const t=String(e);if(!t.startsWith("s1_"))return t;const n=function(e,t=!1){const n=String(e).replace(/-/g,"+").replace(/_/g,"/"),r=n.length%4?"=".repeat(4-n.length%4):"",i=Buffer.from(n+r,"base64");return t?JSON.parse(i.toString("utf8")):i}(t.slice(3));if(n.length<21)throw new Error("INVALID_PARAMETER: Corrupt compressed token.");const r=n[0];if(1!==r)throw new Error(`INVALID_PARAMETER: Unsupported token version: ${r}`);const i=n[1],s=n[2],o=5+n[3],a=o+n[4];if(n.length!==a+16)throw new Error("INVALID_PARAMETER: Corrupt compressed token length.");return`${_e(ye(n.subarray(5,o)),i)}-${_e(ye(n.subarray(o,a)),s)}-${function(e){const t=Buffer.from(e).toString("hex");return[t.slice(0,8),t.slice(8,12),t.slice(12,16),t.slice(16,20),t.slice(20)].join("-")}(n.subarray(a,a+16))}`}(e)).split("-").length){const t=e.split("-");let n,r;try{n=["us31","us72","ap51","ap22","ap41","eu71","ap21","us32","us71","af51","ap31","ap43","ap23","ap42","ca01","eu01","eu72","eu51","eu73","eu11","me51","sa31"][oe(t[1][0])],r=t.slice(2).join("-")}catch(e){throw new Error("INVALID_PARAMETER: Service ID is invalid.")}if(!n)throw new Error("INVALID_PARAMETER: Service ID is invalid.");return{service:n+t[0]+t[1].slice(1),owner:r}}return{service:e,owner:""}}function pe(e,t){const n=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f","g","h","i","j","k","l"][["us31","us72","ap51","ap22","ap41","eu71","ap21","us32","us71","af51","ap31","ap43","ap23","ap42","ca01","eu01","eu72","eu51","eu73","eu11","me51","sa31"].indexOf(e.slice(0,4))];return function(e){const t=String(e).match(/^([0-9A-Za-z]+)-([0-9A-Za-z]+)-([0-9a-fA-F-]{36})$/);if(!t)throw new Error("INVALID_PARAMETER: Input must match <base62>-<base62>-<uuid>.");const[,n,r,i]=t,s=ge(n),o=ge(r),a=me(s),c=me(o),u=function(e){const t=String(e).replace(/-/g,"");if(!/^[0-9a-fA-F]{32}$/.test(t))throw new Error("INVALID_PARAMETER: Invalid UUID format.");return Buffer.from(t,"hex")}(i);if(n.length>255||r.length>255||a.length>255||c.length>255)throw new Error("INVALID_PARAMETER: Input parts are too long to encode.");return`s1_${function(e){if(Buffer)return Buffer.from(e).toString("base64");let t="";const n=new Uint8Array(e);for(let e=0;e<n.length;e+=32768){const r=n.subarray(e,e+32768);t+=String.fromCharCode.apply(null,Array.from(r))}if("function"==typeof btoa)return btoa(t);throw new Error("No base64 encoder available in this environment.")}(Buffer.concat([Buffer.from([1,n.length,r.length,a.length,c.length]),a,c,u]))}`}(`${e.slice(4,-4)}-${n}${e.slice(-4)}-${t}`)}function ge(e){let t=0n;for(const n of e){const e=ne.indexOf(n);if(e<0)throw new Error(`INVALID_PARAMETER: Invalid base62 character: ${n}`);t=t*re+BigInt(e)}return t}function _e(e,t=1){if(e<0n)throw new Error("INVALID_PARAMETER: Negative values are not supported.");if(0n===e)return"0".repeat(Math.max(1,t));let n="",r=e;for(;r>0n;){const e=Number(r%re);n=ne[e]+n,r/=re}return n.length<t&&(n="0".repeat(t-n.length)+n),n}function me(e){if(0n===e)return Buffer.from([0]);const t=[];let n=e;for(;n>0n;)t.push(Number(0xffn&n)),n>>=8n;return t.reverse(),Buffer.from(t)}function ye(e){let t=0n;for(const n of e)t=(t<<8n)+BigInt(n);return t}function we(e,t,n=[],r=null){function i(e){return e&&"object"==typeof e&&!Array.isArray(e)&&Object.keys(e).length}function s(e){return Array.isArray(e)&&e.length}if(null===r&&!i(t))throw'Argument "struct" is required.';let o=null!==r?` in key "${r}" is invalid.`:". Parameter should be type <object>.";if(s(t)){let i="";t.forEach(e=>{["string","number","boolean","object","array"].includes(e)?i+=`Type<${e}>, `:"function"!=typeof e&&(i+=JSON.stringify(e,null,2)+", ")}),i=i?" Should be: "+i.slice(0,-2):"";let s,a=!1,c="";for(let i of t)try{s=we(e,i,n,r),a=!0;break}catch(e){c="function"==typeof i?e?.message||e:"",a=!1}if(!a)throw c||`Invalid type "${typeof e}"${o}${i}.`;return s}if(i(e)){if(i(t))for(let i in t){let o=(null===r?"":r)+(null!==r?"["+i+"]":i);if(!e.hasOwnProperty(i)){if(n.includes(o))throw`Key "${o}" is required.`;s(t[i])&&"function"==typeof t[i][t[i].length-1]&&(e[i]=t[i][t[i].length-1]())}}if("object"===t)return e;if("function"==typeof t)return t(e);for(let i in e){let o=(null===r?"":r)+(null!==r?"["+i+"]":i);if(s(t)||t.hasOwnProperty(i))if(s(e[i])){if("array"===t[i])continue;if("function"==typeof t[i]){e[i]=t[i](e[i]);continue}for(let r=0;r<e[i].length;r++)e[i][r]=we(e[i][r],t[i],n,o+`[${r}]`)}else e[i]=we(e[i],t[i],n,o)}return e}if("function"==typeof t)return t(e);if("array"===t&&Array.isArray(e)||t===typeof e||e===t)return e;if(null==e||(a=e)&&"object"==typeof a&&!Array.isArray(a)&&!Object.keys(a).length)return e;var a;throw`Invalid type "${typeof e}"${o} Should be: ${["string","number","boolean","object","array"].includes(t)?`Type<${t}>`:JSON.stringify(t,null,2)}`}const be={UserId:function(e,t="User ID"){if(!e)throw new te(`${t} is empty.`,{code:"INVALID_PARAMETER"});if("string"!=typeof e)throw new te(`${t} should be type: string.`,{code:"INVALID_PARAMETER"});if(!e.match(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i))throw new te(`${t} is invalid.`,{code:"INVALID_PARAMETER"});return e},PhoneNumber:function(e){if(e&&("string"!=typeof e||"+"!==e.charAt(0)||isNaN(Number(e.substring(1)))))throw new te('"phone_number" is invalid. The format should be "+00123456789". Type: string.',{code:"INVALID_PARAMETER"});return e||""},Birthdate:function(e){if(e){if("string"!=typeof e)throw new te('"birthdate" is invalid. The format should be "yyyy-mm-dd". Type: string.',{code:"INVALID_PARAMETER"});{let t=new RegExp(/([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))/);if(10!==e.length||3!==e.split("-").length||!t.test(e))throw new te('"birthdate" is invalid. The format should be "yyyy-mm-dd". Type: string.',{code:"INVALID_PARAMETER"})}}return e||""},Password:function(e){if(!e)throw new te('"password" is required.',{code:"INVALID_PARAMETER"});if("string"!=typeof e)throw new te('"password" should be type: string.',{code:"INVALID_PARAMETER"});if(e.length<6)throw new te('"password" should be at least 6 characters.',{code:"INVALID_PARAMETER"});if(e.length>60)throw new te('"password" can be up to 60 characters max.',{code:"INVALID_PARAMETER"});return e},Email:function(e,t="email"){if(!e)throw new te(`"${t}" is required.`,{code:"INVALID_PARAMETER"});if("string"!=typeof e)throw new te(`"${t}"should be type: string.`,{code:"INVALID_PARAMETER"});if(e.length<5)throw new te(`"${t}" should be at least 5 characters.`,{code:"INVALID_PARAMETER"});if(/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/.test(e)&&(e=e.trim()).split("@")[1].split(".").length>=2)return e.toLowerCase();throw new te(`"${e}" is an invalid email.`,{code:"INVALID_PARAMETER"})},Url:function(e){const t="undefined"!=typeof window,n=(()=>{let e=t&&window.location.origin||null;return e&&"/"===e.slice(-1)&&(e=e.slice(0,-1)),e})();let r=e=>{if("string"==typeof e){if("*"===e)return"*";{let r,i=e.trim();if("/"===i[0]&&n){if("file:"===n.slice(0,5))throw new te(`"${e}" is an invalid url. Relative URL does not work on local file system. Use full URL string.`,{code:"INVALID_PARAMETER"});i=n+i}else if("."===i[0]&&n){if("file:"===n.slice(0,5))throw new te(`"${e}" is an invalid url. Relative URL does not work on local file system. Use full URL string.`,{code:"INVALID_PARAMETER"});let r=t?window.location.href.split("?")[0]:"";"/"!==r.slice(-1)&&(r+="/"),i=r+i.slice(1)}try{r=new URL(i)}catch(t){throw new te(`"${e}" is an invalid url.`,{code:"INVALID_PARAMETER"})}if(r.protocol)return r.href}}throw new te(`"${e}" is an invalid url.`,{code:"INVALID_PARAMETER"})};return Array.isArray(e)?e.map(e=>r(e)):r(e)},specialChars:function(e,t="parameter",n=!1,r=!1){let i=e=>{if("string"!=typeof e)throw new te(`${t} should be type: <string | string[]>.`,{code:"INVALID_PARAMETER"});if(!r&&e.includes(" "))throw new te(`${t} should not have whitespace.`,{code:"INVALID_PARAMETER"});if(!n&&e.includes("."))throw new te(`${t} should not have periods.`,{code:"INVALID_PARAMETER"});if(/[!#$%&*{};'"|<>\/~]/.test(e))throw new te(`${t} should not have special characters. Allowed special characters are: [ \\ ] ^ _ \` : ; < = > ? @ ( ) + , -`,{code:"INVALID_PARAMETER"})};if(Array.isArray(e))for(let t of e)i(t);else i(e);return e},Params:function(e,t,n=[],r){let i=he(e,r).data;t.service="string",t.owner="string";let s={};for(let e in t)if(i&&"object"==typeof i&&!Array.isArray(i)&&i.hasOwnProperty(e))if("function"==typeof i[e])s[e]=i[e];else try{s[e]=JSON.parse(JSON.stringify(i[e]))}catch(t){s[e]=i[e]}try{return we(s,t,n)}catch(e){throw new te(e,{code:"INVALID_PARAMETER"})}},checkParams:we};let Ae=null;function ve(e){let t={tkid:"ticket_id",cond:"condition",stmp:"timestamp",actn:"action",cnt:"count",ttl:"time_to_live",plch:"placeholder",hash:"hash",desc:"description",pmc:"limit_per_user"},n={};for(let r in e)if("tkid"===r){let t=e[r].split("#");if(1===t.length){n.ticket_id=t[0];continue}n.ticket_id=t[1],n.consume_id=t[2],n.user_id=t[3];let i=t[2].slice(-4);if(n.is_test=":CHK"===i,!e.stmp){let e=t[2].slice(0,-4);/^[0-9]+$/.test(e)?n.timestamp=parseInt(e,10):n.timestamp=oe(t[2].slice(0,-4))}}else t[r]?n[t[r]]=e[r]:n[r]=e[r];return n}async function Se(e){if(!e.ticket_id)throw new te("Ticket ID is required.",{code:"INVALID_PARAMETER"});if(!e.method)throw new te('Method is required. Should be either "GET" or "POST"',{code:"INVALID_PARAMETER"});let t=e.ticket_id;return await this.__connection,ve(await ht.bind(this)(`https://${this.service.slice(0,4)}.${this.customApiDomain}/auth/consume/${this.service}/${this.owner}/${t}`,e?.data||{},{method:e.method,auth:!!e?.auth}))}async function Ee(e,t){await this.__connection;let n=await ht.bind(this)("ticket",Object.assign({exec:"list"},e||{}),{auth:!0,fetchOptions:t});return n.list=n.list.map(ve),n}async function Ie(e,t){await this.__connection;let n=await ht.bind(this)("ticket",Object.assign({exec:"consumed"},e||{}),{auth:!0,fetchOptions:t});return n.list=n.list.map(ve),n}async function Te(e){return ht.bind(this)("register-ticket",Object.assign({exec:"reg"},e),{auth:!0})}async function Re(e){return ht.bind(this)("register-ticket",Object.assign({exec:"unreg"},e),{auth:!0})}async function Ue(){if(await this.__connection,this.session){const e=Math.floor(Date.now()/1e3),t=this.session.getIdToken().getExpiration();if(t<e){this.log("request:requesting new token",null);try{await Pe.bind(this)().getSession({refreshToken:!0}),this.log("request:received new tokens",{exp:this.session?.idToken?.payload?.exp,currentTime:e,expiresIn:t-e,token:this.session?.accessToken?.jwtToken,refreshToken:this.session?.refreshToken?.token})}catch(e){throw this.log("request:new token error",e),new te("User login is required.",{code:"INVALID_REQUEST"})}}else this.log("request:tokens",{exp:this.session.idToken.payload.exp,currentTime:e,expiresIn:t-e,token:this.session.accessToken.jwtToken,refreshToken:this.session.refreshToken.token});return this.session?.idToken?.jwtToken}throw this.log("request:no session",null),Me.bind(this)(),new te("User login is required.",{code:"INVALID_REQUEST"})}function De(e,t){return new Promise((n,r)=>{t.refreshSession(e.getRefreshToken(),(e,t)=>{this.log("getSession:refreshSessionCallback",{refreshErr:e,refreshedSession:t}),e?(Me.bind(this)(),r(e)):t.isValid()?n(t):(Me.bind(this)(),r(new te("Invalid session.",{code:"INVALID_REQUEST"})))})})}function Pe(){if(!this.userPool)throw new te("User pool is missing",{code:"INVALID_REQUEST"});const e=()=>{let e=de(Ae.getSignInUserSession().getIdToken().payload||null);return this.log("normalized user attribute",e),this.__user=e,e},t=async t=>new Promise((n,r)=>{this.log("getSession:option",t);let{refreshToken:i=!1,skipUserUpdateEventTrigger:s=!1}=t||{};if(i&&s&&(s=!1),Ae=this.userPool.getCurrentUser(),!Ae)return this.log("getSession:cognitoUser",Ae),Me.bind(this)(),void r(null);let o=t=>{let n=t.getIdToken().payload;if(this.log("getSession:respond:sessionAttribute",n),n["custom:service"]!==this.service)throw this.log("getSession:respond","invalid service, signing out"),Me.bind(this)(),new te("Invalid session.",{code:"INVALID_REQUEST"});return this.session=t,e(),s||this._runOnUserUpdateListeners(this.user),this.session};Ae.getSession((e,t)=>{if(this.log("getSession:getSessionCallback",{err:e,session:t}),!t)return Me.bind(this)(),void r(new te("Current session does not exist.",{code:"INVALID_REQUEST"}));if(e)return void De.bind(this)(t,Ae).then(e=>n(o(e))).catch(r);const s=Math.floor(Date.now()/1e3),a=t.getIdToken(),c=a.getExpiration(),u=c<s;if(this.log("getSession:currentTime",s),this.log("getSession:idTokenExp",c),this.log("getSession:isExpired",u),this.log("getSession:existingBearerToken",this.bearerToken),this.bearerToken=a.getJwtToken(),u||i||!t.isValid())De.bind(this)(t,Ae).then(e=>n(o(e))).catch(r);else try{n(o(t))}catch(e){r(e)}})}),n=(e,t)=>{let n=t||e.includes(this.service+"-")?e:this.service+"-"+ie.hash(e);return{cognitoUser:new $({Username:n,Pool:this.userPool}),cognitoUsername:n}};return{getSession:t,authenticateUser:(e,r,s=!1,o=!1)=>new Promise((a,c)=>{this.__request_signup_confirmation=null,this.__disabledAccount=null;let u=n(e,s),l=u.cognitoUsername,h=new i({Username:l,Password:r});u.cognitoUser.authenticateUser(h,{newPasswordRequired:(e,n)=>{this.__disabledAccount=null,this.__request_signup_confirmation=l,"PASS"===e["custom:signup_ticket"]||"MEMBER"===e["custom:signup_ticket"]||"OIDPASS"===e["custom:signup_ticket"]?u.cognitoUser.completeNewPasswordChallenge(r,{},{onSuccess:e=>{Ae=u.cognitoUser,t().then(e=>a(this.user))},onFailure:e=>{c(new te(e.message||"Failed to authenticate user.",{code:e.code}))}}):c(new te("User's signup confirmation is required.",{code:"SIGNUP_CONFIRMATION_NEEDED"}))},onSuccess:e=>t({skipUserUpdateEventTrigger:!0}).then(e=>{this.__disabledAccount=null,this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user),a(this.user)}),onFailure:e=>{let t=[],{parsed:n,code:r}=Ce(e),i="string"==typeof e?.message?e.message:"";if("NotAuthorizedException"===r?i.includes("User is disabled.")?(this.__disabledAccount=l,t=["This account is disabled.","USER_IS_DISABLED"]):t=o?["The account already exists.","ACCOUNT_EXISTS"]:["Incorrect username or password.","INCORRECT_USERNAME_OR_PASSWORD"]:"UserNotFoundException"===r?t=["Incorrect username or password.","INCORRECT_USERNAME_OR_PASSWORD"]:"UserNotConfirmedException"===r?(this.__request_signup_confirmation=l,t=["User's signup confirmation is required.","SIGNUP_CONFIRMATION_NEEDED"]):"TooManyRequestsException"!==r&&"LimitExceededException"!==r||(t=["Too many attempts. Please try again later.","REQUEST_EXCEED"]),"SIGNUP_CONFIRMATION_NEEDED"===n.code&&(this.__request_signup_confirmation=l),t.length){let n=t[1],r=t[0];c(new te(r,{code:n,cause:e}))}else c(n)}})}),createCognitoUser:n,signup:(e,t,n)=>new Promise((r,i)=>{this.userPool.signUp(e,t,n,null,(e,t)=>{if(e){let{parsed:t,code:n}=Ce(e),r=[];return"UsernameExistsException"===n?r=["The account already exists.","EXISTS"]:"InvalidPasswordException"===n?r=["Invalid password. Password must be at least 6 characters.","INVALID_PARAMETER"]:"InvalidParameterException"===n?r=[t.message||"Invalid parameter.","INVALID_PARAMETER"]:"TooManyRequestsException"===n||"LimitExceededException"===n?r=["Too many attempts. Please try again later.","REQUEST_EXCEED"]:"CodeDeliveryFailureException"===n?r=["Failed to deliver verification code.","CODE_DELIVERY_FAILURE"]:"UserLambdaValidationException"===n&&(r=[t.message||"Signup validation failed.","INVALID_REQUEST"]),void(r.length?i(new te(r[0],{code:r[1],cause:e})):i(t))}r(t)})})}}function Ce(e){let t="string"==typeof e?.code&&e.code.trim()?e.code.trim():"ERROR",n=(("string"==typeof e?.message?e.message:"string"==typeof e?e:"An error occurred.")||"An error occurred.").trim();n||(n="An error occurred.");let r=n.match(/#([A-Za-z0-9_]+)\s*:\s*([\s\S]+)/),i=r?.[1]?.trim()||t,s=r?.[2]?.trim()||n;return{parsed:new te(s,{code:i,cause:e}),code:t}}async function ke(e){await this.__authConnection;let t=e?.refreshToken||!1;if(!t)return this.user;try{return await Pe.bind(this)().getSession(Object.assign({skipUserUpdateEventTrigger:!t,refreshToken:t},e)),this.user}catch(e){return null}}async function Ne(e){await this.__connection,e=be.Params(e,{token:"string",id:"string",merge:e=>{if(void 0===e)return!1;if("string"==typeof e)return[e];if(Array.isArray(e))for(let t of e)if("string"!=typeof t)throw new te('"merge" array items should be type: <string>.',{code:"INVALID_PARAMETER"});if("boolean"!=typeof e&&!Array.isArray(e))throw new te('"merge" should be type: <boolean | string[]>.',{code:"INVALID_PARAMETER"});return e}});let t=await ht.bind(this)("openid-logger",e),n=t.logger.split("#"),r=this.service+"-"+n[0],i=n[1];return{userProfile:await Pe.bind(this)().authenticateUser(r,i,!0,!0),openid:t.openid}}async function Le(e){await this.__authConnection,this.log("loginWithToken:params",e);const t=function(e){const t=e.split(".");if(3!==t.length)throw new Error("Invalid JWT format");const n=function(e){const t="undefined"!=typeof globalThis?globalThis:void 0;if(t?.Buffer)return t.Buffer.from(e,"base64").toString("utf8");if("function"==typeof atob){const t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return"undefined"!=typeof TextDecoder?(new TextDecoder).decode(n):t}throw new Error("No base64 decoder available in this environment")}(t[1].replace(/-/g,"+").replace(/_/g,"/"));return JSON.parse(n)}((e=be.Params(e,{idToken:"string",accessToken:"string",refreshToken:"string"},["idToken"])).idToken);if(this.log("loginWithToken:idTokenPayload",t),t["custom:service"]!==this.service)throw new te("Token does not belong to this service.",{code:"INVALID_REQUEST"});const n=Math.floor(Date.now()/1e3);if(t.exp&&t.exp<n)throw new te("Token has expired.",{code:"INVALID_REQUEST"});if(this.__user=de(t),this.session=null,e.accessToken&&e.refreshToken)try{if(this.session=new N({IdToken:new D({IdToken:e.idToken}),AccessToken:new R({AccessToken:e.accessToken}),RefreshToken:new P({RefreshToken:e.refreshToken})}),this.log("loginWithToken:session",this.session),this.log("loginWithToken:CognitoUser",$),this.log("loginWithToken:userPool",this.userPool),$&&this.userPool){this.log("loginWithToken:cognito:username",t["cognito:username"]);let e={Username:t["cognito:username"],Pool:this.userPool};this.log("loginWithToken:cognitoUserParams",e),Ae=new $(e),Ae.setSignInUserSession(this.session),this.log("loginWithToken:cognitoUserRestored",{cognitoUserType:typeof Ae,cognitoUserKeys:Object.keys(Ae||{}),cognitoUser:Ae})}}catch(e){this.log("loginWithToken:err",e);try{this.log("loginWithToken:err:stringified",JSON.stringify(e))}catch(t){this.log("loginWithToken:err:stringifyFail",String(e))}try{const t=Object.keys(e||{}),n=Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(e||{}):[],r=Object.getOwnPropertyDescriptors?Object.getOwnPropertyDescriptors(e||{}):{};this.log("loginWithToken:createSessionError:allKeys",{keys:t,symbols:n,descriptors:r})}catch(e){this.log("loginWithToken:createSessionError:allKeysFail",String(e))}}return this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user),this.user}async function Oe(){return await this.__connection,this.__user?.service===this.service?this.__user?.owner===this.host:(await Ve.bind(this)(),!1)}async function Me(e=!1){let t=null;Ae&&(e?t=new Promise((e,t)=>{Ae.globalSignOut({onSuccess:t=>{this.log("globalSignOut:success",t),e(t)},onFailure:e=>{this.log("globalSignOut:error",e),t(e)}})}):Ae.signOut());let n={session:null,__startKeyHistory:{},__cached_requests:{},__user:null};t&&(t=await t);for(let e in n)this[e]=n[e];return this._runOnUserUpdateListeners(null),this._runOnLoginListeners(null),t}async function Ve(e){await this.__connection;let{data:t}=he(e);return await Me.bind(this)(t?.global),"SUCCESS: The user has been logged out."}async function xe(){if(!this.__request_signup_confirmation)throw new te("Least one login attempt is required.",{code:"INVALID_REQUEST"});return await ht.bind(this)("confirm-signup",{username:this.__request_signup_confirmation})}async function Fe(e=!1){if("string"==typeof e)e=be.Url(e);else if("boolean"!=typeof e)throw new te("Argument should be type: <boolean | string>.",{code:"INVALID_REQUEST"});if(!this.__disabledAccount)throw new te("Least one signin attempt of disabled account is required.",{code:"INVALID_REQUEST"});return await ht.bind(this)("recover-account",{username:this.__disabledAccount,redirect:e}),"SUCCESS: Recovery e-mail has been sent."}async function qe(e){let t=be.Params(e,{username:"string",email:"string",password:"string"},["password"]);if(await this.__authConnection,t.email)try{be.Email(t.email)}catch(e){t.username=t.email,delete t.email}if(!t.username&&!t.email)throw new te('Least one of "username" or "email" is required.',{code:"INVALID_PARAMETER"});return await Pe.bind(this)().authenticateUser(t.username||t.email,t.password)}async function Be(e,t){await this.__authConnection;let n={username:"string",password:e=>be.Password(e),email:e=>be.Email(e),name:"string",address:e=>e?"string"==typeof e?e:"object"==typeof e?JSON.stringify(e):void 0:"",gender:"string",birthdate:e=>e?be.Birthdate(e):"",phone_number:e=>e?be.PhoneNumber(e):"",email_public:["boolean",()=>!1],address_public:["boolean",()=>!1],gender_public:["boolean",()=>!1],birthdate_public:["boolean",()=>!1],phone_number_public:["boolean",()=>!1],access_group:"number",misc:"string",picture:e=>e?be.Url(e):"",profile:e=>e?be.Url(e):"",family_name:"string",given_name:"string",middle_name:"string",nickname:"string",website:e=>e?be.Url(e):""},r=be.Params(e||{},n,["email","password"]);await Ve.bind(this)(),t=be.Params(t||{},{email_subscription:e=>{if("boolean"!=typeof e)throw new te('"option.email_subscription" should be type: <boolean>.',{code:"INVALID_PARAMETER"});if(!t?.signup_confirmation)throw new te('"option.signup_confirmation" is required for email subscription.',{code:"INVALID_PARAMETER"});return e},signup_confirmation:e=>{let t=e;if("string"==typeof e)t=be.Url(e);else{if("boolean"!=typeof e)throw new te('"option.signup_confirmation" should be type: <string | boolean>.',{code:"INVALID_PARAMETER"});t=e}if(t&&!r.email)throw new te('"email" is required for signup confirmation.',{code:"INVALID_PARAMETER"});return t},login:e=>{if("boolean"==typeof e){if(t.signup_confirmation&&e)throw new te('"login" is not allowed when "option.signup_confirmation" is true.',{code:"INVALID_PARAMETER"});return e}throw new te('"option.login" should be type: boolean.',{code:"INVALID_PARAMETER"})}});let i=t?.login||!1;if(r.signup_confirmation=t?.signup_confirmation||!1,r.email_subscription=t?.email_subscription||!1,r.email_public&&!r.signup_confirmation)throw new te('"option.signup_confirmation" should be true if "email_public" is set to true.',{code:"INVALID_PARAMETER"});r.service=this.service,r.owner=this.owner;let s=Pe.bind(this)().createCognitoUser(r.username||r.email);for(let e of["email_public","address_public","gender_public","birthdate_public","phone_number_public"])r[e]=r[e]?"1":"0";r.access_group&&(r.access_group=r.access_group.toString());let o=(await ht.bind(this)("signupkey",{username:s.cognitoUsername,signup_confirmation:"boolean"==typeof r.signup_confirmation?JSON.stringify(r.signup_confirmation):r.signup_confirmation,email_subscription:r.email_subscription})).split(":"),a=o.slice(1).join(":"),c=[new V({Name:"custom:signup",Value:o[0]}),new V({Name:"locale",Value:a.split("#")[1]}),new V({Name:"custom:signup_ticket",Value:a})];for(let e in n){let t=["email_public","address_public","gender_public","birthdate_public","phone_number_public","misc","service","owner"];""!==r[e]&&"username"!==e&&"password"!==e&&"access_group"!==e&&(t.includes(e)?c.push(new V({Name:"custom:"+e,Value:r[e]})):c.push(new V({Name:e,Value:r[e]})))}return await Pe.bind(this)().signup(s.cognitoUsername,r.password,c),r.signup_confirmation?(Ae=s.cognitoUser,this.__request_signup_confirmation=s.cognitoUsername,"SUCCESS: The account has been created. User's signup confirmation is required."):i?qe.bind(this)({email:r.username||r.email,password:r.password}):"SUCCESS: The account has been created."}async function $e(){await this.__connection;let e=await ht.bind(this)("remove-account",{disable:this.__user.user_id},{auth:!0});return await Ve.bind(this)(),e}async function je(e){await this.__connection;let t=be.Params(e,{email:e=>be.Email(e),code:["number","string"],new_password:e=>be.Password(e)},["email","code","new_password"]),n=t.code,r=t.new_password;return"number"==typeof n&&(n=n.toString()),new Promise(async(e,i)=>{Pe.bind(this)().createCognitoUser(t.email).cognitoUser.confirmPassword(n,r,{onSuccess:t=>{e("SUCCESS: New password has been set.")},onFailure:e=>{i(new te(e?.message||"Failed to reset password.",{code:e?.code||"ERROR",cause:e}))}})})}async function Ke(e,t){let n;if(await this.__connection,!Ae)throw new te("The user has to be logged in.",{code:"INVALID_REQUEST"});if("email"===e||"phone_number"===e){if(!this.__user.hasOwnProperty(e))throw new te(`No ${"email"===e?"e-mail":"phone number"} to verify`,{code:"INVALID_REQUEST"});return this.__user?.[`${e}_verified`]?`SUCCESS: "${e}" is verified.`:(n=(t?be.Params(t,{code:["string"]}):{}).code||"",new Promise((t,r)=>{let i={onSuccess:i=>{n?Pe.bind(this)().getSession({refreshToken:!0}).then(()=>{this.__user&&(this.__user[e+"_verified"]=!0),t(`SUCCESS: "${e}" is verified.`)}).catch(e=>{r(e)}):t("SUCCESS: Verification code has been sent.")},onFailure:e=>{r(new te(e.message||"Failed to request verification code.",{code:e?.code}))}};n?Ae?.verifyAttribute(e,n,i):(i.inputVerificationCode=null,Ae?.getAttributeVerificationCode(e,i))}))}}function Je(e){return Ke.bind(this)("phone_number",e)}function He(e){return Ke.bind(this)("email",e)}async function We(e){await this.__connection;let t=be.Params(e,{email:e=>be.Email(e)},["email"]);return new Promise(async(e,n)=>{Pe.bind(this)().createCognitoUser(t.email).cognitoUser.forgotPassword({onSuccess:t=>{e("SUCCESS: Verification code has been sent.")},onFailure:e=>{let{parsed:t,code:r}=Ce(e),i={UserNotFoundException:"NOT_EXISTS",InvalidParameterException:"INVALID_PARAMETER",NotAuthorizedException:"INVALID_REQUEST",LimitExceededException:"REQUEST_EXCEED",TooManyRequestsException:"REQUEST_EXCEED",CodeDeliveryFailureException:"CODE_DELIVERY_FAILURE"}[r]||t.code||r||"ERROR";n(new te(t.message,{code:i,cause:e}))}})})}async function Qe(e){if(await this.__connection,!this.session)throw new te("User login is required.",{code:"INVALID_REQUEST"});let t=be.Params(e,{current_password:"string",new_password:"string"});if(!t?.current_password)throw new te('"current_password" is required to change password.',{code:"INVALID_PARAMETER"});if(!t?.new_password)throw new te('"new_password" is required to change password.',{code:"INVALID_PARAMETER"});return be.Password(t.current_password),be.Password(t.new_password),new Promise((e,n)=>{Ae.changePassword(t.current_password,t.new_password,(t,r)=>{if(t)if("InvalidParameterException"===t?.code)n(new te("Invalid password parameter.",{code:"INVALID_PARAMETER"}));else if("NotAuthorizedException"===t?.code)n(new te("Incorrect password.",{code:"INVALID_REQUEST"}));else if("TooManyRequestsException"===t?.code||"LimitExceededException"===t?.code)n(new te("Too many attempts. Please try again later.",{code:"REQUEST_EXCEED"}));else{let{parsed:e,code:r}=Ce(t);n(e)}else e("SUCCESS: Password has been changed.")})})}async function ze(e){if(await this.__connection,!this.session)throw new te("User login is required.",{code:"INVALID_REQUEST"});let t=be.Params(e||{},{user_id:e=>be.UserId(e),email:e=>be.Email(e),address:e=>e?"string"==typeof e?e:"object"==typeof e?JSON.stringify(e):void 0:"",name:"string",gender:"string",birthdate:e=>e?be.Birthdate(e):"",phone_number:e=>e?be.PhoneNumber(e):"",email_public:"boolean",phone_number_public:"boolean",address_public:"boolean",gender_public:"boolean",birthdate_public:"boolean",misc:"string",picture:e=>e?be.Url(e):"",profile:e=>e?be.Url(e):"",family_name:"string",given_name:"string",middle_name:"string",nickname:"string",website:e=>e?be.Url(e):""});if(t&&"object"==typeof t&&!Object.keys(t).length)return this.user;t.email&&(t.preferred_username=this.service+"-"+ie.hash(t.email));let n=[["email_public","email_verified","User's e-mail should be verified to set"],["phone_number_public","phone_number_verified","User's phone number should be verified to set"]];if(this.__user)for(let e of n)if(t[e[0]]&&!this.__user[e[1]])throw new te(`${e[2]} "${e[0]}" to true.`,{code:"INVALID_REQUEST"});let r=[];for(let e in t)if(t[e]!==this.user[e]){if(["email_public","phone_number_public","address_public","gender_public","birthdate_public","misc"].includes(e)){let n=t[e];"boolean"==typeof n&&(n=n?"1":"0"),t["custom:"+e]=n,r.push(e)}}else r.push(e);for(let e of r)delete t[e];if(t.user_id){if(t.user_id!==this.user.user_id)return ht.bind(this)("admin-edit-profile",{attributes:t},{auth:!0});delete t.user_id}if(t&&"object"==typeof t&&Object.keys(t).length){let e=[];for(let n in t)e.push(new V({Name:n,Value:t[n]}));return await new Promise((t,n)=>{Ae?.updateAttributes(e,(e,r)=>{e&&n([e?.code||e?.name,e?.message||"Failed to update user settings."]),t(r)})}),await Pe.bind(this)().getSession({refreshToken:!0}),this.user}return this.user}async function Ge(e,t){(e=he(e).data)||(e={searchFor:"timestamp",condition:">",value:0},t||(t={}),t.ascending=!1),await this.__connection;const n={user_id:e=>Array.isArray(e)?e.map(e=>be.UserId(e)):be.UserId(e),email:"string",phone_number:"string",locale:e=>{if("string"!=typeof e||"string"==typeof e&&e.length>5)throw new te('Value of "locale" should be a country code.',{code:"INVALID_PARAMETER"});return e},name:"string",address:"string",gender:"string",birthdate:e=>be.Birthdate(e),subscribers:"number",timestamp:"number",access_group:"number",approved:"string"};if(e=be.Params(e,{searchFor:["user_id","name","email","phone_number","address","gender","birthdate","locale","subscribers","timestamp","access_group","approved"],condition:[">",">=","=","<","<=","gt","gte","eq","lt","lte",()=>"="],value:t=>{let r=n[e.searchFor];if("function"==typeof r)return r(t);if(typeof t!==r)throw new te(`Value does not match the type of "${e.searchFor}" index.`,{code:"INVALID_PARAMETER"});return t},range:t=>{let r=n[e.searchFor];if("function"==typeof r)return r(t);if(typeof t!==r)throw new te(`Range does not match the type of "${e.searchFor}" index.`,{code:"INVALID_PARAMETER"});return t}},["searchFor","value"]),e?.condition&&"="!==e?.condition&&e.hasOwnProperty("range"))throw new te("Conditions does not apply on range search.",{code:"INVALID_PARAMETER"});if("user_id"===e.searchFor&&("="!==e.condition||e.range))throw new te(`Conditions are not allowed on "${e.searchFor}"`,{code:"INVALID_PARAMETER"});if("string"==typeof e?.value&&!e?.value)throw new te("Value should not be an empty string.",{code:"INVALID_PARAMETER"});if("string"==typeof e?.searchFor&&!e?.searchFor)throw new te('"searchFor" should not be an empty string.',{code:"INVALID_PARAMETER"});return ht.bind(this)("get-users",e,{auth:!0,fetchOptions:t})}async function Ye(e){await this.__connection;let t=await ht.bind(this)("last-verified-email",e,{auth:!0});return t.includes("SUCCESS")?(await Pe.bind(this)().getSession({refreshToken:!0}),this.user):t}async function Ze(e){return await this.__connection,e=be.Params(e,{username:be.Email,redirect:be.Url},["username"]),await ht.bind(this)("request-username-change",e,{auth:!0})}const Xe=class{version="1.0.0";items=[];breakWhenError=!1;batchSize=1;onProgress;completed=[];runningBatches=[];runningSlots=[];get batchToProcess(){return Math.ceil(this.items.length/this.batchSize)}get batchProcessFinished(){let e=Object.keys(this.completed).length===this.runningBatches.length;if(e){const e=this.completed;this.completed=[],this.runningBatches=[],this.runningSlots=[],this.onProgress&&this.onProgress({batchToProcess:this.batchToProcess,itemsToProcess:this.items.length,completed:e})}return e}constructor(e){if(this.breakWhenError=!!e?.breakWhenError,this.batchSize=e?.batchSize??1,"number"!=typeof this.batchSize||this.batchSize<1)throw new Error("batchSize must be at least 1");if(e?.onProgress){if("function"!=typeof e.onProgress)throw new Error("onProgress must be a function");this.onProgress=e.onProgress}}add(e){const t=Array.isArray(e)?e:[e];for(const e of t){if("function"!=typeof e)throw new Error("Each job must be a function that returns a Promise");this.items.push(e)}this.processNext()}processNext(){if(0===this.items.length)return;const e=this.batchSize-this.runningBatches.length;if(!(e<=0)){this.runningBatches.push(...this.items.splice(0,e));for(let e=0;e<this.runningBatches.length;e++)this.runningSlots?.[e]||(this.runningSlots[e]=!0,this.runningBatches[e]().then(t=>this.completed[e]?t:(this.completed[e]=t,this.batchProcessFinished?this.processNext():t)).catch(t=>{if(this.breakWhenError)throw t;return this.completed[e]=t,this.batchProcessFinished?this.processNext():t}))}}terminate(){this.items=[]}};let et=null;const tt="undefined"!=typeof SubmitEvent,nt="undefined"!=typeof HTMLFormElement,rt="undefined"!=typeof FormData;let it=0;function st(e){if(!e)return null;const t=Number(e);if(Number.isFinite(t))return Math.max(0,1e3*t);const n=Date.parse(e);return Number.isNaN(n)?null:Math.max(0,n-Date.now())}function ot(e,t){return t>0?e/t*100:0}let at=e=>{const{auth:t,type:n,endpoints:r}=e,i=r[0],s=r[1];if(it++,"admin"===n){const e=Object.entries(i).filter(([e,n])=>e.includes(t?"_private":"_public")&&"string"==typeof n).map(([,e])=>e);if(!e.length)throw new te("No available admin gateways.",{code:"INVALID_REQUEST"});return e[it%e.length]}if("record"===n){const e=Object.entries(s).filter(([e,n])=>e.includes(t?"record_private":"record_public")&&"string"==typeof n).map(([,e])=>e);if(!e.length)throw new te("No available record gateways.",{code:"INVALID_REQUEST"});return e[it%e.length]}throw new te("Invalid gateway type.",{code:"INVALID_REQUEST"})};async function ct(e,t){const n=await Promise.all([this.admin_endpoint,this.record_endpoint]),r=n[0],i=n[1];let s=e.split("?"),o=s.length>1?"?"+s[1]:"";switch(e=s[0]){case"get-users":return r.get_users_private+e+o;case"service":return r.service_public+e+o;case"get-newsletters":case"get-public-newsletters":case"subscribe-newsletter":case"subscribe-public-newsletter":case"signupkey":case"admin-newsletter-request":case"admin-signup":case"confirm-signup":case"openid-logger":case"block-account":case"admin-edit-profile":case"remove-account":case"post-secure":case"recover-account":case"mock":case"grant-access":case"last-verified-email":case"ticket":case"register-ticket":case"get-newsletter-subscription":case"request-username-change":case"send-inquiry":case"register-newsletter-group":case"newsletter-group-endpoint":case"invitation-list":case"csr":return at.bind(this)({auth:t,type:"admin",endpoints:n})+e+o;case"post-record":return(t?i.post_private:i.post_public)+e+o;case"get-records":return(t?i.get_private:i.get_public)+e+o;case"del-files":case"del-records":return i.del_private+e+o;case"store-subscription":case"get-vapid-public-key":case"push-notification":case"delete-subscription":case"subscription":case"get-subscription":case"get-table":case"get-tag":case"get-uniqueid":case"get-index":case"get-signed-url":case"grant-private-access":case"request-private-access-key":case"get-ws-group":case"check-schema":case"get-feed":case"castspell":case"dopamine":case"getspell":return at.bind(this)({auth:t,type:"record",endpoints:n})+e+o;default:return be.Url(e)+o}}const ut={};function lt(){et&&(et.terminate(),et=null)}async function ht(e,t=null,n,r){this.log("request",{url:e,data:t,options:n,_etc:r||{}}),n=n||{};let{auth:i=!1,method:s="post",bypassAwaitConnection:o=!1}=n;s=s.toUpperCase();let a=null,c=t?.service||this.service,u=t?.owner||this.owner,l=null,h=await ct.bind(this)(e,!!i);if(!o&&(a=await this.__connection,!a))throw new te("Invalid connection. The service could have been disabled, or has a restricted CORS.",{code:"INVALID_REQUEST"});i&&(l=await Ue.bind(this)());let d={},{fetchMore:f=!1,progress:p}=n?.fetchOptions||{};if(n?.fetchOptions&&Object.keys(n.fetchOptions).length){for(let e of["limit","startKey","ascending"])n.fetchOptions.hasOwnProperty(e)&&(d[e]=n.fetchOptions[e]);d=be.Params(d,{limit:e=>{if("number"!=typeof e)throw new te("Fetch limit should be a number.",{code:"INVALID_REQUEST"});if(e>1e3)throw new te("Fetch limit should be below 1000.",{code:"INVALID_REQUEST"});return e},startKey:e=>e,ascending:"boolean"})}let g=r?.ignoreService?{}:{service:c,owner:u};Object.assign(g,d),(t=he(t).data)?t&&"object"==typeof t&&(t=Object.assign(g,t)):t=g;let _=`${s}:${i?"auth":"public"}:${e}`,m=(()=>{if(t&&"object"==typeof t&&Object.keys(t).length&&!(t instanceof FormData)){function e(t){return"object"==typeof t&&null!==t?Object.keys(t).sort().reduce((n,r)=>("object"==typeof t[r]&&null!==t[r]?n[r]=e(t[r]):n[r]=t[r],n),{}):t}return ie.hash(_+"/"+JSON.stringify(e(t)))}return ie.hash(_+"/"+this.service)})(),{requestKey:y,requestKeyWithStartKey:w}=dt.bind(this)({params:t,url:e,fetchMore:f,hashedParams:m});if(!y||y&&"object"==typeof y)return y;if(this.log("requestKey",w),"string"==typeof w&&ut[w]instanceof Promise)return this.log("request:returning pending",w),ut[w];let b={Accept:"*/*"};if(Object.prototype.hasOwnProperty.call(n,"contentType")){const e=null===n.contentType?"application/x-www-form-urlencoded":n.contentType;e&&(b["Content-Type"]=e)}else rt&&t instanceof FormData||(b["Content-Type"]="application/json");l&&(b.Authorization=l);let A={public_identifier:this.__public_identifier,service:c,owner:u};b["Content-Meta"]=JSON.stringify(A);let v={headers:b};if(n?.responseType&&(v.responseType=n.responseType),"GET"===s){if(t){let e=[];if(e=t instanceof FormData?Array.from(t.entries()).map(([e,t])=>{const n="string"==typeof t?t:t.name;return encodeURIComponent(e)+"="+encodeURIComponent(n)}):Object.keys(t).map(e=>{let n=t[e];return"string"!=typeof n&&(n=JSON.stringify(n)),encodeURIComponent(e)+"="+encodeURIComponent(n)}),e.length){const t=h.includes("?")?h.endsWith("?")||h.endsWith("&")?"":"&":"?";h+=t+e.join("&")}}v.body=null}else if(t instanceof FormData)v.body=t;else if("application/x-www-form-urlencoded"===b["Content-Type"]&&t&&"object"==typeof t){const e=new URLSearchParams;for(let n of Object.keys(t)){const r=t[n];e.append(n,"string"==typeof r?r:JSON.stringify(r))}v.body=e.toString()}else v.body="string"==typeof t?t:t?JSON.stringify(t):null;if(v.method=s,null===et){let e={batchSize:this.requestBatchSize,breakWhenError:!1,onProgress:e=>{this.onBatchProcess.forEach(t=>t(e))}};et=new Xe(e)}return new Promise((t,n)=>{et.add([async()=>{let r=ft.bind(this)(h,v,p);ut[w]=r;try{let n=pt.bind(this)({hashedParam:y,requestKeyWithStartKey:w,url:e,fetched:await r});return delete ut[w],this.log("request:end",n),t(n),n}catch(e){throw delete ut[w],this.log("request:err",e),n(e),e}}])})}function dt(e){let{params:t={},url:n,fetchMore:r=!1,hashedParams:i}=e||{};if(t.startKey){if(("object"!=typeof t.startKey||!Object.keys(t.startKey).length)&&"start"!==t.startKey&&"end"!==t.startKey)throw new te(`"${t.startKey}" is invalid startKey key.`,{code:"INVALID_PARAMETER"});"start"===t.startKey&&(r=!1,delete t.startKey)}if(!r){if(this.__cached_requests?.[n]?.[i]&&delete this.__cached_requests[n][i],this.__startKeyHistory?.[n]?.[i]){if(Array.isArray(this.__startKeyHistory[n][i])&&this.__startKeyHistory[n][i].length)for(let e of this.__startKeyHistory[n][i]){let t=i+ie.hash(e);this.__cached_requests?.[n]&&this.__cached_requests?.[n]?.[t]&&delete this.__cached_requests[n][t]}delete this.__startKeyHistory[n][i]}return{requestKeyWithStartKey:i,requestKey:i}}if(!Array.isArray(this.__startKeyHistory?.[n]?.[i]))return{requestKeyWithStartKey:i,requestKey:i};let s=this.__startKeyHistory[n][i],o=s[s.length-1],a=i;if(o){if("end"===o)return{requestKey:{list:[],startKey:"end",endOfList:!0,startKeyHistory:s},requestKeyWithStartKey:a};a+=ie.hash(o),t.startKey=JSON.parse(o)}return this.__cached_requests?.[n]?.[a]?{requestKey:this.__cached_requests[n][a],requestKeyWithStartKey:a}:{requestKeyWithStartKey:a,requestKey:i}}function ft(e,t,n){return new Promise((r,i)=>{let s=new XMLHttpRequest;for(var o in s.open(t.method||"GET",e),t.headers||{})s.setRequestHeader(o,t.headers[o]);t.responseType&&(s.responseType=t.responseType),s.onload=()=>{if(s.status<400)if("json"==t.responseType||"blob"==t.responseType)r(s.response);else{let e=s.responseText;try{e=JSON.parse(e)}catch(e){}r(e)}else if(429===s.status){let o=st(s.getResponseHeader("Retry-After"));null!==o?setTimeout(()=>{ft(e,t,n).then(r,i)},o):i("Too many requests")}else{let e=s.status,n=["INVALID_CORS","INVALID_REQUEST","SERVICE_DISABLED","INVALID_PARAMETER","ERROR","EXISTS","NOT_EXISTS"],r="blob"==t.responseType?s.response:s.responseText;try{r=JSON.parse(r)}catch(e){}if("string"==typeof r){let e=r.split(":"),t=e.splice(0,1)[0].trim(),s=e.join(":").trim();i(new te(s,{code:n.includes(t)?t:"ERROR"}))}else if("object"==typeof r&&r?.message){let t=r?.code||(e?e.toString():null)||"ERROR",n=r.message,s=r?.cause;"string"==typeof n&&(n=n.trim()),i(new te(n,{cause:s,code:t}))}else i(r)}},s.onerror=()=>i("Network error"),s.onabort=()=>i("Aborted"),s.ontimeout=()=>i("Timeout"),"function"==typeof n&&(s.onprogress=e=>{n({status:"download",progress:ot(e.loaded,e.total),loaded:e.loaded,total:e.total,abort:()=>s.abort()})},s.upload&&(s.upload.onprogress=e=>{n({status:"upload",progress:ot(e.loaded,e.total),loaded:e.loaded,total:e.total,abort:()=>s.abort()})})),s.send(t.body)})}function pt(e){let{hashedParam:t,requestKeyWithStartKey:n,url:r,fetched:i}=e;if(!i?.startKey)return i;this.__startKeyHistory.hasOwnProperty(r)||(this.__startKeyHistory[r]={}),this.__startKeyHistory[r].hasOwnProperty(t)||(this.__startKeyHistory[r][t]=[]);let s="end"===i.startKey?"end":JSON.stringify(i.startKey);return this.__startKeyHistory[r][t].includes(s)||this.__startKeyHistory[r][t].push(s),this.__cached_requests?.[r]||(this.__cached_requests[r]={}),this.__cached_requests[r][n]=i,Object.assign({startKeyHistory:this.__startKeyHistory[r][t]},i)}async function gt(e,t){await this.__connection;let{record_id:n,service:r=this.service,progress:i}=t;if(!n)throw new te('"record_id" is required.',{code:"INVALID_PARAMETER"});if(tt&&e instanceof SubmitEvent&&(e=e.target),nt&&e instanceof HTMLFormElement&&(e=new FormData(e)),!(rt&&e instanceof FormData))throw new te('"fileList" should be a FormData or HTMLFormElement.',{code:"INVALID_PARAMETER"});let s,o={reserved_key:ae(),service:r,request:"post"};t?.record_id&&(o.id=t.record_id);let a=(e,t,n)=>new Promise((r,i)=>{s=new XMLHttpRequest,s.open("POST",e),s.onload=()=>{let o=s.responseText;try{o=JSON.parse(o)}catch(e){}if(s.status>=200&&s.status<300)r(o);else if(429===s.status){let o=st(s.getResponseHeader("Retry-After"));null!==o?setTimeout(()=>{a(e,t,n).then(r,i)},o):i("Too many requests")}else i(o)},s.onerror=()=>i("Network error"),s.onabort=()=>i("Aborted"),s.ontimeout=()=>i("Timeout"),s.upload&&"function"==typeof n&&(s.upload.onprogress=n),s.send(t)});function c(e){const t="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";if(0===e)return t[0];let n="";for(;e>0;)n=t[e%62]+n,e=Math.floor(e/62);return n}return null===et&&(et=new Xe({batchSize:this.requestBatchSize,breakWhenError:!1})),new Promise((t,n)=>{et.add([async()=>{let n=[],r=[],u=[];for(let[t,l]of e.entries()){if(!(l instanceof File))continue;let e=Object.assign({key:t+"/"+l.name,sizeKey:c(l.size),contentType:l.type||null},o),{fields:h=null,url:d,cdn:f}=await ht.bind(this)("get-signed-url",e,{auth:!!this.__user});u.push(f);let p=new FormData;for(let e in h)p.append(e,h[e]);p.append("file",l);try{await a(d,p,"function"==typeof i?e=>i({status:"upload",progress:ot(e.loaded,e.total),currentFile:l,completed:n,failed:r,loaded:e.loaded,total:e.total,abort:()=>s.abort()}):null),n.push(l)}catch(e){r.push(l)}}return t({completed:n,failed:r,bin_endpoints:u}),{completed:n,failed:r,bin_endpoints:u}}])})}const _t={};function mt(e){let{preventMultipleCalls:t=!1}=e||{};return function(e,n,r){const i=r.value;r.value=function(...e){let r=e[0],s=!0,o=null,a="",c={},u=!1;if(tt&&r instanceof SubmitEvent){r.preventDefault();let e=window.location.href;o=r.target;let t=new URL(o.action);a=t.href;let n=a?a.match(/(?<=\{).*?(?=\})/g):"";if(n)for(let e of n){if(!e)continue;let t=o.querySelector(`[name="${e}"]`);if(t)if("file"===t.type)for(let n=0;n<=t.files.length-1;n++)t.files[n]&&(c[e]||(c[e]=[]),c[e].push(new Promise((e,r)=>{let i=new FileReader;i.onload=function(){e(i.result)},i.readAsDataURL(t.files[n]),i.onerror=r})));else a=a.replace(`{${e}}`,t.value)}null===o.getAttribute("action")?s=!1:u=t.href===e}const l=async e=>{if(a)for(let e in c)c[e].length&&(a=a.replace(`{${e}}`,(await Promise.all(c[e])).join(",")));return o&&s&&(window.sessionStorage.setItem(`${this.service}:${ie.hash(a)}`,JSON.stringify(e)),u?window.location.replace(a):window.location.href=a),e};let h;const d=async()=>{try{if(h=i.bind(this)(...e),h instanceof Promise){let e=await h;return l(e)}return l(h)}catch(e){throw(e=>{throw e instanceof te?e.name=n+"()":e=e instanceof Error?e:new te(e,{name:n+"()"}),e})(e)}};if(t){let e=`${n}:${this?.__public_identifier||""}:${this?.service||""}:${this?.owner||""}`;return _t?.[e]||(_t[e]=d().finally(()=>{delete _t[e]})),_t[e]}return d()}}}async function yt(){await this.__connection;let e=`${this.service}:${ie.hash(window.location.href.split("?")[0])}`,t=window.sessionStorage.getItem(e);if(window.sessionStorage.removeItem(e),null!==t){try{t=JSON.parse(t)}catch(e){}return t}return null}function wt(e,t="parameter",n=!1,r=!1){if(!e)throw new te(`"${t}" is required.`,{code:"INVALID_PARAMETER"});return be.specialChars(e,t,n,r)}function bt(e){if(void 0===e)return 0;if("number"==typeof e){if(e>99||e<0)throw new te('"table.access_group" value should be within a range of 0 ~ 99.',{code:"INVALID_REQUEST"})}else{if("string"!=typeof e)throw new te('"table.access_group" should be type: <number | string>.',{code:"INVALID_PARAMETER"});if(void 0===(e={private:"private",public:0,authorized:1,admin:99}[e]))throw new te('"table.access_group" is invalid.',{code:"INVALID_PARAMETER"})}if(!this.__user&&e)throw new te("Unsigned users have no access to records with access group.",{code:"INVALID_REQUEST"});return e}function At(e){if("number"==typeof e){if(e>4503599627370496||e<-4503599627370496)throw new te("Number value should be within range -4503599627370496 ~ +4503599627370496",{code:"INVALID_PARAMETER"});return e}if("boolean"==typeof e)return e;if("string"==typeof e)return wt(e,"index.value",!1,!0);throw new te('"index.value" should be type: <number | boolean | string>.',{code:"INVALID_PARAMETER"})}function vt(e){let t={table:{name:[e=>wt(e,"table.name",!0,!0)],access_group:[bt.bind(this)],subscription:e=>{if("string"==typeof e)return be.UserId(e,'User ID in "subscription"'),e}},reference:"string",index:{name:["$updated","$uploaded","$referenced_count","$user_id",e=>wt(e,"index.name",!0,!1)],value:t=>{const n={$updated:"number",$uploaded:"number",$referenced_count:"number",$user_id:be.UserId};if(n.hasOwnProperty(e.index.name)){let r=n[e.index.name];if("function"==typeof r)return r(t);if(r!==typeof t)throw new te(`"index.value" should be type: ${r}.`,{code:"INVALID_PARAMETER"});return t}return"string"!=typeof t||t?At(t):" "},condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq"],range:t=>function(e,t){if(!t.index||!("value"in t.index))throw new te('"index.value" is required.',{code:"INVALID_PARAMETER"});if("$record_id"===t.index.name)throw new te(`Cannot do "index.range" on ${t.index.name}`,{code:"INVALID_PARAMETER"});if(typeof t.index.value!=typeof e)throw new te('"index.range" type should match the type of "index.value".',{code:"INVALID_PARAMETER"});return"string"==typeof e?be.specialChars(e,"index.range",!1,!0):e}(t,e)},tag:e=>{if(null==e)return e;if("string"==typeof e)return be.specialChars(e,"tag",!1,!0);throw new te('"tag" should be type: string.',{code:"INVALID_PARAMETER"})},private_key:"string"};return t.index&&t.index.hasOwnProperty("range")&&t.index.hasOwnProperty("condition")&&delete t.index.range,t}const St={};async function Et(e,t){if(e?.rec&&"called from postRecord"!==t){let t=window.sessionStorage.getItem(`${this.service}:post:${e.rec}`);if(t){try{e=JSON.parse(t)}catch(e){}window.sessionStorage.removeItem(`${this.service}:post:${e.rec}`)}}const n={user_id:"",record_id:"",updated:0,uploaded:0,readonly:!1,table:{name:"",access_group:0,subscription:{is_subscription_record:!1,upload_to_feed:!1,notify_subscribers:!1,feed_referencing_records:!1,notify_referencing_records:!1}},referenced_count:0,source:{referencing_limit:null,prevent_multiple_referencing:!1,can_remove_referencing_records:!1,only_granted_can_reference:!1},ip:"",bin:{}};let r=!1;function i(e){let t="**"==e?"private":parseInt(e);return t=0==t?"public":1==t?"authorized":99==t?"admin":t,t}const s={ip:e=>{let t=e.split("#"),i=t[0];t.length>1&&(n.unique_id=t[1]),"R"===i.slice(-1)?(n.readonly=!0,i=i.slice(0,-1)):n.readonly=!1,/^\d{1,3}-\d{1,3}-\d{1,3}-\d{1,3}$/.test(i)&&(i=i.split("-").join("."),r=!0),n.ip=i},rec:e=>{if(!e)return;n.record_id=e;let t=oe(e.substring(0,e.length-9));n.uploaded=t},usr:e=>{n.user_id=e},tbl:e=>{if(e&&!n.table.name){let t=e.split("/");n.table.name=t[0],n.table.access_group=i(t[2]),t?.[3]&&(n.table.subscription.is_subscription_record=!0)}},usr_tbl:e=>{let t=e.split("/");n.user_id||(n.user_id=t[0]),n.table.name||(n.table.name=t[1],n.table.access_group=i(t[3]),t?.[4]&&(n.table.subscription.is_subscription_record=!0))},idx:e=>{if(!e)return;let t=e.split("!"),r=t.splice(0,1)[0],i=function(e){let t=e.substring(3);switch(e.substring(0,3)){case"!S%":return t;case"!N%":let n=t.split("."),r=Number(n[0])-4503599627370496;return 1===n.length?r:parseFloat(r.toString()+"."+n[1]);case"!B%":return"1"===t;case"!L%":case"!D%":try{return JSON.parse(t)}catch(e){throw new te("Value parse error.",{code:"PARSE_ERROR"})}default:return e}}("!"+t.join("!"));n.index={name:r,value:i}},ref:e=>{e&&(n.reference=e.split("/")[0])},tags:e=>{n.tags=e},upd:e=>{n.updated=e},acpt_mrf:e=>{n.source.prevent_multiple_referencing=!e},ref_limt:e=>{n.source.referencing_limit=e},rfd:e=>{n.referenced_count=e},bin:async e=>{let t={},r=n?.reference||null;if(Array.isArray(e)){const n=await Promise.all(e.map(async e=>{try{let t=e.split("/").slice(3).join("/"),n=t.split("/");if(n.length<12)return null;let s=decodeURIComponent(n[n.length-1]),o=decodeURIComponent(n[10]),a=n[9],c=n[8],u=i(n[6]),l=e;"public"!==u&&(l=await Tt.bind(this)(e,{dataType:"endpoint",_ref:r}));let h={access_group:u,filename:s,url:l,path:t,size:oe(a),uploaded:oe(c),getFile:(e,t)=>{let n={dataType:e||"download",progress:t,_ref:r,_update:h};return Tt.bind(this)(l,n)}};return{pathKey:o,obj:h}}catch{return null}}));for(let e of n)e&&(t[e.pathKey]?t[e.pathKey].push(e.obj):t[e.pathKey]=[e.obj])}n.bin=t},prv_acs:e=>{for(let t in e)["notify_subscribers","upload_to_feed","feed_referencing_records","notify_referencing_records"].includes(t)?n.table.subscription[t]=e[t]:n.source[t]=e[t]},data:e=>{let t=e;"!D%{}"===e?t={}:"!L%[]"===e&&(t=[]),n.data=t}};if(e.record_id)return e;for(let t in s)if(e.hasOwnProperty(t)){let n=s[t](e[t]);n instanceof Promise&&await n}return r&&(n.user_id="anonymous:"+n.user_id),n}async function It(e){let{endpoints:t}=e;if("string"==typeof t&&(t=[t]),!Array.isArray(t))throw new te('"endpoints" should be type: array | string.',{code:"INVALID_PARAMETER"});let n=await ht.bind(this)("del-files",{endpoints:t,storage:"records"},{auth:!0,method:"post"}),r=[];for(let e in n)r.push(Et.bind(this)(n[e]));return Promise.all(r)}async function Tt(e,t){if("string"!=typeof e)throw new te('"url" should be type: string.',{code:"INVALID_PARAMETER"});let n=e.split("?"),r=n.shift()||"",i=n.length?"?"+n.join("?"):"",s=be.Url(r);e=s+i;let o=!1,a=s.split("/"),c=a[2].split("."),u=null;3===c.length&&"skapi"===c[1]&&(u=c[0],o=!0);let l=a.slice(3),h=!1;if(!o&&("auth"===l[0]||"publ"===l[0]))try{be.UserId(l[2]),be.UserId(l[3]),h="auth"==l[0],o=!0}catch{throw new te("Invalid file url.",{code:"INVALID_PARAMETER"})}let d=u?null:l[1];if(t=be.Params(t,{expires:["number",()=>0],dataType:["base64","blob","endpoint","text","info",()=>"download"],progress:"function",_ref:"string",_update:e=>e}),"info"===t?.dataType)return{url:e,filename:l[l.length-1],fileKey:l[l.length-2],access_group:"**"===l[6]?"private":"01"===l[6]?"authorized":"00"===l[6]?"public":parseInt(l[6]),uploader:l[3],record_id:"records"===l[4]?l[5]:"N/A",filesize:oe(l[9]),uploaded:oe(l[8])};let f=e.split("/").slice(-1)[0],p=t.expires;if(p){if(!o)throw new te("Expires option can only be used on skapi cdn endpoints.",{code:"INVALID_PARAMETER"});if(p<0)throw new te('"config.expires" should be > 0. (seconds)',{code:"INVALID_PARAMETER"});let t={request:u?"get-host":"get",id:u||l[5],key:e,expires:p};d&&(t.service=d),e=(await ht.bind(this)("get-signed-url",t,{auth:!0})).url}else if(h){let n=Math.floor(Date.now()/1e3);if(!this.bearerToken&&(!this.session?.idToken?.payload?.exp||this.session.idToken.payload.exp<n)){this.log("getFile:requesting new token",null);try{await Pe.bind(this)().getSession({refreshToken:!0}),this.log("getFile:received new tokens",{exp:this.session?.idToken?.payload?.exp,currTime:n,expiresIn:this.session?.idToken?.payload?.exp-n,token:this.session?.accessToken?.jwtToken,refreshToken:this.session?.refreshToken?.token})}catch(e){throw this.log("getFile:new token error",e),new te("User login is required.",{code:"INVALID_REQUEST"})}}let r=this.bearerToken||this.session?.idToken?.jwtToken;if(!r||!this.user?.user_id)throw new te("User login is required.",{code:"INVALID_REQUEST"});e+=`${e.includes("?")?"&":"?"}t=${encodeURIComponent(r)}`;let i="**"===l[6]?"**":parseInt(l[6]),s=this.user?.access_group??-1;if(this.user.user_id!==l[3]&&("**"===i||s<i)){let n=l[5];if(this.__private_access_key[n]&&"string"==typeof this.__private_access_key[n])e+=`&p=${encodeURIComponent(this.__private_access_key[n])}`;else if(this.owner!==this.host)try{let r=await this.requestPrivateRecordAccessKey({record_id:n,reference_id:t?._ref});e+=`&p=${encodeURIComponent(r)}`}catch(e){}}}if("endpoint"===t?.dataType)return t._update&&(t._update.url=e),e;if("download"===t?.dataType){let t=document.createElement("a");return t.href=e,document.body.appendChild(t),t.setAttribute("download",f),t.target="_blank",t.click(),document.body.removeChild(t),null}return new Promise(async(n,r)=>{try{let r=await ht.bind(this)(e,null,{method:"get",contentType:null,responseType:"text"===t?.dataType?"text":"blob",fetchOptions:{progress:t?.progress}},{ignoreService:!0});if("base64"===t?.dataType){const e=new FileReader;e.onloadend=()=>n(e.result),e.readAsDataURL(r)}else n(r)}catch(e){r(e)}})}async function Rt(e,t=!1){e=he(e,{ignoreEmpty:!0}).data||{},"string"==typeof e?.table&&(e.table={name:e.table,access_group:0});let n="",r=function(e){if(!e.record_id&&!e.unique_id)return null;let t={};return e?.service&&(t.service=e.service),e?.owner&&(t.owner=e.owner),e?.record_id?t.record_id=be.specialChars(e.record_id,"record_id",!1,!1):e?.unique_id&&(t.unique_id=e.unique_id),t}(e);if(r)n=(e=r).record_id||e.unique_id,"string"==typeof n&&("string"==typeof this.__private_access_key?.[n]&&(e.private_key=this.__private_access_key?.[n]||void 0),this.__my_unique_ids[n]&&(t?delete this.__my_unique_ids[n]:e.record_id=this.__my_unique_ids[n]));else{let t=await Oe.bind(this)(),r=e?.reference,i="";r?.record_id||r?.unique_id?(n=r.record_id||r.unique_id,n&&"string"==typeof this.__private_access_key?.[n]&&(e.private_key=this.__private_access_key?.[n]||void 0),e.reference=n):r?.user_id&&(i=r.user_id,e.reference=i),e=be.Params(e||{},vt.bind(this)(e),i||t?[]:["table"],{ignoreEmpty:!0})}return{query:e,is_reference_fetch:n}}async function Ut(e,t){await this.__connection;let n=await Rt.bind(this)(e),r=n.is_reference_fetch,i=await ht.bind(this)("get-records",n.query,{fetchOptions:t,auth:!!this.__user,method:this.__user?"post":"get"});r&&i?.reference_private_key&&"string"==typeof i.reference_private_key&&(this.__private_access_key[r]=i.reference_private_key);let s=[];for(let e in i.list)s.push(Et.bind(this)(i.list[e]));return i.list=await Promise.all(s),i}async function Dt(e,t,n){await this.__connection;let r="";if(!t)throw new te('"config" argument is required.',{code:"INVALID_PARAMETER"});let i=!this.__user;if("string"==typeof t.table&&(t.table={name:t.table}),!t.record_id){if(!t.table||"object"!=typeof t.table)throw new te('"table.name" is required.',{code:"INVALID_PARAMETER"});Object.prototype.hasOwnProperty.call(t.table,"access_group")||(t.table.access_group=0)}t.table?.subscription&&(t.table?.subscription?.is_subscription_record?Object.assign(t.table.subscription,{group:1}):!1!==t.table?.subscription?.is_subscription_record&&(t.record_id||t.table.subscription?.is_subscription_record)||Object.assign(t.table.subscription,{group:null}),delete t.table.subscription?.is_subscription_record);let s=be.Params(t||{},{record_id:["string",()=>{if(!t.table||!t.table.name)throw new te('"table.name" is required.',{code:"INVALID_PARAMETER"})}],unique_id:"string",readonly:"boolean",table:{name:e=>wt(e,"table name",!0,!0),subscription:{group:e=>1===e?1:null,upload_to_feed:"boolean",notify_subscribers:"boolean",feed_referencing_records:"boolean",notify_referencing_records:"boolean"},access_group:bt.bind(this)},source:{referencing_limit:e=>{if(null===e)return null;if("number"==typeof e){if(0>e)throw new te('"reference_limit" should be >= 0',{code:"INVALID_PARAMETER"});if(e>4503599627370546)throw new te('"reference_limit" should be <= 4503599627370546',{code:"INVALID_PARAMETER"});return e}throw new te('"reference_limit" should be type: <number | null>',{code:"INVALID_PARAMETER"})},prevent_multiple_referencing:"boolean",can_remove_referencing_records:"boolean",only_granted_can_reference:"boolean",allow_granted_to_grant_others:"boolean",referencing_index_restrictions:e=>{if(void 0===e)return;if(!e)return null;if(Array.isArray(e)&&!e.length)return null;let t={name:[e=>wt(e,'"name" in "index_restrictions"',!0,!1)],value:e=>At(e),condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne",()=>null],range:t=>{if(null!==t&&typeof e.value!=typeof t)throw new te('Index restriction "range" type should match the type of "value".',{code:"INVALID_PARAMETER"});if(!e.hasOwnProperty("value"))throw new te('Index restriction "value" is required.',{code:"INVALID_PARAMETER"});return t}};Array.isArray(e)||(e=[e]);let n=e.map(e=>be.Params(e,t));if(n.length)for(let e of n)e.condition&&e.hasOwnProperty("range")&&delete e.range;return n}},reference:e=>{if(null===e)return{record_id:null};if(e){if("string"==typeof e)return r=e,this.__my_unique_ids[e]?this.__my_unique_ids[e]:e;if("object"!=typeof e)throw new te('"reference" should be type: <string | object>.',{code:"INVALID_PARAMETER"});return be.Params(e,{unique_id:"string",record_id:e=>null==e?e:(r=e,"string"==typeof this.__private_access_key?.[e]&&(t.reference_private_key=this.__private_access_key[e]||void 0),be.specialChars(e,'"reference.record_id"',!1,!1))})}},index:{name:e=>wt(e,"index.name",!0,!1),value:e=>At(e)},tags:e=>null==e?e:("string"==typeof e&&(e=e.split(",").map(e=>e.trim())),be.specialChars(e,"tag",!1,!0)),remove_bin:e=>{if(!e)return null;let t=[];if(!Array.isArray(e))throw new te('"remove_bin" should be type: <string[] | BinaryFile[] | null>',{code:"INVALID_PARAMETER"});for(let n of e)if("string"==typeof n)t.push(decodeURIComponent(n.split("?")[0]));else{if(!(n.url&&n.size&&n.filename))throw new te('"remove_bin" should be type: <string[] | BinaryFile[] | null>',{code:"INVALID_PARAMETER"});{let e=n.url.split("/").slice(0,3).join("/")+"/"+n.path;t.push(e)}}return t},progress:"function"}),o=t.progress||null;delete s.progress;let a={auth:!!this.__user,method:"post"},c=null,u=[],l=he(e);if(n&&Array.isArray(n)&&n.length&&(u=u.concat(n)),l.files&&Array.isArray(l.files)&&l.files.length&&(u=u.concat(l.files)),i){if(s.record_id)throw new te("Public users cannot update existing records.",{code:"INVALID_REQUEST"});if("public"!==s.table.access_group&&0!==s.table.access_group)throw new te("Public users can only post records to public tables.",{code:"INVALID_REQUEST"});if(s.table.subscription)throw new te("Public users cannot post subscription records.",{code:"INVALID_REQUEST"});if(s.remove_bin)throw new te("Public users cannot remove files from records.",{code:"INVALID_REQUEST"});if(s.unique_id)throw new te("Public users cannot set unique_id for records.",{code:"INVALID_REQUEST"})}c=Object.assign({data:l.data},s);let h={};"function"==typeof o&&(h.progress=o),Object.keys(h).length&&Object.assign(a,{fetchOptions:h});let d=await ht.bind(this)("post-record",c,a);if(u.length){let e=new FormData;for(let t of u)e.append(t.name,t.file,t.file.name);let t={record_id:d.rec,progress:o};s.hasOwnProperty("service")&&(t.service=s.service);let{bin_endpoints:n}=await gt.bind(this)(e,t);d.bin?d.bin.push(...n):d.bin=n}r&&"string"==typeof d?.reference_private_key&&(this.__private_access_key[r]=d.reference_private_key),window.sessionStorage.setItem(`${this.service}:post:${d.rec}`,JSON.stringify(d));let f=await Et.bind(this)(d,"called from postRecord");return f.unique_id&&(this.__my_unique_ids[f.unique_id]=f.record_id,window.sessionStorage.setItem(`${this.service}:uniqueids`,JSON.stringify(this.__my_unique_ids))),f}async function Pt(e,t){let n=await ht.bind(this)("get-table",be.Params(e||{},{table:"string",condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}),Object.assign({auth:!!this.__user},{fetchOptions:t})),r={cnt_rec:"number_of_records",tbl:"table",srvc:"service"};if(Array.isArray(n?.list))for(let e of n.list)for(let t in r)e.hasOwnProperty(t)&&(e[r[t]]=e[t],delete e[t]);return n}async function Ct(e,t){if(!e?.table)throw new te('"table" is required.',{code:"INVALID_PARAMETER"});let n=be.Params(e||{},{table:"string",index:e=>be.specialChars(e,"index name",!0,!1),order:{by:["average_number","total_number","number_count","average_bool","total_bool","bool_count","string_count","index_name","number_of_records"],value:["string","number","boolean"],condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}},["table"]);if(n.hasOwnProperty("order")){if(!n.order?.by)throw new te('"order.by" is required.',{code:"INVALID_PARAMETER"});if(n.order.hasOwnProperty("condition")&&!n.order.hasOwnProperty("value"))throw new te('"value" is required for "condition".',{code:"INVALID_PARAMETER"});if(n.hasOwnProperty("index")&&"."!==n.index.substring(n.index.length-1))throw new te('"index" should be a parent index name of the compound index when using "order.by"',{code:"INVALID_PARAMETER"})}let r=await ht.bind(this)("get-index",n,Object.assign({auth:!!this.__user},{fetchOptions:t})),i={cnt_bool:"boolean_count",cnt_numb:"number_count",totl_numb:"total_number",totl_bool:"total_bool",avrg_numb:"average_number",avrg_bool:"average_bool",cnt_str:"string_count"};return Array.isArray(r?.list)&&(r.list=r.list.map(e=>{let t=e.idx.split("/"),n={table:t[1],index:t[2],number_of_records:e.cnt_rec};for(let t in i)Object.prototype.hasOwnProperty.call(e,t)&&(n[i[t]]=e[t]);return n})),r}async function kt(e,t){let n=await ht.bind(this)("get-tag",be.Params(e||{},{table:"string",tag:"string",condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}),Object.assign({auth:!!this.__user},{fetchOptions:t}));return Array.isArray(n?.list)&&(n.list=n.list.map(e=>{let t=e.tag.split("/");return{table:t[1],tag:t[0],number_of_records:e.cnt_rec}})),n}async function Nt(e,t){let n=await ht.bind(this)("get-uniqueid",be.Params(e||{},{unique_id:"string",condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}),Object.assign({auth:!!this.__user},{fetchOptions:t}));if(Array.isArray(n?.list))for(let e in n.list){let t=n.list[e];n.list[e]={unique_id:t.unq,record_id:t.rec}}return n}async function Lt(e,t){await this.__connection;let n=await Rt.bind(this)(e,!0),r=n.is_reference_fetch,i=await ht.bind(this)("del-records",n.query,{auth:!0,fetchOptions:t});return r&&"string"==typeof i?.reference_private_key&&(this.__private_access_key[r]=i.reference_private_key),i?.message||i}function Ot(e){return Ft.bind(this)({record_id:e.record_id,user_id:e.user_id,execute:"add"})}function Mt(e){return Ft.bind(this)({record_id:e.record_id,user_id:e.user_id||null,execute:"remove"})}async function Vt(e,t){let n={record_id:e.record_id||void 0,user_id:e.user_id||void 0,execute:"list"};if(!n.record_id&&!n.user_id)throw new te("Either record_id or user_id must be provided.",{code:"INVALID_PARAMETER"});if(n.user_id)if("string"==typeof n.user_id)be.UserId(n.user_id),n.user_id=[n.user_id];else{if(!Array.isArray(n.user_id))throw new te("user_id should be type: <string | string[]>",{code:"INVALID_PARAMETER"});for(let e of n.user_id)be.UserId(e)}let r=await ht.bind(this)("grant-private-access",n,{auth:!0,fetchOptions:t});return r.list=r.list.map(e=>(e.rec_usr?(e.record_id=e.rec_usr.split("/")[0],e.user_id=e.rec_usr.split("/")[1]):e.usr_rec&&(e.user_id=e.usr_rec.split("/")[0],e.record_id=e.usr_rec.split("/")[1]),e)),r}function xt(e){let t=e.record_id,n=e.reference_id||void 0;if(!t)throw new te("Record ID is required.",{code:"INVALID_PARAMETER"});if("string"!=typeof t)throw new te("Record ID should be type: <string | string[]>",{code:"INVALID_PARAMETER"});if(n&&"string"!=typeof n)throw new te("Reference ID should be type: <string>",{code:"INVALID_PARAMETER"});if("string"==typeof this.__private_access_key[t])return Promise.resolve(this.__private_access_key[t]);if(St[t])return St[t];let r=ht.bind(this)("request-private-access-key",{record_id:t,reference_id:n},{auth:!0}).then(e=>{let n="string"==typeof e?e:e?.private_key;if("string"!=typeof n)throw new te("Invalid private access key response.",{code:"ERROR"});return this.__private_access_key[t]=n,n}).finally(()=>{delete St[t]});return St[t]=r,r}function Ft(e){e.execute;let t=be.Params(e,{record_id:"string",user_id:e=>{if(!e)throw new te("User ID is required.",{code:"INVALID_PARAMETER"});let t=e;if("string"==typeof t&&(t=[t]),t.length>100)throw new te("Cannot process more than 100 users at once.",{code:"INVALID_REQUEST"});for(let e of t)be.UserId(e,'User ID in "user_id"');return t},execute:["add","remove"]},["execute","record_id","user_id"]);return t.user_id||(t.user_id=null),ht.bind(this)("grant-private-access",t,{auth:!0})}const qt={},Bt={},$t={},jt={},Kt={};let Jt,Ht={},Wt={};function Qt(e,t,n){e[t]||(e[t]=[]),e[t].push(n)}async function zt(e,t,n){let r=[];if(e[t]){for(let i of e[t])if(i){let e=n(i);e instanceof Promise&&(e=await e),r.push(e)}delete e[t]}return r}async function Gt(e,t){if(!this?.session?.accessToken?.jwtToken)throw new te("Access token is required.",{code:"INVALID_PARAMETER"});let n=await this.__socket;async function r(e,t,n){this.log("answerSdpOffer from",t),await qt[t].setRemoteDescription(new RTCSessionDescription(e));const r=await qt[t].createAnswer();await qt[t].setLocalDescription(r),n.send(JSON.stringify({action:"rtc",uid:t,content:{sdpanswer:r},token:this.session.accessToken.jwtToken}))}qt?.[t]?e?(await zt(Wt,t,e=>r.bind(this)(e,t,n)),await r.bind(this)(e,t,n)):await zt(Wt,t,e=>r.bind(this)(e,t,n)):e&&Qt(Wt,t,e)}async function Yt(e,t){if(this.log("receiveIceCandidate",e),qt?.[t]&&qt[t]?.remoteDescription&&qt[t]?.remoteDescription?.type){if(!e)return zt(Ht,t,e=>qt[t].addIceCandidate(e));await zt(Ht,t,e=>qt[t].addIceCandidate(e)),await qt[t].addIceCandidate(e)}else Qt(Ht,t,e)}async function Zt(e){if("undefined"==typeof window||window._runningInNodeJS)throw new te("WebRTC is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});be.Params(e,{cid:e=>{if("string"!=typeof e)throw new te('"cid" should be type: <string>.',{code:"INVALID_PARAMETER"});if(e&&"cid:"!==e.slice(0,4))throw new te('"cid" should be a valid connection id.',{code:"INVALID_PARAMETER"});return e},close:"boolean"});let t=await this.__socket,{cid:n,close_all:r=!1}=e||{};if(!r&&!n)throw new te('"cid" is required.',{code:"INVALID_PARAMETER"});let i=e=>{if(!e)throw new te('"cid" is required.',{code:"INVALID_PARAMETER"});if(delete Wt[e],delete Ht[e],Bt[e]&&Object.values(Bt[e]).forEach(e=>{"closed"!==e.readyState&&e.close()}),delete Bt[e],qt?.[e]){"closed"!==qt[e].connectionState&&(qt[e].close(),t.send(JSON.stringify({action:"rtc",uid:e,content:{hungup:this.user.user_id},token:this.session.accessToken.jwtToken})));let n={type:"connectionstatechange",target:qt[e],timestamp:(new Date).toISOString(),state:qt[e].connectionState,iceState:qt[e].iceConnectionState,signalingState:qt[e].signalingState};Kt[e]&&Kt[e](n),this.log("closeRTC",n)}delete Kt[e],delete jt[e],delete $t[e],delete qt[e]};if(r)for(let e in qt)i(e);else i(n);this.log("Cleaning up media stream..."),this.__mediaStream&&(this.__mediaStream.getTracks().forEach(e=>{e.stop()}),this.__mediaStream=null)}async function Xt(e){if(e instanceof MediaStream)return e;if(!e.video&&!e.audio){const e=new MediaStream,t=document.createElement("canvas");t.width=1,t.height=1;const n=t.captureStream().getVideoTracks()[0];return e.addTrack(n),e}return window.navigator.mediaDevices.getUserMedia(e)}async function en(e,t){if("undefined"==typeof window||window._runningInNodeJS)throw new te("WebRTC is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if("function"!=typeof t)throw new te("Callback is required.",{code:"INVALID_PARAMETER"});if(!this?.session?.accessToken?.jwtToken)throw new te("Access token is required.",{code:"INVALID_PARAMETER"});e=be.Params(e,{cid:e=>{if("string"!=typeof e)throw new te('"cid" should be type: <string>.',{code:"INVALID_PARAMETER"});if(e&&"cid:"!==e.slice(0,4))throw new te('"cid" should be a valid connection id.',{code:"INVALID_PARAMETER"});return e},ice:["string",()=>"stun:stun.skapi.com:3468"],media:e=>e,channels:["text-chat","file-transfer","video-chat","voice-chat","gaming",{ordered:"boolean",maxPacketLifeTime:"number",maxRetransmits:"number",protocol:"string"},()=>[{ordered:!0,maxPacketLifeTime:10,protocol:"default"}]]},["cid"]);let{cid:n,ice:r}=e;if(!(e?.media instanceof MediaStream)&&(e?.media?.video||e?.media?.audio)&&"localhost"!==window.location.hostname&&"https:"!==window.location.protocol)throw new te("Media stream is only supported on either localhost or https.",{code:"INVALID_REQUEST"});let i=this.__socket?await this.__socket:this.__socket;if(!i)throw new te("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});if(1!==i.readyState)throw new te("Realtime connection is not ready.",{code:"INVALID_REQUEST"});const s={iceServers:[{urls:r}]};qt?.[n]||(qt[n]=new RTCPeerConnection(s)),e?.media&&(this.__mediaStream=await Xt(e.media),this.__mediaStream.getTracks().forEach(e=>{qt[n].addTrack(e,this.__mediaStream)})),Kt[n]=t,Bt[n]||(Bt[n]={});for(let t=0;t<e.channels.length;t++){let r=e.channels[t];if("string"==typeof r)switch(r){case"text-chat":r={ordered:!0,maxRetransmits:10,protocol:"text-chat"};break;case"file-transfer":r={ordered:!1,maxPacketLifeTime:3e3,protocol:"file-transfer"};break;case"video-chat":r={ordered:!0,maxRetransmits:10,protocol:"video-chat"};break;case"voice-chat":r={ordered:!0,maxRetransmits:10,protocol:"voice-chat"};break;case"gaming":r={ordered:!1,maxPacketLifeTime:100,protocol:"gaming"};break;default:r={ordered:!0,maxRetransmits:10,protocol:"default"}}let i=r.protocol||"default";if(Object.keys(Bt[n]).includes(i))throw new te(`Data channel with the protocol "${i}" already exists.`,{code:"INVALID_REQUEST"});let s=qt[n].createDataChannel(i,r);Bt[n][i]=s}for(let e in Bt[n]){let t=Bt[n][e];on.bind(this)(n,t)}return sn.bind(this)(n,["onnegotiationneeded"]),await nn.bind(this)(n),{hangup:()=>$t[n]&&$t[n](!1),connection:new Promise(e=>{$t[n]=(t=>{if(this.log("receiver picked up the call",n),!t)return Zt.bind(this)({cid:n}),null;qt[n].onnegotiationneeded=()=>{this.log("onnegotiationneeded",`sending offer to "${n}".`),nn.bind(this)(n),Kt[n]&&Kt[n]({type:"negotiationneeded",target:qt[n],timestamp:(new Date).toISOString(),signalingState:qt[n].signalingState,connectionState:qt[n].iceConnectionState,gatheringState:qt[n].iceGatheringState})},e({target:qt[n],channels:Bt[n],hangup:()=>Zt.bind(this)({cid:n}),media:this.__mediaStream})}).bind(this)})}}function tn(e){return async(t,n)=>{t=he(t=t||{}).data;let r=e.sender_cid,i=await this.__socket;if(!jt[r])return null;if("function"!=typeof n)throw new te("Callback is required.",{code:"INVALID_PARAMETER"});if(!(t?.media instanceof MediaStream)&&(t?.media?.video||t?.media?.audio)&&"localhost"!==window.location.hostname&&"https:"!==window.location.protocol)throw new te("Media stream is only supported on either localhost or https.",{code:"INVALID_REQUEST"});let{ice:s="stun:stun.skapi.com:3468"}=t;return qt?.[r]||(qt[r]=new RTCPeerConnection({iceServers:[{urls:s}]})),t?.media&&(this.__mediaStream=await Xt(t.media),this.__mediaStream.getTracks().forEach(e=>{qt[r].addTrack(e,this.__mediaStream)})),delete jt[r],Kt[r]=n,Bt[r]||(Bt[r]={}),qt[r].ondatachannel=e=>{this.log("ondatachannel",`received data channel "${e.channel.label}".`);const t=e.channel;Bt[r][t.label]=t,on.bind(this)(r,t)},sn.bind(this)(r,["onnegotiationneeded"]),await Gt.bind(this)(null,r),await Yt.bind(this)(null,r),i.send(JSON.stringify({action:"rtc",uid:r,content:{pickup:this.user.user_id},token:this.session.accessToken.jwtToken})),{target:qt[r],channels:Bt[r],hangup:()=>Zt.bind(this)({cid:r}),media:this.__mediaStream}}}async function nn(e){if(!this?.session?.accessToken?.jwtToken)throw new te("Access token is required.",{code:"INVALID_PARAMETER"});this.log("sendOffer",e);let t=await this.__socket;const n=await qt[e].createOffer();await qt[e].setLocalDescription(n);let r=qt[e].localDescription;this.log("rtcSdpOffer to",r),t.send(JSON.stringify({action:"rtc",uid:e,content:{sdpoffer:r},token:this.session.accessToken.jwtToken}))}async function rn(e,t){if(!this?.session?.accessToken?.jwtToken)throw new te("Access token is required.",{code:"INVALID_PARAMETER"});this.log("sendIceCandidate to",t);let n=await this.__socket;if(!e.candidate)return void this.log("candidate-end","all ice candidates have been sent");let r=Kt[t]||(()=>{}),i=e.candidate;this.log("ice gathering state set to",qt[t].iceGatheringState),r({type:"icecandidate",target:qt[t],timestamp:(new Date).toISOString(),candidate:e.candidate.candidate,sdpMid:e.candidate.sdpMid,sdpMLineIndex:e.candidate.sdpMLineIndex,usernameFragment:e.candidate.usernameFragment,protocol:e.candidate.protocol,gatheringState:qt[t].iceGatheringState,connectionState:qt[t].iceConnectionState}),n.send(JSON.stringify({action:"rtc",uid:t,content:{candidate:i},token:this.session.accessToken.jwtToken}))}function sn(e,t){let n=new Set(t),r=Kt[e]||(e=>{}),i=qt[e];const s={ontrack:e=>{r({type:"track",target:i,timeStamp:e.timeStamp,streams:e.streams,track:e.track})},onicecandidate:t=>{rn.bind(this)(t,e),t.candidate?r({type:"icecandidate",target:i,timestamp:(new Date).toISOString(),candidate:t.candidate.candidate,sdpMid:t.candidate.sdpMid,sdpMLineIndex:t.candidate.sdpMLineIndex,usernameFragment:t.candidate.usernameFragment,protocol:t.candidate.protocol,gatheringState:i.iceGatheringState,connectionState:i.iceConnectionState}):r({type:"icecandidateend",target:i,timestamp:(new Date).toISOString()})},onicecandidateerror:e=>{r({type:"icecandidateerror",target:i,timestamp:(new Date).toISOString(),errorCode:e.errorCode,errorText:e.errorText,url:e.url,hostCandidate:e.hostCandidate,gatheringState:i.iceGatheringState,connectionState:i.iceConnectionState})},oniceconnectionstatechange:()=>{r({type:"iceconnectionstatechange",target:i,timestamp:(new Date).toISOString(),state:i.iceConnectionState,gatheringState:i.iceGatheringState,signalingState:i.signalingState})},onicegatheringstatechange:()=>{r({type:"icegatheringstatechange",target:i,timestamp:(new Date).toISOString(),state:i.iceGatheringState,connectionState:i.iceConnectionState,signalingState:i.signalingState})},onsignalingstatechange:()=>{r({type:"signalingstatechange",target:i,timestamp:(new Date).toISOString(),state:i.signalingState,connectionState:i.iceConnectionState,gatheringState:i.iceGatheringState})},onnegotiationneeded:()=>{nn.bind(this)(e),r({type:"negotiationneeded",target:i,timestamp:(new Date).toISOString(),signalingState:i.signalingState,connectionState:i.iceConnectionState,gatheringState:i.iceGatheringState})},onconnectionstatechange:()=>{r({type:"connectionstatechange",target:i,timestamp:(new Date).toISOString(),state:i.connectionState,iceState:i.iceConnectionState,signalingState:i.signalingState});let t=i.connectionState;"disconnected"!==t&&"failed"!==t&&"closed"!==t||Zt.bind(this)({cid:e})}};for(const[e,t]of Object.entries(s))n.has(e)||(i[e]=t)}function on(e,t,n){let r=new Set(n),i=Kt[e]||(e=>{});const s={onmessage:e=>{let n={type:e.type,target:t,timeStamp:e.timeStamp,data:e.data,lastEventId:e.lastEventId,origin:e.origin,readyState:t.readyState,bufferedAmount:t.bufferedAmount};this.log(`${t.label}: message`,e.data),i(n)},onerror:e=>{let n={type:e.type,target:t,timeStamp:e.timeStamp,error:e.error.message,errorCode:e.error.errorDetail,readyState:t.readyState,label:t.label};this.log(`${t.label}: error`,e.error.message),i(n)},onclose:n=>{let r={type:n.type,target:t,timeStamp:n.timeStamp,readyState:t.readyState,label:t.label,id:t.id};this.log(`${t.label}: closed`,null),i(r),Bt[e]&&(delete Bt[e][t.label],0===Object.keys(Bt[e]).length&&Zt.bind(this)({cid:e}))},onbufferedamountlow:e=>{let n={target:t,bufferedAmount:t.bufferedAmount,bufferedAmountLowThreshold:t.bufferedAmountLowThreshold,type:e.type,timeStamp:e.timeStamp};this.log(`${t.label}: bufferedamountlow`,t.bufferedAmount),i(n)},onopen:e=>{this.log("dataChannel",`data channel: "${t.label}" is open and ready to send messages.`);let n={type:e.type,target:t,timeStamp:e.timeStamp,readyState:t.readyState,label:t.label,id:t.id,ordered:t.ordered,maxRetransmits:t.maxRetransmits,protocol:t.protocol};i(n)}};for(const[e,n]of Object.entries(s))r.has(e)||(t[e]=n)}let an=null,cn=!0,un=0;async function ln(){if("undefined"==typeof window||window._runningInNodeJS)throw new te("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.getProfile(),!this.session)throw new te("No access.",{code:"INVALID_REQUEST"});let e=await this.record_endpoint;return new WebSocket(e.websocket_private+"?token="+this.session.accessToken.jwtToken)}let hn=null;async function dn(){if("undefined"==typeof window||window._runningInNodeJS)throw new te("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});cn=!0;let e=this.__socket?await this.__socket:this.__socket;Zt.bind(this)({close_all:!0}),Jt&&gn.bind(this)({group:null}),un=0,an&&(an.terminate(),an=null);try{e&&e.close()}catch(e){}return window.removeEventListener("visibilitychange",hn),this.__socket=null,null}async function fn(e,t=50,n){if("undefined"==typeof window||window._runningInNodeJS)throw new te("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if("function"!=typeof e)throw new te("Callback must be a function.",{code:"INVALID_REQUEST"});if("reconnect"===n){if(this.__socket instanceof Promise){let e=await this.__socket;if(e.readyState!==WebSocket.CLOSED&&e.readyState!==WebSocket.CLOSING)return this.__socket}}else if(cn&&(hn=()=>{document.hidden||cn||fn.bind(this)(e,0,"reconnect")},this.__socket instanceof Promise))return this.__socket;an&&(an.terminate(),an=null),this.__socket=new Promise(async r=>{await Ue.bind(this)(),setTimeout(async()=>{let t=await ln.bind(this)();t.onopen=()=>{cn=!1,un=0,"reconnect"!==n&&window.addEventListener("visibilitychange",hn),this.log("realtime onopen","Connected to WebSocket server."),e({type:"success",message:"Connected to WebSocket server."}),Jt&&t.send(JSON.stringify({action:"joinRoom",rid:Jt,token:this.session.accessToken.jwtToken}));const i=new Blob(['\n let interval = 15000; // Set interval time 15 seconds\n\n function runInterval() {\n postMessage({ type: "ping" });\n setTimeout(runInterval, interval); // Use setTimeout instead of setInterval\n }\n\n runInterval(); // Start interval\n '],{type:"application/javascript"});an=new Worker(URL.createObjectURL(i)),an.onmessage=e=>{1===t.readyState&&t.send(JSON.stringify({action:"keepAlive"}))},r(t)},t.onmessage=async n=>{let r,i="";try{i=JSON.parse(decodeURI(n.data)),this.log("socket onmessage",i)}catch(e){return}switch(!0){case!!i?.["#message"]:r="message";break;case!!i?.["#private"]:r="private";break;case!!i?.["#notice"]:r="notice";break;case!!i?.["#rtc"]:r="rtc";break;case!!i?.["#error"]:r="error"}if(!r)return;let s={type:r,message:i?.["#rtc"]||i?.["#message"]||i?.["#private"]||i?.["#notice"]||i?.["#error"]||null,sender:i?.["#user_id"]||null,sender_cid:i?.["#scid"]?"cid:"+i["#scid"]:null,sender_rid:i?.["#srid"]||null,code:i?.["#code"]||null};if("notice"===r)e(s);else if("rtc"===r){if(s.sender!==this.user.user_id){let n=s.message;if(n.hungup)return $t[s.sender_cid]&&($t[s.sender_cid](!1),delete $t[s.sender_cid]),jt[s.sender_cid]&&delete jt[s.sender_cid],qt?.[s.sender_cid]&&Zt.bind(this)({cid:s.sender_cid}),s.type="rtc:closed",void e(s);if(n.candidate&&Yt.bind(this)(n.candidate,s.sender_cid),n.sdpoffer&&(Gt.bind(this)(n.sdpoffer,s.sender_cid),jt[s.sender_cid]||(jt[s.sender_cid]=s.sender_cid,delete s.message,s.connectRTC=tn.bind(this)(s),s.type="rtc:incoming",s.hangup=(()=>{qt[s.sender_cid]?Zt.bind(this)({cid:s.sender_cid}):jt[s.sender_cid]&&(delete jt[s.sender_cid],t.send(JSON.stringify({action:"rtc",uid:s.sender_cid,content:{hungup:this.user.user_id},token:this.session.accessToken.jwtToken})))}).bind(this),e(s))),n.pickup&&$t[s.sender_cid]&&($t[s.sender_cid](!0),delete $t[s.sender_cid]),n.sdpanswer&&qt[s.sender_cid]){if("have-local-offer"!==qt[s.sender_cid].signalingState)throw new te("Invalid signaling state.",{code:"INVALID_REQUEST"});await qt[s.sender_cid].setRemoteDescription(new RTCSessionDescription(n.sdpanswer))}}}else e(s)},t.onclose=()=>{cn?(this.log("realtime onclose","WebSocket connection closed."),e({type:"close",message:"WebSocket connection closed."})):(this.log("realtime onclose","WebSocket unexpected close."),e({type:"error",message:"Skapi: WebSocket unexpected close."}),un++,un<3?(this.log("realtime onclose","Reconnecting to WebSocket server..."+un),e({type:"reconnect",message:"Reconnecting to WebSocket server..."+un}),fn.bind(this)(e,3e3,"reconnect")):(this.log("realtime onclose","Max reconnection attempts reached."),e({type:"error",message:"Skapi: Max reconnection attempts reached."})))},t.onerror=()=>{this.log("realtime onerror","WebSocket connection error."),e({type:"error",message:"Skapi: WebSocket connection error."})}},t)})}async function pn(e,t,n){if("undefined"==typeof window||window._runningInNodeJS)throw new te("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});let r=this.__socket?await this.__socket:this.__socket;if(!r)throw new te("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});if(!t)throw new te("No recipient.",{code:"INVALID_REQUEST"});await Ue.bind(this)(),e=he(e).data;let i="";if(n&&(n=be.Params(n,{config:{always:"boolean"},title:"string",body:"string"},["title","body"]),i=JSON.stringify({title:n.title,body:n.body}),new Blob([i]).size>3072))throw new te("Notification size exceeds 3kb.",{code:"INVALID_PARAMETER"});if(1===r.readyState){try{be.UserId(t),r.send(JSON.stringify({action:"sendMessage",uid:t,content:e,notification:i,notificationConfig:n?.config||{},token:`IdT:${this.service}:${this.owner}:`+(this.bearerToken||this.session?.idToken?.jwtToken||"null")}))}catch(s){if(this.log("postRealtime:err",{err:s}),Jt!==t)throw new te(`User has not joined to the recipient group. Run joinRealtime({ group: "${t}" })`,{code:"INVALID_REQUEST"});r.send(JSON.stringify({action:"broadcast",rid:t,content:e,notification:i,notificationConfig:n?.config||{},token:`IdT:${this.service}:${this.owner}:`+(this.bearerToken||this.session?.idToken?.jwtToken||"null")}))}return{type:"success",message:"Message sent."}}throw new te("Realtime connection is not open. Try reconnecting with connectRealtime().",{code:"INVALID_REQUEST"})}async function gn(e){if("undefined"==typeof window||window._runningInNodeJS)throw new te("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});let t=this.__socket?await this.__socket:this.__socket;if(!t)throw new te("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});await Ue.bind(this)(),e=he(e,{nullIfEmpty:!0}).data;let{group:n=null}=e;if(!n&&!Jt)return{type:"success",message:"Left realtime message group."};if(null!==n&&"string"!=typeof n)throw new te('"group" must be a string | null.',{code:"INVALID_PARAMETER"});return t.send(JSON.stringify({action:"joinRoom",rid:n,token:this.session.accessToken.jwtToken})),Jt=n,{type:"success",message:n?`Joined realtime message group: "${n}".`:"Left realtime message group."}}async function _n(e,t){e=be.Params(e,{user_id:e=>be.UserId(e,'User ID in "user_id"'),group:["string",()=>{if(!Jt)throw new te('No group has been joined. Otherwise "group" is required.',{code:"INVALID_REQUEST"});return Jt}]});let n=await ht.bind(this)("get-ws-group",e,{fetchOptions:t,auth:!0,method:"post"});return n.list=n.list.map(e=>({user_id:e.uid.split("#")[1],cid:"cid:"+e.cid})),n}async function mn(e,t){if(await this.__connection,e||(e={searchFor:"group",value:" ",condition:">"}),(e=be.Params(e,{searchFor:["group","number_of_users",()=>"group"],value:["string","number",()=>e?.searchFor&&"number_of_users"===e?.searchFor?0:" "],condition:[">",">=","=","<","<=","!=","gt","gte","eq","lt","lte","ne"],range:["string","number"]})).condition||(" "!==e.value&&e.value?e.condition="=":e.condition=">"),e.range&&e.condition&&delete e.condition,"number_of_users"===e.searchFor&&"number"!=typeof e.value)throw new te('"value" must be a number.',{code:"INVALID_PARAMETER"});if("group"===e.searchFor&&"string"!=typeof e.value)throw new te('"value" must be a string.',{code:"INVALID_PARAMETER"});if(e.hasOwnProperty("range")&&typeof e.range!=typeof e.value)throw new te(`"range" must be a ${typeof e.value}.`,{code:"INVALID_PARAMETER"});let n=await ht.bind(this)("get-ws-group",e,{fetchOptions:t,auth:!0,method:"post"});return n.list=n.list.map(e=>({group:e.rid.split("#")[1],number_of_users:e.cnt})),n}const yn="undefined"!=typeof FormData,wn="undefined"!=typeof HTMLFormElement,bn="undefined"!=typeof SubmitEvent;async function An(e){let t=!1,n=e=>{for(let n in e)if("string"==typeof e[n]&&e[n].includes("$CLIENT_SECRET")){t=!0;break}};if(e=be.Params(e,{url:e=>{if(!e||"string"!=typeof e)throw new te('"url" should be type: <string>.',{code:"INVALID_PARAMETER"});return be.Url(e),e.includes("$CLIENT_SECRET")&&(t=!0),e},clientSecretName:"string",method:e=>{if(e&&"string"!=typeof e)throw new te('"method" should be either "GET" or "POST" or "DELETE" or "PUT".',{code:"INVALID_PARAMETER"});let t=e.toLowerCase();if("get"!==t&&"post"!==t&&"delete"!==t&&"put"!==t)throw new te('"method" should be either "GET" or "POST" or "DELETE" or "PUT".',{code:"INVALID_PARAMETER"});return t},headers:e=>{if(e&&"object"!=typeof e)throw new te('"headers" should be type: <object>.',{code:"INVALID_PARAMETER"});return n(e),e},data:e=>{if(e&&"object"!=typeof e)throw new te('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return n(e),e},params:e=>{if(e&&"object"!=typeof e)throw new te('"params" should be type: <object>.',{code:"INVALID_PARAMETER"});return n(e),e}},["clientSecretName","method","url"]),!t)throw new te(`At least one parameter value should include "$CLIENT_SECRET" in ${"post"===e.method.toLowerCase()?'"data"':'"params"'} or "headers".`,{code:"INVALID_PARAMETER"});await this.__connection;let r=!!this.__user;return ht.bind(this)("csr"+(r?"-public":""),e,{auth:r})}async function vn(e){await this.__connection;let t={name:"string",email:e=>(be.Email(e),e),subject:"string",message:"string"};return e=be.Params(e,t,["name","email","subject","message"]),await ht.bind(this)("send-inquiry",e),"SUCCESS: Inquiry has been sent."}async function Sn(e,t){if(await this.__connection,yn&&e instanceof FormData||wn&&e instanceof HTMLFormElement||bn&&e instanceof SubmitEvent){if(!t)throw new te("Url string as a second argument is required when form is passed.",{code:"INVALID_PARAMETER"});e={url:t,data:he(e).data,sync:!0}}let n={url:e=>be.Url(e),data:e=>e,sync:["boolean",()=>!0]};if(Array.isArray(e))for(let t of e)t=be.Params(t,n);else e=be.Params(e,n);return ht.bind(this)("post-secure",e,{auth:!0})}async function En(e,t){await this.__connection;let{auth:n=!1,method:r="POST",bypassAwaitConnection:i=!1,responseType:s,contentType:o,progress:a}=t||{};if(t=Object.assign({auth:n,method:r,bypassAwaitConnection:i,responseType:s,contentType:o},{fetchOptions:{progress:a}}),"object"!=typeof e&&("application/json"===o||void 0===o))throw new te('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return ht.bind(this)("mock",e,t)}async function In(e,t){await this.__connection,e=be.Params(e||{},{access_group:e=>{if("authorized"===e&&(e=1),"public"===e&&(e=0),"number"!=typeof e)throw new te('"access_group" should be type number.',{code:"INVALID_PARAMETER"});if(e<0)throw new te('"access_group" should be zero or a positive number.',{code:"INVALID_PARAMETER"});if(e>this.__user.access_group)throw new te("User has no access.",{code:"INVALID_REQUEST"});return e}});let n=await ht.bind(this)("get-feed",e,{auth:!0,fetchOptions:t});for(let e in n.list)n.list[e]=await Et.bind(this)(n.list[e]);return n}function Tn(e){if(e===this.__user.user_id)throw new te('"user_id" cannot be the user\'s own ID.',{code:"INVALID_PARAMETER"});return be.UserId(e,'"user_id"')}async function Rn(e,t){if(e=he(e,{ignoreEmpty:!0}).data,!(e=be.Params(e,{subscriber:e=>be.UserId(e,'User ID in "subscriber"'),subscription:Tn.bind(this),blocked:"boolean"})).subscriber&&!e.subscription)throw new te('At least either "subscriber" or "subscription" should have a value.',{code:"INVALID_PARAMETER"});let n=await ht.bind(this)("get-subscription",e,Object.assign({auth:!0},{fetchOptions:t}));return n.list=n.list.map(e=>{let t={};if(e.sub){let n=e.sub.split("#");t.subscriber=n[2],t.subscription=n[0]}else t.subscriber=e.subscriber,t.subscription=e.subscription;return t.timestamp=e?.timestamp||e.stmp,t.blocked=e?.blocked||"N"===e.grp.substring(0,1),Object.assign(t,e.opt),t}),n}async function Un(e){await this.__connection,e=be.Params(e,{user_id:Tn.bind(this),get_feed:["boolean",()=>!1],get_notified:["boolean",()=>!1],get_email:e=>{if(e&&!this.__user.email||!this.__user.email_verified)throw new te("User has no verified email address.",{code:"INVALID_REQUEST"});return!!e}},["user_id"]);let t=await ht.bind(this)("subscription",{subscribe:e.user_id,option:{get_feed:e.get_feed,get_notified:e.get_notified,get_email:e.get_email||!1}},{auth:!0}),n={};if(t.sub){let e=t.sub.split("#");n.subscriber=e[2],n.subscription=e[0]}else n.subscriber=t.subscriber,n.subscription=t.subscription;return n.timestamp=t?.timestamp||t.stmp,n.blocked=t?.blocked||"N"===t.grp.substring(0,1),Object.assign(n,t.opt),n}async function Dn(e){return await this.__connection,await ht.bind(this)("admin-newsletter-request",e,{auth:!0})}async function Pn(e){await this.__connection;let{user_id:t}=be.Params(e,{user_id:Tn.bind(this)},["user_id"]);return await ht.bind(this)("subscription",{unsubscribe:t},{auth:!0})}async function Cn(e){await this.__connection;let{user_id:t}=be.Params(e,{user_id:Tn.bind(this)},["user_id"]);return await ht.bind(this)("subscription",{block:t},{auth:!0})}async function kn(e){await this.__connection;let{user_id:t}=be.Params(e,{user_id:Tn.bind(this)},["user_id"]);return await ht.bind(this)("subscription",{unblock:t},{auth:!0})}async function Nn(e,t){await this.__connection;let n=await Oe.bind(this)();e=be.Params(e,{user_id:e=>{if(e!==this.__user.user_id&&!n)throw new te("No access.",{code:"INVALID_REQUEST"});return e},group:e=>{if("public"===e&&(e=0),"authorized"===e&&(e=1),"number"!=typeof e)throw new te('"group" should be type number | "public" | "authorized".',{code:"INVALID_PARAMETER"});return e}});let r=await ht.bind(this)("get-newsletter-subscription",e,{auth:!0,fetchOptions:t||null}),i=r?.list||r,s=[];Array.isArray(i)||(i=[]);for(let e of i){let t=e.subt.split("#"),n=!0;"@"===t[0].charAt(0)&&(n=!1,t[0]=t[0].substring(1));let r=parseInt(t[0]);s.push({timestamp:e.stmp,group:r,subscribed_email:t[1],active:n})}return r?.list?(r.list=s,r):s}async function Ln(e){await this.__connection;let t=be.Params(e||{},{email:e=>Array.isArray(e)&&e.length>0?1===e.length?be.Email(e[0]):e.map(e=>be.Email(e)):be.Email(e),group:["number","public","authorized","admin",e=>{if("string"!=typeof e||e.length>20||!/^[a-zA-Z0-9]+$/.test(e))throw new te('"group" should be an alphanumeric string without spaces and less than 20 characters.',{code:"INVALID_PARAMETER"});return e}],redirect:e=>be.Url(e)},this.__user?["group"]:["email","group"]);return ht.bind(this)(`subscribe-${this.__user?"":"public-"}newsletter`,t,{auth:!!this.__user})}async function On(e){await this.__connection;let t=be.Params(e||{},{group:e=>{if("string"!=typeof e||e.length>20||!/^[a-zA-Z0-9]+$/.test(e))throw new te('"group" should be an alphanumeric string without spaces and less than 20 characters.',{code:"INVALID_PARAMETER"});return e},restriction:e=>{if("number"!=typeof e||e<0||e>99)throw new te('"restriction" should be a number between 0 and 99.',{code:"INVALID_PARAMETER"});return e}},["group","restriction"]);return ht.bind(this)("register-newsletter-group",t,{auth:!0})}async function Mn(e){return await this.__connection,await ht.bind(this)("newsletter-group-endpoint",e,{auth:!0})}async function Vn(e){await this.__connection,e=be.Params(e,{group:["number","public","authorized","admin"]},["group"]);let t=Object.assign({action:"unsubscribe"},e);return ht.bind(this)("subscribe-newsletter",t,{auth:!0})}async function xn(e,t){let n=await Oe.bind(this)(),r={message_id:"string",timestamp:"number",read:"number",complaint:"number",subject:"string",bounced:"number"};e||(t=Object.assign({ascending:!1},t||{})),e=(e=he(e).data)||{searchFor:"timestamp",value:Date.now(),condition:"<",group:"public"};let i=0===(e=be.Params(e,{searchFor:["message_id","timestamp","subject","complaint","read","bounced"],value:t=>{if(typeof t!==r[e.searchFor])throw new te(`"value" type does not match the type of "${e.searchFor}" index.`,{code:"INVALID_PARAMETER"});if("string"==typeof t&&!t)throw new te('"value" should not be empty string.',{code:"INVALID_PARAMETER"});return t},range:t=>{if(!e.hasOwnProperty("value")||typeof t!=typeof e.value)throw new te('"range" should match type of "value".',{code:"INVALID_PARAMETER"});return t},condition:[">",">=","=","<","<=","gt","gte","eq","lt","lte",()=>"="],group:e=>{if("public"===e)return 0;if(!this.session)throw new te("User should be logged in.",{code:"INVALID_REQUEST"});if("authorized"===e)return 1;if("number"==typeof e){if(!n&&e>parseInt(this.user?.access_group||this.session?.idToken?.payload?.access_group))throw new te("User has no access.",{code:"INVALID_REQUEST"});return e}throw new te('"group" should be type: number | "public" | "authorized".',{code:"INVALID_PARAMETER"})}},["searchFor","value","group"])).group?"get-public-newsletters":"get-newsletters",s=await ht.bind(this)(i,e,Object.assign({method:"get",auth:"get-public-newsletters"!==i||!!this.__user},{fetchOptions:t})),o={message_id:"mid",timestamp:"stmp",complaint:"cmpl",read:"read",subject:"subj",bounced:"bnce",url:"url",delivered:"delv"},a={message_id:"",timestamp:0,complaint:0,read:0,subject:"",bounced:"",url:"",delivered:0};return s.list=s.list.map(e=>{let t={};for(let n in o)t[n]=e[o[n]]||a[n];return t.bounced=String(t.bounced),t}),s}async function Fn(e){let t=be.Params(e,{user_id:e=>be.UserId(e,'"user_id"')},["user_id"]);if(t=t?.service&&t?.owner?{service:t?.service,owner:t?.owner,block:t.user_id}:{block:t.user_id},!await Oe.bind(this)()){if(!this.__user)throw new te("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new te("Invalid access.",{code:"INVALID_REQUEST"})}return await ht.bind(this)("block-account",t,{auth:!0})}async function qn(e){let t=be.Params(e,{user_id:e=>be.UserId(e,'"user_id"')},["user_id"]);if(t=t?.service&&t?.owner?{service:t?.service,owner:t?.owner,unblock:t.user_id}:{unblock:t.user_id},!await Oe.bind(this)()){if(!this.__user)throw new te("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new te("Invalid access.",{code:"INVALID_REQUEST"})}return await ht.bind(this)("block-account",t,{auth:!0})}async function Bn(e){let t=be.Params(e,{user_id:e=>be.UserId(e,'"user_id"')},["user_id"]);if(t=t?.service&&t?.owner?{service:t?.service,owner:t?.owner,delete:t.user_id}:{delete:t.user_id},!await Oe.bind(this)()){if(!this.__user)throw new te("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new te("Invalid access.",{code:"INVALID_REQUEST"})}return await ht.bind(this)("remove-account",t,{auth:!0})}async function $n(e,t){let n={email:e=>be.Email(e),password:e=>be.Password(e),name:"string",username:"string",gender:"string",address:e=>e?"string"==typeof e?e:"object"==typeof e?JSON.stringify(e):void 0:"",birthdate:e=>be.Birthdate(e),phone_number:e=>be.PhoneNumber(e),picture:e=>e?be.Url(e):void 0,profile:e=>e?be.Url(e):void 0,website:e=>e?be.Url(e):void 0,nickname:"string",misc:"string",email_public:["boolean",()=>!1],gender_public:["boolean",()=>!1],address_public:["boolean",()=>!1],birthdate_public:["boolean",()=>!1],phone_number_public:["boolean",()=>!1],openid_id:"string",access_group:e=>{try{"string"==typeof e&&(e="admin"===e?99:parseInt(e))}catch(e){throw new te('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if("number"!=typeof e||e<1||e>100)throw new te('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"});return e}},r=be.Params(e,n,["email"]);if(t=be.Params(t,{confirmation_url:e=>{let t=e;if("string"!=typeof e)throw new te('"options.confirmation_url" should be type: <string>.',{code:"INVALID_PARAMETER"});if(t=be.Url(e),t&&!r.email)throw new te('"email" is required for signup confirmation.',{code:"INVALID_PARAMETER"});return t},email_subscription:e=>{if("boolean"!=typeof e)throw new te('"options.email_subscription" should be type: <boolean>.',{code:"INVALID_PARAMETER"});if(!t?.confirmation_url)throw new te('"options.confirmation_url" is required for email subscription.',{code:"INVALID_PARAMETER"});return e},template:e=>{if("object"!=typeof e||!e.url||!e.subject)throw new te('"options.template" should be type: <object> with "url" and "subject".',{code:"INVALID_PARAMETER"});return{url:be.Url(e.url),subject:e.subject}}}),r.signup_confirmation=t?.confirmation_url||!0,r.email_subscription=t?.email_subscription||!1,r.template=t?.template||{},!await Oe.bind(this)()){if(!this.__user)throw new te("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new te("Invalid access.",{code:"INVALID_REQUEST"})}return await ht.bind(this)("admin-signup",r,{auth:!0})}async function jn(e){let t={email:e=>be.Email(e),password:e=>be.Password(e),openid_id:"string",name:"string",username:"string",gender:"string",address:e=>e?"string"==typeof e?e:"object"==typeof e?JSON.stringify(e):void 0:"",birthdate:e=>be.Birthdate(e),phone_number:e=>be.PhoneNumber(e),picture:e=>e?be.Url(e):"",profile:e=>e?be.Url(e):"",website:e=>e?be.Url(e):"",nickname:"string",misc:"string",email_public:["boolean",()=>!1],gender_public:["boolean",()=>!1],address_public:["boolean",()=>!1],birthdate_public:["boolean",()=>!1],phone_number_public:["boolean",()=>!1],access_group:e=>{try{"string"==typeof e&&(e=parseInt(e))}catch(e){throw new te('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if("number"!=typeof e||e<1||e>100)throw new te('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"});return e}},n=be.Params(e,t,["email","password"]);if(!await Oe.bind(this)()){if(!this.__user)throw new te("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new te("Invalid access.",{code:"INVALID_REQUEST"})}return await ht.bind(this)("admin-signup",n,{auth:!0})}async function Kn(e){if(e=be.Params(e,{user_id:e=>be.UserId(e,'"user_id"'),access_group:e=>{try{"string"==typeof e&&(e=parseInt(e))}catch(e){throw new te('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if("number"==typeof e&&e>0&&e<100)return e;throw new te('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"})}},["user_id","access_group"]),!await Oe.bind(this)()){if(!this.__user)throw new te("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new te("Invalid access.",{code:"INVALID_REQUEST"})}return await ht.bind(this)("grant-access",e,{auth:!0})}async function Jn(e,t){if(e=be.Params(e,{email:"string"}),!await Oe.bind(this)()){if(!this.__user)throw new te("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new te("Invalid access.",{code:"INVALID_REQUEST"})}let n=await ht.bind(this)("invitation-list",Object.assign({mode:"search"},e),{fetchOptions:t,auth:!0});return n.list=n.list.map(e=>de(e.user)),n}async function Hn(e){if(e=be.Params(e,{email:e=>be.Email(e)},["email"]),!await Oe.bind(this)()){if(!this.__user)throw new te("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new te("Invalid access.",{code:"INVALID_REQUEST"})}return await ht.bind(this)("invitation-list",Object.assign({mode:"cancel"},e),{auth:!0})}async function Wn(e){if(e=be.Params(e,{email:e=>be.Email(e)},["email"]),!await Oe.bind(this)()){if(!this.__user)throw new te("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new te("Invalid access.",{code:"INVALID_REQUEST"})}return await ht.bind(this)("invitation-list",Object.assign({mode:"resend"},e),{auth:!0})}async function Qn(e){if("undefined"==typeof window||window._runningInNodeJS)throw new te("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.__connection,!e.endpoint)throw new te("Missing parameter: endpoint",{code:"INVALID_PARAMETER"});if(!e.keys||!e.keys.p256dh||!e.keys.auth)throw new te("Missing parameter: keys.p256dh or keys.auth",{code:"INVALID_PARAMETER"});return await ht.bind(this)("store-subscription",{endpoint:e.endpoint,keys:e.keys},{auth:!0}),"SUCCESS: Subscribed to receive notifications."}async function zn(e){if("undefined"==typeof window||window._runningInNodeJS)throw new te("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.__connection,!e.endpoint)throw new te("Missing parameter: endpoint",{code:"INVALID_PARAMETER"});if(!e.keys||!e.keys.p256dh||!e.keys.auth)throw new te("Missing parameter: keys.p256dh or keys.auth",{code:"INVALID_PARAMETER"});return await ht.bind(this)("delete-subscription",{endpoint:e.endpoint,keys:e.keys},{auth:!0}),"SUCCESS: Unsubscribed from notifications."}async function Gn(){if("undefined"==typeof window||window._runningInNodeJS)throw new te("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});return await this.__connection,{VAPIDPublicKey:await ht.bind(this)("get-vapid-public-key",null,{auth:!0})}}async function Yn(e,t){if("undefined"==typeof window||window._runningInNodeJS)throw new te("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});await this.__connection;let{title:n,body:r}=he(e||{},{nullIfEmpty:!0}).data;if(!n)throw new te("Missing parameter: message title",{code:"INVALID_PARAMETER"});if(!r)throw new te("Missing parameter: message body",{code:"INVALID_PARAMETER"});const i={title:n,body:r};return t?("string"==typeof t&&(t=[t]),i.user_ids=t):i.user_ids="all_users",await ht.bind(this)("push-notification",i,{auth:!0}),"SUCCESS: Notification sent."}async function Zn(e){return await this.__connection,e=be.Params(e,{spell:"string",name:"string",magic:"object"},["spell","name"]),await ht.bind(this)("castspell",e)}async function Xn(e){return await this.__connection,e=be.Params(e,{search_option:["spell","name"],value:"string",condition:["starts_with","exact"]},["search_option","value","condition"]),await ht.bind(this)("getspell",e)}async function er(e){await this.__connection,e=be.Params(e,{message:"string",name:"string"},["message","name"]);let t=await ht.bind(this)("dopamine",e,{auth:!0}),n=t?.previous_message?.message,r=t?.previous_message?.name;n&&r&&window.alert(`${r} said ${n}`),window.location.href=t.video}const tr=JSON.parse('{"rE":"1.2.14-beta.3"}');var nr=function(e,t,n,r){var i,s=arguments.length,o=s<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,n,o):i(t,n))||o);return s>3&&o&&Object.defineProperty(t,n,o),o};class rr{get user(){return this.__user&&Object.keys(this.__user).length?JSON.parse(JSON.stringify(this.__user)):null}set user(e){}get onLogin(){return this._onLoginListeners}set onLogin(e){"function"==typeof e&&this._onLoginListeners.push(e)}get onUserUpdate(){return this._userProfileListeners}set onUserUpdate(e){"function"==typeof e&&this._userProfileListeners.push(e)}_runOnUserUpdateListeners(e){for(let t of this._userProfileListeners)"function"==typeof t&&t(e)}_runOnLoginListeners(e){for(let t of this._onLoginListeners)"function"==typeof t&&t(e)}get onBatchProcess(){return this._onBatchProcessListeners}set onBatchProcess(e){"function"==typeof e&&this._onBatchProcessListeners.push(e)}_alert(e){"undefined"!=typeof window&&"function"==typeof window.alert&&window.alert(e)}constructor(e,t,n,r){if(this.__version=tr.rE,this.session=null,this.connection=null,this.__my_unique_ids={},this.userPool=null,this.__socket=null,this.__mediaStream=null,this.host="skapi",this.hostDomain="skapi.com",this.target_cdn="d3e9syvbtso631",this.customApiDomain="skapi.dev",this.requestBatchSize=30,this.__disabledAccount=null,this.__cached_requests={},this.__startKeyHistory={},this.__request_signup_confirmation=null,this.__private_access_key={},this.__class_properties_has_been_cached=!1,this.__user=null,this._userProfileListeners=[],this._onLoginListeners=[],this._onBatchProcessListeners=[],this.validate={userId(e){try{return be.UserId(e),!0}catch(e){return!1}},url(e){try{return be.Url(e),!0}catch(e){return!1}},phoneNumber(e){try{return be.PhoneNumber(e),!0}catch(e){return!1}},birthdate(e){try{return be.Birthdate(e),!0}catch(e){return!1}},email(e){try{return be.Email(e),!0}catch(e){return!1}},params:(e,t,n)=>be.Params(e,t,n)},this.util={MD5:ie,generateRandom:ae,toBase62:se,fromBase62:oe,decodeServiceId:fe,formatServiceId:pe,extractFormData:he,terminatePendingRequests:lt,request:(e,t,n)=>ht.bind(this)(e,t,n,{ignoreService:!0})},this.__network_logs=!1,this.__endpoint_version="v1",this.__public_identifier="",this.bearerToken="",this.registerTicket=Te.bind(this),this.unregisterTicket=Re.bind(this),!e||"string"!=typeof e)throw this._alert("Service ID is required."),new te("Service ID is required.",{code:"INVALID_PARAMETER"});if(e.startsWith("s1_")||7===e.split("-").length)try{let i=fe(e);n&&"object"==typeof n&&(r=n),t&&"object"==typeof t&&(n=t),t=i.owner,e=i.service}catch(e){throw this._alert("Service ID is invalid."),new te("Service ID is invalid.",{code:"INVALID_PARAMETER"})}if(!t||"string"!=typeof t)throw this._alert("Owner ID is invalid."),new te("Owner ID is invalid.",{code:"INVALID_PARAMETER"});if("service_id"===e.toLowerCase())throw this._alert('Replace "service_id" with your actual Service ID.'),new te("Service ID is required.",{code:"INVALID_PARAMETER"});if(t!==this.host)try{be.UserId(t,'"owner"')}catch(e){throw this._alert("Owner ID is invalid."),new te("Owner ID is invalid.",{code:"INVALID_PARAMETER"})}this.service=e,this.owner=t;let i=!0;if(n&&("boolean"==typeof n.autoLogin&&(i=n.autoLogin),"number"==typeof n.requestBatchSize)){if(n.requestBatchSize<1)throw new te('"requestBatchSize" must be greater than 0.',{code:"INVALID_PARAMETER"});this.requestBatchSize=n.requestBatchSize}n?.eventListener&&"object"==typeof n.eventListener&&(n.eventListener?.onLogin&&"function"==typeof n.eventListener.onLogin&&(this.onLogin=n.eventListener.onLogin),n.eventListener?.onUserUpdate&&"function"==typeof n.eventListener.onUserUpdate&&(this.onUserUpdate=n.eventListener.onUserUpdate),n.eventListener?.onBatchProcess&&"function"==typeof n.eventListener.onBatchProcess&&(this.onBatchProcess=n.eventListener.onBatchProcess)),this.target_cdn=r?.target_cdn||this.target_cdn,this.hostDomain=r?.hostDomain||this.hostDomain,this.customApiDomain=r?.customApiDomain||this.customApiDomain,this.__network_logs=!!r?.network_logs;const s=`https://${this.target_cdn}.cloudfront.net`;let o=e.substring(0,4);this.admin_endpoint=fetch(`${s}/${o}/admin-${this.__endpoint_version}.json`).then(e=>e.blob()).then(e=>new Promise((t,n)=>{const r=new FileReader;r.onloadend=()=>t(r.result),r.onerror=n,r.readAsDataURL(e)})).then(e=>{try{return"string"==typeof e?JSON.parse(atob(e.split(",")[1])):null}catch(e){throw new te("Service does not exist. Create your service from skapi.com",{code:"NOT_EXISTS"})}}),this.record_endpoint=fetch(`${s}/${o}/record-${this.__endpoint_version}.json`).then(e=>e.blob()).then(e=>new Promise((t,n)=>{const r=new FileReader;r.onloadend=()=>t(r.result),r.onerror=n,r.readAsDataURL(e)})).then(e=>{try{return"string"==typeof e?JSON.parse(atob(e.split(",")[1])):null}catch(e){throw new te("Service does not exist. Create your service from skapi.com",{code:"NOT_EXISTS"})}});const a="undefined"!=typeof window;if(!a||!window.sessionStorage)throw this._alert("This browser is not supported."),new Error("This browser is not supported.");const c=a?JSON.parse(window.sessionStorage.getItem(`${e}#${t}`)||"null"):null;if(this.log("constructor:restore",c),c?.connection){for(let e in c)this[e]=c[e];c.__public_identifier||(this.__public_identifier=`${this.service}:${this.owner}:${ae(16)}`)}this.__authConnection=(async()=>{const e=await this.admin_endpoint,t={UserPoolId:e.userpool_id,ClientId:e.userpool_client};window._runningInNodeJS&&(t.Storage=window.localStorage),this.userPool=new ee(t);try{this.user||await Pe.bind(this)().getSession({skipUserUpdateEventTrigger:!0}),this.user&&(c?.connection||i?(this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user)):Me.bind(this)())}catch(e){}})();let u=a?window.sessionStorage.getItem(`${this.service}:uniqueids`):null;if(u)try{this.__my_unique_ids=JSON.parse(u)}catch(e){this.__my_unique_ids={}}this.__connection=(async()=>{let n=null;await this.record_endpoint,c?.connection||(n=this._updateConnection());const r=()=>{if(this.__class_properties_has_been_cached)return;let r=()=>{let n={};const r=["__startKeyHistory","__disabledAccount","__cached_requests","__request_signup_confirmation","__public_identifier","connection"];if(this.connection){for(let e of r)n[e]=this[e];a&&window.sessionStorage.setItem(`${e}#${t}`,JSON.stringify(n)),this.__class_properties_has_been_cached=!0}};return n instanceof Promise?n.then(()=>r()):r()};return a&&(window.addEventListener("beforeunload",()=>{this.closeRealtime(),r()}),window.addEventListener("visibilitychange",()=>{r()})),await n,await this.__authConnection,this.connection})(),this.__connection.then(e=>{((e?.group||0)<3||this.__network_logs)&&this.version()})}async getConnectionInfo(){let e=await this.__connection,t=e?.user_agent||("undefined"!=typeof window?window.navigator.userAgent:`skapi-node/${globalThis?.process?.versions?.node||"unknown"}`);return{user_ip:e.ip,user_agent:t,user_location:e.locale,service_name:e.service_name,version:this.__version}}async _updateConnection(){try{this.connection=await ht.bind(this)("service",{service:this.service,owner:this.owner},{bypassAwaitConnection:!0,method:"get"})}catch(e){throw this.log("connection fail",e),this._alert("Service is not available: "+(e.message||e.toString())),this.connection=null,e}return this.connection}async version(){return await this.__connection,console.log(`Built with:\n%c\r\n $$\\ $$\\ \r\n $$ | \\__|\r\n $$$$$$$\\ $$ | $$\\ $$$$$$\\ $$$$$$\\ $$\\ \r\n$$ _____|$$ | $$ |\\____$$\\ $$ __$$\\ $$ |\r\n\\$$$$$$\\ $$$$$$ / $$$$$$$ |$$ / $$ |$$ |\r\n \\____$$\\ $$ _$$< $$ __$$ |$$ | $$ |$$ |\r\n$$$$$$$ |$$ | \\$$\\\\$$$$$$$ |$$$$$$$ |$$ |\r\n\\_______/ \\__| \\__|\\_______|$$ ____/ \\__|\r\n $$ | \r\n $$ | \r\n \\__| \r\nVersion: ${this.__version}\n\nFull Documentation: https://docs.skapi.com/skapi.md`,"font-family: monospace; color:blue;"),1===this.connection.group&&console.log("%cSKAPI: THE SERVICE IS IN TRIAL MODE. ALL THE USERS AND DATA WILL BE INITIALIZED EVERY 30 DAYS.","font-family: monospace; color:red;"),this.__version}log(e,t){if(this.__network_logs){if("object"==typeof t)try{t=JSON.parse(JSON.stringify(t))}catch(e){t=String(t)}else"string"==typeof t&&t.length>100&&(t=t.substring(0,100)+"...");console.log(`%c${e}:`,"color: blue;",t)}}getFeed(e,t){return In.bind(this)(e,t)}closeRTC(e){return Zt.bind(this)(e)}connectRTC(e,t){return en.bind(this)(e,t)}connectRealtime(e){return fn.bind(this)(e)}spellcast(e){return Zn.bind(this)(e)}getspell(e){return Xn.bind(this)(e)}dopamine(e){return er.bind(this)(e)}getUniqueId(e,t){return Nt.bind(this)(e,t)}resendInvitation(e){return Wn.bind(this)(e)}cancelInvitation(e){return Hn.bind(this)(e)}getInvitations(e,t){return Jn.bind(this)(e,t)}openIdLogin(e){return Ne.bind(this)(e)}loginWithToken(e){return Le.bind(this)(e)}registerNewsletterGroup(e){return On.bind(this)(e)}clientSecretRequest(e){return An.bind(this)(e)}consumeTicket(e){return Se.bind(this)(e)}getConsumedTickets(e,t){return Ie.bind(this)(e,t)}getTickets(e,t){return Ee.bind(this)(e,t)}closeRealtime(){return dn.bind(this)()}getRealtimeUsers(e,t){return _n.bind(this)(e,t)}sendInquiry(e){return vn.bind(this)(e)}blockAccount(e){return Fn.bind(this)(e)}unblockAccount(e){return qn.bind(this)(e)}deleteAccount(e){return Bn.bind(this)(e)}inviteUser(e,t){return $n.bind(this)(e,t)}createAccount(e){return jn.bind(this)(e)}grantAccess(e){return Kn.bind(this)(e)}getRealtimeGroups(e,t){return mn.bind(this)(e,t)}newsletterGroupEndpoint(e){return Mn.bind(this)(e)}postRealtime(e,t,n){return pn.bind(this)(e,t,n)}joinRealtime(e){return gn.bind(this)(e)}getConnection(){return this.__connection}getProfile(e){return ke.bind(this)(e)}getFile(e,t){return Tt.bind(this)(e,t)}secureRequest(e,t){return Sn.bind(this)(e,t)}getFormResponse(){return yt.bind(this)()}getRecords(e,t){return Ut.bind(this)(e,t)}getTables(e,t){return Pt.bind(this)(e,t)}getIndexes(e,t){return Ct.bind(this)(e,t)}getTags(e,t){return kt.bind(this)(e,t)}deleteRecords(e,t){return Lt.bind(this)(e,t)}resendSignupConfirmation(){return xe.bind(this)()}recoverAccount(e=!1){return Fe.bind(this)(e)}getUsers(e,t){return Ge.bind(this)(e,t)}disableAccount(){return $e.bind(this)()}lastVerifiedEmail(e){return Ye.bind(this)(e)}unsubscribeNewsletter(e){return Vn.bind(this)(e)}adminNewsletterRequest(e){return Dn.bind(this)(e)}subscribeNotification(e,t){return Qn.bind(this)({endpoint:e,keys:t})}unsubscribeNotification(e,t){return zn.bind(this)({endpoint:e,keys:t})}vapidPublicKey(){return Gn.bind(this)()}pushNotification(e,t){return Yn.bind(this)(e,t)}getNewsletters(e,t){return xn.bind(this)(e,t)}getNewsletterSubscription(e,t){return Nn.bind(this)(e,t)}requestUsernameChange(e){return Ze.bind(this)(e)}grantPrivateRecordAccess(e){return Ot.bind(this)(e)}removePrivateRecordAccess(e){return Mt.bind(this)(e)}listPrivateRecordAccess(e){return Vt.bind(this)(e)}requestPrivateRecordAccessKey(e){return xt.bind(this)(e)}deleteFiles(e){return It.bind(this)(e)}uploadFiles(e,t){return gt.bind(this)(e,t)}mock(e,t){return En.bind(this)(e,t)}login(e){return qe.bind(this)(e)}logout(e){return Ve.bind(this)(e)}signup(e,t){return Be.bind(this)(e,t)}resetPassword(e){return je.bind(this)(e)}verifyEmail(e){return He.bind(this)(e)}verifyPhoneNumber(e){return Je.bind(this)(e)}forgotPassword(e){return We.bind(this)(e)}changePassword(e){return Qe.bind(this)(e)}updateProfile(e){return ze.bind(this)(e)}postRecord(e,t,n){return Dt.bind(this)(e,t,n)}getSubscriptions(e,t){return Rn.bind(this)(e,t)}subscribe(e){return Un.bind(this)(e)}unsubscribe(e){return Pn.bind(this)(e)}blockSubscriber(e){return Cn.bind(this)(e)}unblockSubscriber(e){return kn.bind(this)(e)}subscribeNewsletter(e){return Ln.bind(this)(e)}}nr([mt()],rr.prototype,"getFeed",null),nr([mt()],rr.prototype,"closeRTC",null),nr([mt()],rr.prototype,"connectRTC",null),nr([mt()],rr.prototype,"spellcast",null),nr([mt()],rr.prototype,"getspell",null),nr([mt()],rr.prototype,"dopamine",null),nr([mt()],rr.prototype,"getUniqueId",null),nr([mt()],rr.prototype,"resendInvitation",null),nr([mt()],rr.prototype,"cancelInvitation",null),nr([mt()],rr.prototype,"getInvitations",null),nr([mt()],rr.prototype,"openIdLogin",null),nr([mt()],rr.prototype,"loginWithToken",null),nr([mt()],rr.prototype,"registerNewsletterGroup",null),nr([mt()],rr.prototype,"clientSecretRequest",null),nr([mt()],rr.prototype,"consumeTicket",null),nr([mt()],rr.prototype,"getConsumedTickets",null),nr([mt()],rr.prototype,"getTickets",null),nr([mt()],rr.prototype,"getRealtimeUsers",null),nr([mt()],rr.prototype,"sendInquiry",null),nr([mt()],rr.prototype,"blockAccount",null),nr([mt()],rr.prototype,"unblockAccount",null),nr([mt()],rr.prototype,"deleteAccount",null),nr([mt()],rr.prototype,"inviteUser",null),nr([mt()],rr.prototype,"createAccount",null),nr([mt()],rr.prototype,"grantAccess",null),nr([mt()],rr.prototype,"getRealtimeGroups",null),nr([mt()],rr.prototype,"newsletterGroupEndpoint",null),nr([mt()],rr.prototype,"postRealtime",null),nr([mt()],rr.prototype,"joinRealtime",null),nr([mt()],rr.prototype,"getProfile",null),nr([mt()],rr.prototype,"getFile",null),nr([mt()],rr.prototype,"secureRequest",null),nr([mt()],rr.prototype,"getFormResponse",null),nr([mt()],rr.prototype,"getRecords",null),nr([mt()],rr.prototype,"getTables",null),nr([mt()],rr.prototype,"getIndexes",null),nr([mt()],rr.prototype,"getTags",null),nr([mt()],rr.prototype,"deleteRecords",null),nr([mt()],rr.prototype,"resendSignupConfirmation",null),nr([mt()],rr.prototype,"recoverAccount",null),nr([mt()],rr.prototype,"getUsers",null),nr([mt()],rr.prototype,"disableAccount",null),nr([mt()],rr.prototype,"lastVerifiedEmail",null),nr([mt()],rr.prototype,"unsubscribeNewsletter",null),nr([mt()],rr.prototype,"adminNewsletterRequest",null),nr([mt()],rr.prototype,"subscribeNotification",null),nr([mt()],rr.prototype,"unsubscribeNotification",null),nr([mt()],rr.prototype,"vapidPublicKey",null),nr([mt()],rr.prototype,"pushNotification",null),nr([mt()],rr.prototype,"getNewsletters",null),nr([mt()],rr.prototype,"getNewsletterSubscription",null),nr([mt()],rr.prototype,"requestUsernameChange",null),nr([mt()],rr.prototype,"grantPrivateRecordAccess",null),nr([mt()],rr.prototype,"removePrivateRecordAccess",null),nr([mt()],rr.prototype,"listPrivateRecordAccess",null),nr([mt()],rr.prototype,"requestPrivateRecordAccessKey",null),nr([mt()],rr.prototype,"deleteFiles",null),nr([mt()],rr.prototype,"uploadFiles",null),nr([mt()],rr.prototype,"mock",null),nr([mt({preventMultipleCalls:!0})],rr.prototype,"login",null),nr([mt()],rr.prototype,"logout",null),nr([mt({preventMultipleCalls:!0})],rr.prototype,"signup",null),nr([mt({preventMultipleCalls:!0})],rr.prototype,"resetPassword",null),nr([mt({preventMultipleCalls:!0})],rr.prototype,"verifyEmail",null),nr([mt({preventMultipleCalls:!0})],rr.prototype,"verifyPhoneNumber",null),nr([mt({preventMultipleCalls:!0})],rr.prototype,"forgotPassword",null),nr([mt({preventMultipleCalls:!0})],rr.prototype,"changePassword",null),nr([mt({preventMultipleCalls:!0})],rr.prototype,"updateProfile",null),nr([mt()],rr.prototype,"postRecord",null),nr([mt()],rr.prototype,"getSubscriptions",null),nr([mt()],rr.prototype,"subscribe",null),nr([mt()],rr.prototype,"unsubscribe",null),nr([mt()],rr.prototype,"blockSubscriber",null),nr([mt()],rr.prototype,"unblockSubscriber",null),nr([mt()],rr.prototype,"subscribeNewsletter",null)})(),r})());
2
+ !function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var n=t();for(var r in n)("object"==typeof exports?exports:e)[r]=n[r]}}(self,()=>(()=>{var e={602(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RawSha256=void 0;var r=n(494),i=function(){function e(){this.state=Int32Array.from(r.INIT),this.temp=new Int32Array(64),this.buffer=new Uint8Array(64),this.bufferLength=0,this.bytesHashed=0,this.finished=!1}return e.prototype.update=function(e){if(this.finished)throw new Error("Attempted to update an already finished hash.");var t=0,n=e.byteLength;if(this.bytesHashed+=n,8*this.bytesHashed>r.MAX_HASHABLE_LENGTH)throw new Error("Cannot hash more than 2^53 - 1 bits");for(;n>0;)this.buffer[this.bufferLength++]=e[t++],n--,this.bufferLength===r.BLOCK_SIZE&&(this.hashBuffer(),this.bufferLength=0)},e.prototype.digest=function(){if(!this.finished){var e=8*this.bytesHashed,t=new DataView(this.buffer.buffer,this.buffer.byteOffset,this.buffer.byteLength),n=this.bufferLength;if(t.setUint8(this.bufferLength++,128),n%r.BLOCK_SIZE>=r.BLOCK_SIZE-8){for(var i=this.bufferLength;i<r.BLOCK_SIZE;i++)t.setUint8(i,0);this.hashBuffer(),this.bufferLength=0}for(i=this.bufferLength;i<r.BLOCK_SIZE-8;i++)t.setUint8(i,0);t.setUint32(r.BLOCK_SIZE-8,Math.floor(e/4294967296),!0),t.setUint32(r.BLOCK_SIZE-4,e),this.hashBuffer(),this.finished=!0}var s=new Uint8Array(r.DIGEST_LENGTH);for(i=0;i<8;i++)s[4*i]=this.state[i]>>>24&255,s[4*i+1]=this.state[i]>>>16&255,s[4*i+2]=this.state[i]>>>8&255,s[4*i+3]=this.state[i]>>>0&255;return s},e.prototype.hashBuffer=function(){for(var e=this.buffer,t=this.state,n=t[0],i=t[1],s=t[2],o=t[3],a=t[4],c=t[5],u=t[6],l=t[7],h=0;h<r.BLOCK_SIZE;h++){if(h<16)this.temp[h]=(255&e[4*h])<<24|(255&e[4*h+1])<<16|(255&e[4*h+2])<<8|255&e[4*h+3];else{var d=this.temp[h-2],f=(d>>>17|d<<15)^(d>>>19|d<<13)^d>>>10,p=((d=this.temp[h-15])>>>7|d<<25)^(d>>>18|d<<14)^d>>>3;this.temp[h]=(f+this.temp[h-7]|0)+(p+this.temp[h-16]|0)}var g=(((a>>>6|a<<26)^(a>>>11|a<<21)^(a>>>25|a<<7))+(a&c^~a&u)|0)+(l+(r.KEY[h]+this.temp[h]|0)|0)|0,_=((n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10))+(n&i^n&s^i&s)|0;l=u,u=c,c=a,a=o+g|0,o=s,s=i,i=n,n=g+_|0}t[0]+=n,t[1]+=i,t[2]+=s,t[3]+=o,t[4]+=a,t[5]+=c,t[6]+=u,t[7]+=l},e}();t.RawSha256=i},494(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MAX_HASHABLE_LENGTH=t.INIT=t.KEY=t.DIGEST_LENGTH=t.BLOCK_SIZE=void 0,t.BLOCK_SIZE=64,t.DIGEST_LENGTH=32,t.KEY=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),t.INIT=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],t.MAX_HASHABLE_LENGTH=Math.pow(2,53)-1},523(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),(0,n(215).__exportStar)(n(871),t)},871(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Sha256=void 0;var r=n(215),i=n(494),s=n(602),o=n(388),a=function(){function e(e){if(this.hash=new s.RawSha256,e){this.outer=new s.RawSha256;var t=function(e){var t=(0,o.convertToBuffer)(e);if(t.byteLength>i.BLOCK_SIZE){var n=new s.RawSha256;n.update(t),t=n.digest()}var r=new Uint8Array(i.BLOCK_SIZE);return r.set(t),r}(e),n=new Uint8Array(i.BLOCK_SIZE);n.set(t);for(var r=0;r<i.BLOCK_SIZE;r++)t[r]^=54,n[r]^=92;for(this.hash.update(t),this.outer.update(n),r=0;r<t.byteLength;r++)t[r]=0}}return e.prototype.update=function(e){if(!(0,o.isEmptyData)(e)&&!this.error)try{this.hash.update((0,o.convertToBuffer)(e))}catch(e){this.error=e}},e.prototype.digestSync=function(){if(this.error)throw this.error;return this.outer?(this.outer.finished||this.outer.update(this.hash.digest()),this.outer.digest()):this.hash.digest()},e.prototype.digest=function(){return(0,r.__awaiter)(this,void 0,void 0,function(){return(0,r.__generator)(this,function(e){return[2,this.digestSync()]})})},e}();t.Sha256=a},24(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.convertToBuffer=void 0;var r=n(6),i="undefined"!=typeof Buffer&&Buffer.from?function(e){return Buffer.from(e,"utf8")}:r.fromUtf8;t.convertToBuffer=function(e){return e instanceof Uint8Array?e:"string"==typeof e?i(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(e)}},388(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uint32ArrayFrom=t.numToUint8=t.isEmptyData=t.convertToBuffer=void 0;var r=n(24);Object.defineProperty(t,"convertToBuffer",{enumerable:!0,get:function(){return r.convertToBuffer}});var i=n(165);Object.defineProperty(t,"isEmptyData",{enumerable:!0,get:function(){return i.isEmptyData}});var s=n(413);Object.defineProperty(t,"numToUint8",{enumerable:!0,get:function(){return s.numToUint8}});var o=n(110);Object.defineProperty(t,"uint32ArrayFrom",{enumerable:!0,get:function(){return o.uint32ArrayFrom}})},165(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isEmptyData=void 0,t.isEmptyData=function(e){return"string"==typeof e?0===e.length:0===e.byteLength}},413(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.numToUint8=void 0,t.numToUint8=function(e){return new Uint8Array([(4278190080&e)>>24,(16711680&e)>>16,(65280&e)>>8,255&e])}},110(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uint32ArrayFrom=void 0,t.uint32ArrayFrom=function(e){if(!Array.from){for(var t=new Uint32Array(e.length);0<e.length;)t[0]=e[0];return t}return Uint32Array.from(e)}},6(e,t,n){"use strict";n.r(t),n.d(t,{fromUtf8:()=>r,toUtf8:()=>i});const r=e=>"function"==typeof TextEncoder?function(e){return(new TextEncoder).encode(e)}(e):(e=>{const t=[];for(let n=0,r=e.length;n<r;n++){const r=e.charCodeAt(n);if(r<128)t.push(r);else if(r<2048)t.push(r>>6|192,63&r|128);else if(n+1<e.length&&55296==(64512&r)&&56320==(64512&e.charCodeAt(n+1))){const i=65536+((1023&r)<<10)+(1023&e.charCodeAt(++n));t.push(i>>18|240,i>>12&63|128,i>>6&63|128,63&i|128)}else t.push(r>>12|224,r>>6&63|128,63&r|128)}return Uint8Array.from(t)})(e),i=e=>"function"==typeof TextDecoder?function(e){return new TextDecoder("utf-8").decode(e)}(e):(e=>{let t="";for(let n=0,r=e.length;n<r;n++){const r=e[n];if(r<128)t+=String.fromCharCode(r);else if(192<=r&&r<224){const i=e[++n];t+=String.fromCharCode((31&r)<<6|63&i)}else if(240<=r&&r<365){const i="%"+[r,e[++n],e[++n],e[++n]].map(e=>e.toString(16)).join("%");t+=decodeURIComponent(i)}else t+=String.fromCharCode((15&r)<<12|(63&e[++n])<<6|63&e[++n])}return t})(e)},526(e,t){"use strict";t.byteLength=function(e){var t=a(e),n=t[0],r=t[1];return 3*(n+r)/4-r},t.toByteArray=function(e){var t,n,s=a(e),o=s[0],c=s[1],u=new i(function(e,t,n){return 3*(t+n)/4-n}(0,o,c)),l=0,h=c>0?o-4:o;for(n=0;n<h;n+=4)t=r[e.charCodeAt(n)]<<18|r[e.charCodeAt(n+1)]<<12|r[e.charCodeAt(n+2)]<<6|r[e.charCodeAt(n+3)],u[l++]=t>>16&255,u[l++]=t>>8&255,u[l++]=255&t;return 2===c&&(t=r[e.charCodeAt(n)]<<2|r[e.charCodeAt(n+1)]>>4,u[l++]=255&t),1===c&&(t=r[e.charCodeAt(n)]<<10|r[e.charCodeAt(n+1)]<<4|r[e.charCodeAt(n+2)]>>2,u[l++]=t>>8&255,u[l++]=255&t),u},t.fromByteArray=function(e){for(var t,r=e.length,i=r%3,s=[],o=16383,a=0,c=r-i;a<c;a+=o)s.push(u(e,a,a+o>c?c:a+o));return 1===i?(t=e[r-1],s.push(n[t>>2]+n[t<<4&63]+"==")):2===i&&(t=(e[r-2]<<8)+e[r-1],s.push(n[t>>10]+n[t>>4&63]+n[t<<2&63]+"=")),s.join("")};for(var n=[],r=[],i="undefined"!=typeof Uint8Array?Uint8Array:Array,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",o=0;o<64;++o)n[o]=s[o],r[s.charCodeAt(o)]=o;function a(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var n=e.indexOf("=");return-1===n&&(n=t),[n,n===t?0:4-n%4]}function c(e){return n[e>>18&63]+n[e>>12&63]+n[e>>6&63]+n[63&e]}function u(e,t,n){for(var r,i=[],s=t;s<n;s+=3)r=(e[s]<<16&16711680)+(e[s+1]<<8&65280)+(255&e[s+2]),i.push(c(r));return i.join("")}r["-".charCodeAt(0)]=62,r["_".charCodeAt(0)]=63},287(e,t,n){"use strict";var r=n(526),i=n(251),s=n(634);function o(){return c.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function a(e,t){if(o()<t)throw new RangeError("Invalid typed array length");return c.TYPED_ARRAY_SUPPORT?(e=new Uint8Array(t)).__proto__=c.prototype:(null===e&&(e=new c(t)),e.length=t),e}function c(e,t,n){if(!(c.TYPED_ARRAY_SUPPORT||this instanceof c))return new c(e,t,n);if("number"==typeof e){if("string"==typeof t)throw new Error("If encoding is specified then the first argument must be a string");return h(this,e)}return u(this,e,t,n)}function u(e,t,n,r){if("number"==typeof t)throw new TypeError('"value" argument must not be a number');return"undefined"!=typeof ArrayBuffer&&t instanceof ArrayBuffer?function(e,t,n,r){if(t.byteLength,n<0||t.byteLength<n)throw new RangeError("'offset' is out of bounds");if(t.byteLength<n+(r||0))throw new RangeError("'length' is out of bounds");return t=void 0===n&&void 0===r?new Uint8Array(t):void 0===r?new Uint8Array(t,n):new Uint8Array(t,n,r),c.TYPED_ARRAY_SUPPORT?(e=t).__proto__=c.prototype:e=d(e,t),e}(e,t,n,r):"string"==typeof t?function(e,t,n){if("string"==typeof n&&""!==n||(n="utf8"),!c.isEncoding(n))throw new TypeError('"encoding" must be a valid string encoding');var r=0|p(t,n),i=(e=a(e,r)).write(t,n);return i!==r&&(e=e.slice(0,i)),e}(e,t,n):function(e,t){if(c.isBuffer(t)){var n=0|f(t.length);return 0===(e=a(e,n)).length||t.copy(e,0,0,n),e}if(t){if("undefined"!=typeof ArrayBuffer&&t.buffer instanceof ArrayBuffer||"length"in t)return"number"!=typeof t.length||(r=t.length)!=r?a(e,0):d(e,t);if("Buffer"===t.type&&s(t.data))return d(e,t.data)}var r;throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")}(e,t)}function l(e){if("number"!=typeof e)throw new TypeError('"size" argument must be a number');if(e<0)throw new RangeError('"size" argument must not be negative')}function h(e,t){if(l(t),e=a(e,t<0?0:0|f(t)),!c.TYPED_ARRAY_SUPPORT)for(var n=0;n<t;++n)e[n]=0;return e}function d(e,t){var n=t.length<0?0:0|f(t.length);e=a(e,n);for(var r=0;r<n;r+=1)e[r]=255&t[r];return e}function f(e){if(e>=o())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+o().toString(16)+" bytes");return 0|e}function p(e,t){if(c.isBuffer(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!=typeof e&&(e=""+e);var n=e.length;if(0===n)return 0;for(var r=!1;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":case void 0:return $(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return j(e).length;default:if(r)return $(e).length;t=(""+t).toLowerCase(),r=!0}}function g(e,t,n){var r=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if((n>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return P(this,t,n);case"utf8":case"utf-8":return T(this,t,n);case"ascii":return D(this,t,n);case"latin1":case"binary":return U(this,t,n);case"base64":return I(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return C(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function _(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function m(e,t,n,r,i){if(0===e.length)return-1;if("string"==typeof n?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),n=+n,isNaN(n)&&(n=i?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(i)return-1;n=e.length-1}else if(n<0){if(!i)return-1;n=0}if("string"==typeof t&&(t=c.from(t,r)),c.isBuffer(t))return 0===t.length?-1:y(e,t,n,r,i);if("number"==typeof t)return t&=255,c.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):y(e,[t],n,r,i);throw new TypeError("val must be string, number or Buffer")}function y(e,t,n,r,i){var s,o=1,a=e.length,c=t.length;if(void 0!==r&&("ucs2"===(r=String(r).toLowerCase())||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(e.length<2||t.length<2)return-1;o=2,a/=2,c/=2,n/=2}function u(e,t){return 1===o?e[t]:e.readUInt16BE(t*o)}if(i){var l=-1;for(s=n;s<a;s++)if(u(e,s)===u(t,-1===l?0:s-l)){if(-1===l&&(l=s),s-l+1===c)return l*o}else-1!==l&&(s-=s-l),l=-1}else for(n+c>a&&(n=a-c),s=n;s>=0;s--){for(var h=!0,d=0;d<c;d++)if(u(e,s+d)!==u(t,d)){h=!1;break}if(h)return s}return-1}function w(e,t,n,r){n=Number(n)||0;var i=e.length-n;r?(r=Number(r))>i&&(r=i):r=i;var s=t.length;if(s%2!=0)throw new TypeError("Invalid hex string");r>s/2&&(r=s/2);for(var o=0;o<r;++o){var a=parseInt(t.substr(2*o,2),16);if(isNaN(a))return o;e[n+o]=a}return o}function b(e,t,n,r){return B($(t,e.length-n),e,n,r)}function A(e,t,n,r){return B(function(e){for(var t=[],n=0;n<e.length;++n)t.push(255&e.charCodeAt(n));return t}(t),e,n,r)}function v(e,t,n,r){return A(e,t,n,r)}function E(e,t,n,r){return B(j(t),e,n,r)}function S(e,t,n,r){return B(function(e,t){for(var n,r,i,s=[],o=0;o<e.length&&!((t-=2)<0);++o)r=(n=e.charCodeAt(o))>>8,i=n%256,s.push(i),s.push(r);return s}(t,e.length-n),e,n,r)}function I(e,t,n){return 0===t&&n===e.length?r.fromByteArray(e):r.fromByteArray(e.slice(t,n))}function T(e,t,n){n=Math.min(e.length,n);for(var r=[],i=t;i<n;){var s,o,a,c,u=e[i],l=null,h=u>239?4:u>223?3:u>191?2:1;if(i+h<=n)switch(h){case 1:u<128&&(l=u);break;case 2:128==(192&(s=e[i+1]))&&(c=(31&u)<<6|63&s)>127&&(l=c);break;case 3:s=e[i+1],o=e[i+2],128==(192&s)&&128==(192&o)&&(c=(15&u)<<12|(63&s)<<6|63&o)>2047&&(c<55296||c>57343)&&(l=c);break;case 4:s=e[i+1],o=e[i+2],a=e[i+3],128==(192&s)&&128==(192&o)&&128==(192&a)&&(c=(15&u)<<18|(63&s)<<12|(63&o)<<6|63&a)>65535&&c<1114112&&(l=c)}null===l?(l=65533,h=1):l>65535&&(l-=65536,r.push(l>>>10&1023|55296),l=56320|1023&l),r.push(l),i+=h}return function(e){var t=e.length;if(t<=R)return String.fromCharCode.apply(String,e);for(var n="",r=0;r<t;)n+=String.fromCharCode.apply(String,e.slice(r,r+=R));return n}(r)}t.hp=c,t.IS=50,c.TYPED_ARRAY_SUPPORT=void 0!==n.g.TYPED_ARRAY_SUPPORT?n.g.TYPED_ARRAY_SUPPORT:function(){try{var e=new Uint8Array(1);return e.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===e.foo()&&"function"==typeof e.subarray&&0===e.subarray(1,1).byteLength}catch(e){return!1}}(),o(),c.poolSize=8192,c._augment=function(e){return e.__proto__=c.prototype,e},c.from=function(e,t,n){return u(null,e,t,n)},c.TYPED_ARRAY_SUPPORT&&(c.prototype.__proto__=Uint8Array.prototype,c.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&c[Symbol.species]===c&&Object.defineProperty(c,Symbol.species,{value:null,configurable:!0})),c.alloc=function(e,t,n){return function(e,t,n,r){return l(t),t<=0?a(e,t):void 0!==n?"string"==typeof r?a(e,t).fill(n,r):a(e,t).fill(n):a(e,t)}(null,e,t,n)},c.allocUnsafe=function(e){return h(null,e)},c.allocUnsafeSlow=function(e){return h(null,e)},c.isBuffer=function(e){return!(null==e||!e._isBuffer)},c.compare=function(e,t){if(!c.isBuffer(e)||!c.isBuffer(t))throw new TypeError("Arguments must be Buffers");if(e===t)return 0;for(var n=e.length,r=t.length,i=0,s=Math.min(n,r);i<s;++i)if(e[i]!==t[i]){n=e[i],r=t[i];break}return n<r?-1:r<n?1:0},c.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},c.concat=function(e,t){if(!s(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return c.alloc(0);var n;if(void 0===t)for(t=0,n=0;n<e.length;++n)t+=e[n].length;var r=c.allocUnsafe(t),i=0;for(n=0;n<e.length;++n){var o=e[n];if(!c.isBuffer(o))throw new TypeError('"list" argument must be an Array of Buffers');o.copy(r,i),i+=o.length}return r},c.byteLength=p,c.prototype._isBuffer=!0,c.prototype.swap16=function(){var e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var t=0;t<e;t+=2)_(this,t,t+1);return this},c.prototype.swap32=function(){var e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var t=0;t<e;t+=4)_(this,t,t+3),_(this,t+1,t+2);return this},c.prototype.swap64=function(){var e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var t=0;t<e;t+=8)_(this,t,t+7),_(this,t+1,t+6),_(this,t+2,t+5),_(this,t+3,t+4);return this},c.prototype.toString=function(){var e=0|this.length;return 0===e?"":0===arguments.length?T(this,0,e):g.apply(this,arguments)},c.prototype.equals=function(e){if(!c.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===c.compare(this,e)},c.prototype.inspect=function(){var e="",n=t.IS;return this.length>0&&(e=this.toString("hex",0,n).match(/.{2}/g).join(" "),this.length>n&&(e+=" ... ")),"<Buffer "+e+">"},c.prototype.compare=function(e,t,n,r,i){if(!c.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===r&&(r=0),void 0===i&&(i=this.length),t<0||n>e.length||r<0||i>this.length)throw new RangeError("out of range index");if(r>=i&&t>=n)return 0;if(r>=i)return-1;if(t>=n)return 1;if(this===e)return 0;for(var s=(i>>>=0)-(r>>>=0),o=(n>>>=0)-(t>>>=0),a=Math.min(s,o),u=this.slice(r,i),l=e.slice(t,n),h=0;h<a;++h)if(u[h]!==l[h]){s=u[h],o=l[h];break}return s<o?-1:o<s?1:0},c.prototype.includes=function(e,t,n){return-1!==this.indexOf(e,t,n)},c.prototype.indexOf=function(e,t,n){return m(this,e,t,n,!0)},c.prototype.lastIndexOf=function(e,t,n){return m(this,e,t,n,!1)},c.prototype.write=function(e,t,n,r){if(void 0===t)r="utf8",n=this.length,t=0;else if(void 0===n&&"string"==typeof t)r=t,n=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t|=0,isFinite(n)?(n|=0,void 0===r&&(r="utf8")):(r=n,n=void 0)}var i=this.length-t;if((void 0===n||n>i)&&(n=i),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");for(var s=!1;;)switch(r){case"hex":return w(this,e,t,n);case"utf8":case"utf-8":return b(this,e,t,n);case"ascii":return A(this,e,t,n);case"latin1":case"binary":return v(this,e,t,n);case"base64":return E(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return S(this,e,t,n);default:if(s)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),s=!0}},c.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var R=4096;function D(e,t,n){var r="";n=Math.min(e.length,n);for(var i=t;i<n;++i)r+=String.fromCharCode(127&e[i]);return r}function U(e,t,n){var r="";n=Math.min(e.length,n);for(var i=t;i<n;++i)r+=String.fromCharCode(e[i]);return r}function P(e,t,n){var r=e.length;(!t||t<0)&&(t=0),(!n||n<0||n>r)&&(n=r);for(var i="",s=t;s<n;++s)i+=q(e[s]);return i}function C(e,t,n){for(var r=e.slice(t,n),i="",s=0;s<r.length;s+=2)i+=String.fromCharCode(r[s]+256*r[s+1]);return i}function k(e,t,n){if(e%1!=0||e<0)throw new RangeError("offset is not uint");if(e+t>n)throw new RangeError("Trying to access beyond buffer length")}function N(e,t,n,r,i,s){if(!c.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||t<s)throw new RangeError('"value" argument is out of bounds');if(n+r>e.length)throw new RangeError("Index out of range")}function L(e,t,n,r){t<0&&(t=65535+t+1);for(var i=0,s=Math.min(e.length-n,2);i<s;++i)e[n+i]=(t&255<<8*(r?i:1-i))>>>8*(r?i:1-i)}function O(e,t,n,r){t<0&&(t=4294967295+t+1);for(var i=0,s=Math.min(e.length-n,4);i<s;++i)e[n+i]=t>>>8*(r?i:3-i)&255}function M(e,t,n,r,i,s){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function V(e,t,n,r,s){return s||M(e,0,n,4),i.write(e,t,n,r,23,4),n+4}function x(e,t,n,r,s){return s||M(e,0,n,8),i.write(e,t,n,r,52,8),n+8}c.prototype.slice=function(e,t){var n,r=this.length;if((e=~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),(t=void 0===t?r:~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),t<e&&(t=e),c.TYPED_ARRAY_SUPPORT)(n=this.subarray(e,t)).__proto__=c.prototype;else{var i=t-e;n=new c(i,void 0);for(var s=0;s<i;++s)n[s]=this[s+e]}return n},c.prototype.readUIntLE=function(e,t,n){e|=0,t|=0,n||k(e,t,this.length);for(var r=this[e],i=1,s=0;++s<t&&(i*=256);)r+=this[e+s]*i;return r},c.prototype.readUIntBE=function(e,t,n){e|=0,t|=0,n||k(e,t,this.length);for(var r=this[e+--t],i=1;t>0&&(i*=256);)r+=this[e+--t]*i;return r},c.prototype.readUInt8=function(e,t){return t||k(e,1,this.length),this[e]},c.prototype.readUInt16LE=function(e,t){return t||k(e,2,this.length),this[e]|this[e+1]<<8},c.prototype.readUInt16BE=function(e,t){return t||k(e,2,this.length),this[e]<<8|this[e+1]},c.prototype.readUInt32LE=function(e,t){return t||k(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},c.prototype.readUInt32BE=function(e,t){return t||k(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},c.prototype.readIntLE=function(e,t,n){e|=0,t|=0,n||k(e,t,this.length);for(var r=this[e],i=1,s=0;++s<t&&(i*=256);)r+=this[e+s]*i;return r>=(i*=128)&&(r-=Math.pow(2,8*t)),r},c.prototype.readIntBE=function(e,t,n){e|=0,t|=0,n||k(e,t,this.length);for(var r=t,i=1,s=this[e+--r];r>0&&(i*=256);)s+=this[e+--r]*i;return s>=(i*=128)&&(s-=Math.pow(2,8*t)),s},c.prototype.readInt8=function(e,t){return t||k(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},c.prototype.readInt16LE=function(e,t){t||k(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},c.prototype.readInt16BE=function(e,t){t||k(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},c.prototype.readInt32LE=function(e,t){return t||k(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},c.prototype.readInt32BE=function(e,t){return t||k(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},c.prototype.readFloatLE=function(e,t){return t||k(e,4,this.length),i.read(this,e,!0,23,4)},c.prototype.readFloatBE=function(e,t){return t||k(e,4,this.length),i.read(this,e,!1,23,4)},c.prototype.readDoubleLE=function(e,t){return t||k(e,8,this.length),i.read(this,e,!0,52,8)},c.prototype.readDoubleBE=function(e,t){return t||k(e,8,this.length),i.read(this,e,!1,52,8)},c.prototype.writeUIntLE=function(e,t,n,r){e=+e,t|=0,n|=0,r||N(this,e,t,n,Math.pow(2,8*n)-1,0);var i=1,s=0;for(this[t]=255&e;++s<n&&(i*=256);)this[t+s]=e/i&255;return t+n},c.prototype.writeUIntBE=function(e,t,n,r){e=+e,t|=0,n|=0,r||N(this,e,t,n,Math.pow(2,8*n)-1,0);var i=n-1,s=1;for(this[t+i]=255&e;--i>=0&&(s*=256);)this[t+i]=e/s&255;return t+n},c.prototype.writeUInt8=function(e,t,n){return e=+e,t|=0,n||N(this,e,t,1,255,0),c.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},c.prototype.writeUInt16LE=function(e,t,n){return e=+e,t|=0,n||N(this,e,t,2,65535,0),c.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):L(this,e,t,!0),t+2},c.prototype.writeUInt16BE=function(e,t,n){return e=+e,t|=0,n||N(this,e,t,2,65535,0),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):L(this,e,t,!1),t+2},c.prototype.writeUInt32LE=function(e,t,n){return e=+e,t|=0,n||N(this,e,t,4,4294967295,0),c.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):O(this,e,t,!0),t+4},c.prototype.writeUInt32BE=function(e,t,n){return e=+e,t|=0,n||N(this,e,t,4,4294967295,0),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):O(this,e,t,!1),t+4},c.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t|=0,!r){var i=Math.pow(2,8*n-1);N(this,e,t,n,i-1,-i)}var s=0,o=1,a=0;for(this[t]=255&e;++s<n&&(o*=256);)e<0&&0===a&&0!==this[t+s-1]&&(a=1),this[t+s]=(e/o|0)-a&255;return t+n},c.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t|=0,!r){var i=Math.pow(2,8*n-1);N(this,e,t,n,i-1,-i)}var s=n-1,o=1,a=0;for(this[t+s]=255&e;--s>=0&&(o*=256);)e<0&&0===a&&0!==this[t+s+1]&&(a=1),this[t+s]=(e/o|0)-a&255;return t+n},c.prototype.writeInt8=function(e,t,n){return e=+e,t|=0,n||N(this,e,t,1,127,-128),c.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},c.prototype.writeInt16LE=function(e,t,n){return e=+e,t|=0,n||N(this,e,t,2,32767,-32768),c.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):L(this,e,t,!0),t+2},c.prototype.writeInt16BE=function(e,t,n){return e=+e,t|=0,n||N(this,e,t,2,32767,-32768),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):L(this,e,t,!1),t+2},c.prototype.writeInt32LE=function(e,t,n){return e=+e,t|=0,n||N(this,e,t,4,2147483647,-2147483648),c.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):O(this,e,t,!0),t+4},c.prototype.writeInt32BE=function(e,t,n){return e=+e,t|=0,n||N(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):O(this,e,t,!1),t+4},c.prototype.writeFloatLE=function(e,t,n){return V(this,e,t,!0,n)},c.prototype.writeFloatBE=function(e,t,n){return V(this,e,t,!1,n)},c.prototype.writeDoubleLE=function(e,t,n){return x(this,e,t,!0,n)},c.prototype.writeDoubleBE=function(e,t,n){return x(this,e,t,!1,n)},c.prototype.copy=function(e,t,n,r){if(n||(n=0),r||0===r||(r=this.length),t>=e.length&&(t=e.length),t||(t=0),r>0&&r<n&&(r=n),r===n)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(n<0||n>=this.length)throw new RangeError("sourceStart out of bounds");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-t<r-n&&(r=e.length-t+n);var i,s=r-n;if(this===e&&n<t&&t<r)for(i=s-1;i>=0;--i)e[i+t]=this[i+n];else if(s<1e3||!c.TYPED_ARRAY_SUPPORT)for(i=0;i<s;++i)e[i+t]=this[i+n];else Uint8Array.prototype.set.call(e,this.subarray(n,n+s),t);return s},c.prototype.fill=function(e,t,n,r){if("string"==typeof e){if("string"==typeof t?(r=t,t=0,n=this.length):"string"==typeof n&&(r=n,n=this.length),1===e.length){var i=e.charCodeAt(0);i<256&&(e=i)}if(void 0!==r&&"string"!=typeof r)throw new TypeError("encoding must be a string");if("string"==typeof r&&!c.isEncoding(r))throw new TypeError("Unknown encoding: "+r)}else"number"==typeof e&&(e&=255);if(t<0||this.length<t||this.length<n)throw new RangeError("Out of range index");if(n<=t)return this;var s;if(t>>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(s=t;s<n;++s)this[s]=e;else{var o=c.isBuffer(e)?e:$(new c(e,r).toString()),a=o.length;for(s=0;s<n-t;++s)this[s+t]=o[s%a]}return this};var F=/[^+\/0-9A-Za-z-_]/g;function q(e){return e<16?"0"+e.toString(16):e.toString(16)}function $(e,t){var n;t=t||1/0;for(var r=e.length,i=null,s=[],o=0;o<r;++o){if((n=e.charCodeAt(o))>55295&&n<57344){if(!i){if(n>56319){(t-=3)>-1&&s.push(239,191,189);continue}if(o+1===r){(t-=3)>-1&&s.push(239,191,189);continue}i=n;continue}if(n<56320){(t-=3)>-1&&s.push(239,191,189),i=n;continue}n=65536+(i-55296<<10|n-56320)}else i&&(t-=3)>-1&&s.push(239,191,189);if(i=null,n<128){if((t-=1)<0)break;s.push(n)}else if(n<2048){if((t-=2)<0)break;s.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;s.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;s.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return s}function j(e){return r.toByteArray(function(e){if((e=function(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}(e).replace(F,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function B(e,t,n,r){for(var i=0;i<r&&!(i+n>=t.length||i>=e.length);++i)t[i+n]=e[i];return i}},251(e,t){t.read=function(e,t,n,r,i){var s,o,a=8*i-r-1,c=(1<<a)-1,u=c>>1,l=-7,h=n?i-1:0,d=n?-1:1,f=e[t+h];for(h+=d,s=f&(1<<-l)-1,f>>=-l,l+=a;l>0;s=256*s+e[t+h],h+=d,l-=8);for(o=s&(1<<-l)-1,s>>=-l,l+=r;l>0;o=256*o+e[t+h],h+=d,l-=8);if(0===s)s=1-u;else{if(s===c)return o?NaN:1/0*(f?-1:1);o+=Math.pow(2,r),s-=u}return(f?-1:1)*o*Math.pow(2,s-r)},t.write=function(e,t,n,r,i,s){var o,a,c,u=8*s-i-1,l=(1<<u)-1,h=l>>1,d=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,f=r?0:s-1,p=r?1:-1,g=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,o=l):(o=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-o))<1&&(o--,c*=2),(t+=o+h>=1?d/c:d*Math.pow(2,1-h))*c>=2&&(o++,c/=2),o+h>=l?(a=0,o=l):o+h>=1?(a=(t*c-1)*Math.pow(2,i),o+=h):(a=t*Math.pow(2,h-1)*Math.pow(2,i),o=0));i>=8;e[n+f]=255&a,f+=p,a/=256,i-=8);for(o=o<<i|a,u+=i;u>0;e[n+f]=255&o,f+=p,o/=256,u-=8);e[n+f-p]|=128*g}},634(e){var t={}.toString;e.exports=Array.isArray||function(e){return"[object Array]"==t.call(e)}},916(e,t,n){e.exports=self.fetch||(self.fetch=n(782).default||n(782))},596(e,t,n){var r,i,s;s=function(){function e(){for(var e=0,t={};e<arguments.length;e++){var n=arguments[e];for(var r in n)t[r]=n[r]}return t}function t(e){return e.replace(/(%[0-9A-Z]{2})+/g,decodeURIComponent)}return function n(r){function i(){}function s(t,n,s){if("undefined"!=typeof document){"number"==typeof(s=e({path:"/"},i.defaults,s)).expires&&(s.expires=new Date(1*new Date+864e5*s.expires)),s.expires=s.expires?s.expires.toUTCString():"";try{var o=JSON.stringify(n);/^[\{\[]/.test(o)&&(n=o)}catch(e){}n=r.write?r.write(n,t):encodeURIComponent(String(n)).replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g,decodeURIComponent),t=encodeURIComponent(String(t)).replace(/%(23|24|26|2B|5E|60|7C)/g,decodeURIComponent).replace(/[\(\)]/g,escape);var a="";for(var c in s)s[c]&&(a+="; "+c,!0!==s[c]&&(a+="="+s[c].split(";")[0]));return document.cookie=t+"="+n+a}}function o(e,n){if("undefined"!=typeof document){for(var i={},s=document.cookie?document.cookie.split("; "):[],o=0;o<s.length;o++){var a=s[o].split("="),c=a.slice(1).join("=");n||'"'!==c.charAt(0)||(c=c.slice(1,-1));try{var u=t(a[0]);if(c=(r.read||r)(c,u)||t(c),n)try{c=JSON.parse(c)}catch(e){}if(i[u]=c,e===u)break}catch(e){}}return e?i[e]:i}}return i.set=s,i.get=function(e){return o(e,!1)},i.getJSON=function(e){return o(e,!0)},i.remove=function(t,n){s(t,"",e(n,{expires:-1}))},i.defaults={},i.withConverter=n,i}(function(){})},void 0===(i="function"==typeof(r=s)?r.call(t,n,t,e):r)||(e.exports=i),e.exports=s()},284(e,t,n){"use strict";const r="undefined"!=typeof globalThis?globalThis:void 0,i=r?.window;if(i)i.global=i,i.global._runningInNodeJS=!1;else if(r&&(r.global=r,void 0===r.window)){class e{constructor(){this.result=null,this.error=null,this.onload=null,this.onloadend=null,this.onerror=null}readAsDataURL(e){e.arrayBuffer().then(t=>{const n=function(e){if(Buffer)return Buffer.from(e).toString("base64");let t="";const n=new Uint8Array(e);for(let e=0;e<n.length;e+=32768){const r=n.subarray(e,e+32768);t+=String.fromCharCode.apply(null,Array.from(r))}if("function"==typeof btoa)return btoa(t);throw new Error("No base64 encoder available in this environment.")}(t),r=e.type||"application/octet-stream";this.result=`data:${r};base64,${n}`,this.onload&&this.onload({target:this}),this.onloadend&&this.onloadend({target:this})}).catch(e=>{this.error=e,this.onerror&&this.onerror({target:this})})}readAsArrayBuffer(e){e.arrayBuffer().then(e=>{this.result=e,this.onload&&this.onload({target:this}),this.onloadend&&this.onloadend({target:this})}).catch(e=>{this.error=e,this.onerror&&this.onerror({target:this})})}readAsText(e,t="utf-8"){e.text().then(e=>{this.result=e,this.onload&&this.onload({target:this}),this.onloadend&&this.onloadend({target:this})}).catch(e=>{this.error=e,this.onerror&&this.onerror({target:this})})}}r.FileReader=e;class t{constructor(){this.status=0,this.statusText="",this.readyState=0,this.responseText="",this.response=null,this.responseType="",this.responseURL="",this.timeout=0,this.withCredentials=!1,this.onload=null,this.onerror=null,this.onabort=null,this.ontimeout=null,this.onprogress=null,this.onreadystatechange=null,this.upload={onprogress:null},this._method="GET",this._url="",this._headers={},this._aborted=!1}open(e,t){this._method=e,this._url=t,this.readyState=1}setRequestHeader(e,t){this._headers[e]=t}getResponseHeader(e){return null}abort(){this._aborted=!0,this.onabort&&this.onabort({})}send(e){if(this._aborted)return;const t={method:this._method,headers:this._headers};e&&"GET"!==this._method&&"HEAD"!==this._method&&(t.body=e),fetch(this._url,t).then(async e=>{if(!this._aborted){if(this.status=e.status,this.statusText=e.statusText,this.responseURL=e.url,this.readyState=4,"blob"===this.responseType)this.response=await e.blob();else if("json"===this.responseType)try{this.response=await e.json()}catch{this.response=null}else"arraybuffer"===this.responseType?this.response=await e.arrayBuffer():(this.responseText=await e.text(),this.response=this.responseText);this.onload&&this.onload({})}}).catch(e=>{this._aborted||this.onerror&&this.onerror(e)})}}r.XMLHttpRequest=t,r.window={_runningInNodeJS:!0,alert:e=>console.error("[Alert]",e),sessionStorage:{getItem:e=>null,setItem:(e,t)=>{},removeItem:e=>{}},localStorage:{getItem:e=>{const t=n(132),r=n(300);try{const n=r.resolve(process.cwd(),"states","localStorage",`${e}.skapi`);return t.existsSync(n)?t.readFileSync(n,"utf8"):null}catch(e){return null}},setItem:(e,t)=>{const r=n(132),i=n(300);try{const n=i.resolve(process.cwd(),"states","localStorage");r.existsSync(n)||r.mkdirSync(n,{recursive:!0});const s=i.resolve(n,`${e}.skapi`);r.writeFileSync(s,t,"utf8")}catch(e){}},removeItem:e=>{const t=n(132),r=n(300);try{const n=r.resolve(process.cwd(),"states","localStorage",`${e}.skapi`);t.existsSync(n)&&t.unlinkSync(n)}catch(e){}}},location:{href:"",origin:"",hostname:"",protocol:"",replace:e=>{}},navigator:{userAgent:`nodejs/${r?.process?.versions?.node||"unknown"}`,mediaDevices:{getUserMedia:async e=>{throw new Error("getUserMedia is not supported in Node.js environment.")}}},addEventListener:()=>{},removeEventListener:()=>{}}}},215(e,t,n){"use strict";n.r(t),n.d(t,{__assign:()=>s,__asyncDelegator:()=>b,__asyncGenerator:()=>w,__asyncValues:()=>A,__await:()=>y,__awaiter:()=>l,__classPrivateFieldGet:()=>I,__classPrivateFieldSet:()=>T,__createBinding:()=>d,__decorate:()=>a,__exportStar:()=>f,__extends:()=>i,__generator:()=>h,__importDefault:()=>S,__importStar:()=>E,__makeTemplateObject:()=>v,__metadata:()=>u,__param:()=>c,__read:()=>g,__rest:()=>o,__spread:()=>_,__spreadArrays:()=>m,__values:()=>p});var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])},r(e,t)};function i(e,t){function n(){this.constructor=e}r(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}var s=function(){return s=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},s.apply(this,arguments)};function o(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]])}return n}function a(e,t,n,r){var i,s=arguments.length,o=s<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,n,o):i(t,n))||o);return s>3&&o&&Object.defineProperty(t,n,o),o}function c(e,t){return function(n,r){t(n,r,e)}}function u(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}function l(e,t,n,r){return new(n||(n=Promise))(function(i,s){function o(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(o,a)}c((r=r.apply(e,t||[])).next())})}function h(e,t){var n,r,i,s,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(s){return function(a){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;o;)try{if(n=1,r&&(i=2&s[0]?r.return:s[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,s[1])).done)return i;switch(r=0,i&&(s=[2&s[0],i.value]),s[0]){case 0:case 1:i=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,r=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!((i=(i=o.trys).length>0&&i[i.length-1])||6!==s[0]&&2!==s[0])){o=0;continue}if(3===s[0]&&(!i||s[1]>i[0]&&s[1]<i[3])){o.label=s[1];break}if(6===s[0]&&o.label<i[1]){o.label=i[1],i=s;break}if(i&&o.label<i[2]){o.label=i[2],o.ops.push(s);break}i[2]&&o.ops.pop(),o.trys.pop();continue}s=t.call(e,o)}catch(e){s=[6,e],r=0}finally{n=i=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,a])}}}function d(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}function f(e,t){for(var n in e)"default"===n||t.hasOwnProperty(n)||(t[n]=e[n])}function p(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function g(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,i,s=n.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(r=s.next()).done;)o.push(r.value)}catch(e){i={error:e}}finally{try{r&&!r.done&&(n=s.return)&&n.call(s)}finally{if(i)throw i.error}}return o}function _(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(g(arguments[t]));return e}function m(){for(var e=0,t=0,n=arguments.length;t<n;t++)e+=arguments[t].length;var r=Array(e),i=0;for(t=0;t<n;t++)for(var s=arguments[t],o=0,a=s.length;o<a;o++,i++)r[i]=s[o];return r}function y(e){return this instanceof y?(this.v=e,this):new y(e)}function w(e,t,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r,i=n.apply(e,t||[]),s=[];return r={},o("next"),o("throw"),o("return"),r[Symbol.asyncIterator]=function(){return this},r;function o(e){i[e]&&(r[e]=function(t){return new Promise(function(n,r){s.push([e,t,n,r])>1||a(e,t)})})}function a(e,t){try{(n=i[e](t)).value instanceof y?Promise.resolve(n.value.v).then(c,u):l(s[0][2],n)}catch(e){l(s[0][3],e)}var n}function c(e){a("next",e)}function u(e){a("throw",e)}function l(e,t){e(t),s.shift(),s.length&&a(s[0][0],s[0][1])}}function b(e){var t,n;return t={},r("next"),r("throw",function(e){throw e}),r("return"),t[Symbol.iterator]=function(){return this},t;function r(r,i){t[r]=e[r]?function(t){return(n=!n)?{value:y(e[r](t)),done:"return"===r}:i?i(t):t}:i}}function A(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,n=e[Symbol.asyncIterator];return n?n.call(e):(e=p(e),t={},r("next"),r("throw"),r("return"),t[Symbol.asyncIterator]=function(){return this},t);function r(n){t[n]=e[n]&&function(t){return new Promise(function(r,i){!function(e,t,n,r){Promise.resolve(r).then(function(t){e({value:t,done:n})},t)}(r,i,(t=e[n](t)).done,t.value)})}}}function v(e,t){return Object.defineProperty?Object.defineProperty(e,"raw",{value:t}):e.raw=t,e}function E(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t}function S(e){return e&&e.__esModule?e:{default:e}}function I(e,t){if(!t.has(e))throw new TypeError("attempted to get private field on non-instance");return t.get(e)}function T(e,t,n){if(!t.has(e))throw new TypeError("attempted to set private field on non-instance");return t.set(e,n),n}},782(e,t,n){"use strict";function r(e,t){return t=t||{},new Promise(function(n,r){var i=new XMLHttpRequest,s=[],o=[],a={},c=function(){return{ok:2==(i.status/100|0),statusText:i.statusText,status:i.status,url:i.responseURL,text:function(){return Promise.resolve(i.responseText)},json:function(){return Promise.resolve(i.responseText).then(JSON.parse)},blob:function(){return Promise.resolve(new Blob([i.response]))},clone:c,headers:{keys:function(){return s},entries:function(){return o},get:function(e){return a[e.toLowerCase()]},has:function(e){return e.toLowerCase()in a}}}};for(var u in i.open(t.method||"get",e,!0),i.onload=function(){i.getAllResponseHeaders().replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm,function(e,t,n){s.push(t=t.toLowerCase()),o.push([t,n]),a[t]=a[t]?a[t]+","+n:n}),n(c())},i.onerror=r,i.withCredentials="include"==t.credentials,t.headers)i.setRequestHeader(u,t.headers[u]);i.send(t.body||null)})}n.r(t),n.d(t,{default:()=>r})},682(){},132(){},300(){}},t={};function n(r){var i=t[r];if(void 0!==i)return i.exports;var s=t[r]={exports:{}};return e[r](s,s.exports,n),s.exports}n.d=(e,t)=>{for(var r in t)n.o(t,r)&&!n.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var r={};return(()=>{"use strict";n.r(r),n.d(r,{Skapi:()=>ur,SkapiError:()=>te,Types:()=>e});var e={};n.r(e),n(284);var t,i=function(){function e(e){var t=e||{},n=t.ValidationData,r=t.Username,i=t.Password,s=t.AuthParameters,o=t.ClientMetadata;this.validationData=n||{},this.authParameters=s||{},this.clientMetadata=o||{},this.username=r,this.password=i}var t=e.prototype;return t.getUsername=function(){return this.username},t.getPassword=function(){return this.password},t.getValidationData=function(){return this.validationData},t.getAuthParameters=function(){return this.authParameters},t.getClientMetadata=function(){return this.clientMetadata},e}(),s=n(287);if("undefined"!=typeof window&&window.crypto&&(t=window.crypto),!t&&"undefined"!=typeof window&&window.msCrypto&&(t=window.msCrypto),!t&&void 0!==n.g&&n.g.crypto&&(t=n.g.crypto),!t)try{t=n(682)}catch(e){}function o(){if(t){if("function"==typeof t.getRandomValues)try{return t.getRandomValues(new Uint32Array(1))[0]}catch(e){}if("function"==typeof t.randomBytes)try{return t.randomBytes(4).readInt32LE()}catch(e){}}throw new Error("Native crypto module could not be used to get secure random number.")}var a=function(){function e(e,t){e=this.words=e||[],this.sigBytes=null!=t?t:4*e.length}var t=e.prototype;return t.random=function(t){for(var n=[],r=0;r<t;r+=4)n.push(o());return new e(n,t)},t.toString=function(){return function(e){for(var t=e.words,n=e.sigBytes,r=[],i=0;i<n;i++){var s=t[i>>>2]>>>24-i%4*8&255;r.push((s>>>4).toString(16)),r.push((15&s).toString(16))}return r.join("")}(this)},e}(),c=n(523);const u=l;function l(e,t){null!=e&&this.fromString(e,t)}function h(){return new l(null)}var d,f="undefined"!=typeof navigator;f&&"Microsoft Internet Explorer"==navigator.appName?(l.prototype.am=function(e,t,n,r,i,s){for(var o=32767&t,a=t>>15;--s>=0;){var c=32767&this[e],u=this[e++]>>15,l=a*c+u*o;i=((c=o*c+((32767&l)<<15)+n[r]+(1073741823&i))>>>30)+(l>>>15)+a*u+(i>>>30),n[r++]=1073741823&c}return i},d=30):f&&"Netscape"!=navigator.appName?(l.prototype.am=function(e,t,n,r,i,s){for(;--s>=0;){var o=t*this[e++]+n[r]+i;i=Math.floor(o/67108864),n[r++]=67108863&o}return i},d=26):(l.prototype.am=function(e,t,n,r,i,s){for(var o=16383&t,a=t>>14;--s>=0;){var c=16383&this[e],u=this[e++]>>14,l=a*c+u*o;i=((c=o*c+((16383&l)<<14)+n[r]+i)>>28)+(l>>14)+a*u,n[r++]=268435455&c}return i},d=28),l.prototype.DB=d,l.prototype.DM=(1<<d)-1,l.prototype.DV=1<<d,l.prototype.FV=Math.pow(2,52),l.prototype.F1=52-d,l.prototype.F2=2*d-52;var p,g,_=new Array;for(p="0".charCodeAt(0),g=0;g<=9;++g)_[p++]=g;for(p="a".charCodeAt(0),g=10;g<36;++g)_[p++]=g;for(p="A".charCodeAt(0),g=10;g<36;++g)_[p++]=g;function m(e){return"0123456789abcdefghijklmnopqrstuvwxyz".charAt(e)}function y(e,t){var n=_[e.charCodeAt(t)];return null==n?-1:n}function w(e){var t=h();return t.fromInt(e),t}function b(e){var t,n=1;return 0!=(t=e>>>16)&&(e=t,n+=16),0!=(t=e>>8)&&(e=t,n+=8),0!=(t=e>>4)&&(e=t,n+=4),0!=(t=e>>2)&&(e=t,n+=2),0!=(t=e>>1)&&(e=t,n+=1),n}function A(e){this.m=e,this.mp=e.invDigit(),this.mpl=32767&this.mp,this.mph=this.mp>>15,this.um=(1<<e.DB-15)-1,this.mt2=2*e.t}function v(e){return s.hp.from((new a).random(e).toString(),"hex")}A.prototype.convert=function(e){var t=h();return e.abs().dlShiftTo(this.m.t,t),t.divRemTo(this.m,null,t),e.s<0&&t.compareTo(l.ZERO)>0&&this.m.subTo(t,t),t},A.prototype.revert=function(e){var t=h();return e.copyTo(t),this.reduce(t),t},A.prototype.reduce=function(e){for(;e.t<=this.mt2;)e[e.t++]=0;for(var t=0;t<this.m.t;++t){var n=32767&e[t],r=n*this.mpl+((n*this.mph+(e[t]>>15)*this.mpl&this.um)<<15)&e.DM;for(e[n=t+this.m.t]+=this.m.am(0,r,e,t,0,this.m.t);e[n]>=e.DV;)e[n]-=e.DV,e[++n]++}e.clamp(),e.drShiftTo(this.m.t,e),e.compareTo(this.m)>=0&&e.subTo(this.m,e)},A.prototype.mulTo=function(e,t,n){e.multiplyTo(t,n),this.reduce(n)},A.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)},l.prototype.copyTo=function(e){for(var t=this.t-1;t>=0;--t)e[t]=this[t];e.t=this.t,e.s=this.s},l.prototype.fromInt=function(e){this.t=1,this.s=e<0?-1:0,e>0?this[0]=e:e<-1?this[0]=e+this.DV:this.t=0},l.prototype.fromString=function(e,t){var n;if(16==t)n=4;else if(8==t)n=3;else if(2==t)n=1;else if(32==t)n=5;else{if(4!=t)throw new Error("Only radix 2, 4, 8, 16, 32 are supported");n=2}this.t=0,this.s=0;for(var r=e.length,i=!1,s=0;--r>=0;){var o=y(e,r);o<0?"-"==e.charAt(r)&&(i=!0):(i=!1,0==s?this[this.t++]=o:s+n>this.DB?(this[this.t-1]|=(o&(1<<this.DB-s)-1)<<s,this[this.t++]=o>>this.DB-s):this[this.t-1]|=o<<s,(s+=n)>=this.DB&&(s-=this.DB))}this.clamp(),i&&l.ZERO.subTo(this,this)},l.prototype.clamp=function(){for(var e=this.s&this.DM;this.t>0&&this[this.t-1]==e;)--this.t},l.prototype.dlShiftTo=function(e,t){var n;for(n=this.t-1;n>=0;--n)t[n+e]=this[n];for(n=e-1;n>=0;--n)t[n]=0;t.t=this.t+e,t.s=this.s},l.prototype.drShiftTo=function(e,t){for(var n=e;n<this.t;++n)t[n-e]=this[n];t.t=Math.max(this.t-e,0),t.s=this.s},l.prototype.lShiftTo=function(e,t){var n,r=e%this.DB,i=this.DB-r,s=(1<<i)-1,o=Math.floor(e/this.DB),a=this.s<<r&this.DM;for(n=this.t-1;n>=0;--n)t[n+o+1]=this[n]>>i|a,a=(this[n]&s)<<r;for(n=o-1;n>=0;--n)t[n]=0;t[o]=a,t.t=this.t+o+1,t.s=this.s,t.clamp()},l.prototype.rShiftTo=function(e,t){t.s=this.s;var n=Math.floor(e/this.DB);if(n>=this.t)t.t=0;else{var r=e%this.DB,i=this.DB-r,s=(1<<r)-1;t[0]=this[n]>>r;for(var o=n+1;o<this.t;++o)t[o-n-1]|=(this[o]&s)<<i,t[o-n]=this[o]>>r;r>0&&(t[this.t-n-1]|=(this.s&s)<<i),t.t=this.t-n,t.clamp()}},l.prototype.subTo=function(e,t){for(var n=0,r=0,i=Math.min(e.t,this.t);n<i;)r+=this[n]-e[n],t[n++]=r&this.DM,r>>=this.DB;if(e.t<this.t){for(r-=e.s;n<this.t;)r+=this[n],t[n++]=r&this.DM,r>>=this.DB;r+=this.s}else{for(r+=this.s;n<e.t;)r-=e[n],t[n++]=r&this.DM,r>>=this.DB;r-=e.s}t.s=r<0?-1:0,r<-1?t[n++]=this.DV+r:r>0&&(t[n++]=r),t.t=n,t.clamp()},l.prototype.multiplyTo=function(e,t){var n=this.abs(),r=e.abs(),i=n.t;for(t.t=i+r.t;--i>=0;)t[i]=0;for(i=0;i<r.t;++i)t[i+n.t]=n.am(0,r[i],t,i,0,n.t);t.s=0,t.clamp(),this.s!=e.s&&l.ZERO.subTo(t,t)},l.prototype.squareTo=function(e){for(var t=this.abs(),n=e.t=2*t.t;--n>=0;)e[n]=0;for(n=0;n<t.t-1;++n){var r=t.am(n,t[n],e,2*n,0,1);(e[n+t.t]+=t.am(n+1,2*t[n],e,2*n+1,r,t.t-n-1))>=t.DV&&(e[n+t.t]-=t.DV,e[n+t.t+1]=1)}e.t>0&&(e[e.t-1]+=t.am(n,t[n],e,2*n,0,1)),e.s=0,e.clamp()},l.prototype.divRemTo=function(e,t,n){var r=e.abs();if(!(r.t<=0)){var i=this.abs();if(i.t<r.t)return null!=t&&t.fromInt(0),void(null!=n&&this.copyTo(n));null==n&&(n=h());var s=h(),o=this.s,a=e.s,c=this.DB-b(r[r.t-1]);c>0?(r.lShiftTo(c,s),i.lShiftTo(c,n)):(r.copyTo(s),i.copyTo(n));var u=s.t,d=s[u-1];if(0!=d){var f=d*(1<<this.F1)+(u>1?s[u-2]>>this.F2:0),p=this.FV/f,g=(1<<this.F1)/f,_=1<<this.F2,m=n.t,y=m-u,w=null==t?h():t;for(s.dlShiftTo(y,w),n.compareTo(w)>=0&&(n[n.t++]=1,n.subTo(w,n)),l.ONE.dlShiftTo(u,w),w.subTo(s,s);s.t<u;)s[s.t++]=0;for(;--y>=0;){var A=n[--m]==d?this.DM:Math.floor(n[m]*p+(n[m-1]+_)*g);if((n[m]+=s.am(0,A,n,y,0,u))<A)for(s.dlShiftTo(y,w),n.subTo(w,n);n[m]<--A;)n.subTo(w,n)}null!=t&&(n.drShiftTo(u,t),o!=a&&l.ZERO.subTo(t,t)),n.t=u,n.clamp(),c>0&&n.rShiftTo(c,n),o<0&&l.ZERO.subTo(n,n)}}},l.prototype.invDigit=function(){if(this.t<1)return 0;var e=this[0];if(!(1&e))return 0;var t=3&e;return(t=(t=(t=(t=t*(2-(15&e)*t)&15)*(2-(255&e)*t)&255)*(2-((65535&e)*t&65535))&65535)*(2-e*t%this.DV)%this.DV)>0?this.DV-t:-t},l.prototype.addTo=function(e,t){for(var n=0,r=0,i=Math.min(e.t,this.t);n<i;)r+=this[n]+e[n],t[n++]=r&this.DM,r>>=this.DB;if(e.t<this.t){for(r+=e.s;n<this.t;)r+=this[n],t[n++]=r&this.DM,r>>=this.DB;r+=this.s}else{for(r+=this.s;n<e.t;)r+=e[n],t[n++]=r&this.DM,r>>=this.DB;r+=e.s}t.s=r<0?-1:0,r>0?t[n++]=r:r<-1&&(t[n++]=this.DV+r),t.t=n,t.clamp()},l.prototype.toString=function(e){if(this.s<0)return"-"+this.negate().toString(e);var t;if(16==e)t=4;else if(8==e)t=3;else if(2==e)t=1;else if(32==e)t=5;else{if(4!=e)throw new Error("Only radix 2, 4, 8, 16, 32 are supported");t=2}var n,r=(1<<t)-1,i=!1,s="",o=this.t,a=this.DB-o*this.DB%t;if(o-- >0)for(a<this.DB&&(n=this[o]>>a)>0&&(i=!0,s=m(n));o>=0;)a<t?(n=(this[o]&(1<<a)-1)<<t-a,n|=this[--o]>>(a+=this.DB-t)):(n=this[o]>>(a-=t)&r,a<=0&&(a+=this.DB,--o)),n>0&&(i=!0),i&&(s+=m(n));return i?s:"0"},l.prototype.negate=function(){var e=h();return l.ZERO.subTo(this,e),e},l.prototype.abs=function(){return this.s<0?this.negate():this},l.prototype.compareTo=function(e){var t=this.s-e.s;if(0!=t)return t;var n=this.t;if(0!=(t=n-e.t))return this.s<0?-t:t;for(;--n>=0;)if(0!=(t=this[n]-e[n]))return t;return 0},l.prototype.bitLength=function(){return this.t<=0?0:this.DB*(this.t-1)+b(this[this.t-1]^this.s&this.DM)},l.prototype.mod=function(e){var t=h();return this.abs().divRemTo(e,null,t),this.s<0&&t.compareTo(l.ZERO)>0&&e.subTo(t,t),t},l.prototype.equals=function(e){return 0==this.compareTo(e)},l.prototype.add=function(e){var t=h();return this.addTo(e,t),t},l.prototype.subtract=function(e){var t=h();return this.subTo(e,t),t},l.prototype.multiply=function(e){var t=h();return this.multiplyTo(e,t),t},l.prototype.divide=function(e){var t=h();return this.divRemTo(e,t,null),t},l.prototype.modPow=function(e,t,n){var r,i=e.bitLength(),s=w(1),o=new A(t);if(i<=0)return s;r=i<18?1:i<48?3:i<144?4:i<768?5:6;var a=new Array,c=3,u=r-1,l=(1<<r)-1;if(a[1]=o.convert(this),r>1){var d=h();for(o.sqrTo(a[1],d);c<=l;)a[c]=h(),o.mulTo(d,a[c-2],a[c]),c+=2}var f,p,g=e.t-1,_=!0,m=h();for(i=b(e[g])-1;g>=0;){for(i>=u?f=e[g]>>i-u&l:(f=(e[g]&(1<<i+1)-1)<<u-i,g>0&&(f|=e[g-1]>>this.DB+i-u)),c=r;!(1&f);)f>>=1,--c;if((i-=c)<0&&(i+=this.DB,--g),_)a[f].copyTo(s),_=!1;else{for(;c>1;)o.sqrTo(s,m),o.sqrTo(m,s),c-=2;c>0?o.sqrTo(s,m):(p=s,s=m,m=p),o.mulTo(m,a[f],s)}for(;g>=0&&!(e[g]&1<<i);)o.sqrTo(s,m),p=s,s=m,m=p,--i<0&&(i=this.DB-1,--g)}var y=o.revert(s);return n(null,y),y},l.ZERO=w(0),l.ONE=w(1);var E=/^[89a-f]/i,S=function(){function e(e){this.N=new u("FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200CBBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF",16),this.g=new u("2",16),this.k=new u(this.hexHash(""+this.padHex(this.N)+this.padHex(this.g)),16),this.smallAValue=this.generateRandomSmallA(),this.getLargeAValue(function(){}),this.infoBits=s.hp.from("Caldera Derived Key","utf8"),this.poolName=e}var t=e.prototype;return t.getSmallAValue=function(){return this.smallAValue},t.getLargeAValue=function(e){var t=this;this.largeAValue?e(null,this.largeAValue):this.calculateA(this.smallAValue,function(n,r){n&&e(n,null),t.largeAValue=r,e(null,t.largeAValue)})},t.generateRandomSmallA=function(){var e=v(128).toString("hex");return new u(e,16)},t.generateRandomString=function(){return v(40).toString("base64")},t.getRandomPassword=function(){return this.randomPassword},t.getSaltDevices=function(){return this.SaltToHashDevices},t.getVerifierDevices=function(){return this.verifierDevices},t.generateHashDevice=function(e,t,n){var r=this;this.randomPassword=this.generateRandomString();var i=""+e+t+":"+this.randomPassword,s=this.hash(i),o=v(16).toString("hex");this.SaltToHashDevices=this.padHex(new u(o,16)),this.g.modPow(new u(this.hexHash(this.SaltToHashDevices+s),16),this.N,function(e,t){e&&n(e,null),r.verifierDevices=r.padHex(t),n(null,null)})},t.calculateA=function(e,t){var n=this;this.g.modPow(e,this.N,function(e,r){e&&t(e,null),r.mod(n.N).equals(u.ZERO)&&t(new Error("Illegal paramater. A mod N cannot be 0."),null),t(null,r)})},t.calculateU=function(e,t){return this.UHexHash=this.hexHash(this.padHex(e)+this.padHex(t)),new u(this.UHexHash,16)},t.hash=function(e){var t=new c.Sha256;t.update(e);var n=t.digestSync(),r=s.hp.from(n).toString("hex");return new Array(64-r.length).join("0")+r},t.hexHash=function(e){return this.hash(s.hp.from(e,"hex"))},t.computehkdf=function(e,t){var n=s.hp.concat([this.infoBits,s.hp.from(String.fromCharCode(1),"utf8")]),r=new c.Sha256(t);r.update(e);var i=r.digestSync(),o=new c.Sha256(i);return o.update(n),o.digestSync().slice(0,16)},t.getPasswordAuthenticationKey=function(e,t,n,r,i){var o=this;if(n.mod(this.N).equals(u.ZERO))throw new Error("B cannot be zero.");if(this.UValue=this.calculateU(this.largeAValue,n),this.UValue.equals(u.ZERO))throw new Error("U cannot be zero.");var a=""+this.poolName+e+":"+t,c=this.hash(a),l=new u(this.hexHash(this.padHex(r)+c),16);this.calculateS(l,n,function(e,t){e&&i(e,null);var n=o.computehkdf(s.hp.from(o.padHex(t),"hex"),s.hp.from(o.padHex(o.UValue),"hex"));i(null,n)})},t.calculateS=function(e,t,n){var r=this;this.g.modPow(e,this.N,function(i,s){i&&n(i,null),t.subtract(r.k.multiply(s)).modPow(r.smallAValue.add(r.UValue.multiply(e)),r.N,function(e,t){e&&n(e,null),n(null,t.mod(r.N))})})},t.getNewPasswordRequiredChallengeUserAttributePrefix=function(){return"userAttributes."},t.padHex=function(e){if(!(e instanceof u))throw new Error("Not a BigInteger");var t=e.compareTo(u.ZERO)<0,n=e.abs().toString(16);if(n=n.length%2!=0?"0"+n:n,n=E.test(n)?"00"+n:n,t){var r=n.split("").map(function(e){var t=15&~parseInt(e,16);return"0123456789ABCDEF".charAt(t)}).join("");(n=new u(r,16).add(u.ONE).toString(16)).toUpperCase().startsWith("FF8")&&(n=n.substring(2))}return n},e}(),I=function(){function e(e){this.jwtToken=e||"",this.payload=this.decodePayload()}var t=e.prototype;return t.getJwtToken=function(){return this.jwtToken},t.getExpiration=function(){return this.payload.exp},t.getIssuedAt=function(){return this.payload.iat},t.decodePayload=function(){var e=this.jwtToken.split(".")[1];try{return JSON.parse(s.hp.from(e,"base64").toString("utf8"))}catch(e){return{}}},e}();function T(e,t){return T=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},T(e,t)}var R=function(e){function t(t){var n=(void 0===t?{}:t).AccessToken;return e.call(this,n||"")||this}var n,r;return r=e,(n=t).prototype=Object.create(r.prototype),n.prototype.constructor=n,T(n,r),t}(I);function D(e,t){return D=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},D(e,t)}var U=function(e){function t(t){var n=(void 0===t?{}:t).IdToken;return e.call(this,n||"")||this}var n,r;return r=e,(n=t).prototype=Object.create(r.prototype),n.prototype.constructor=n,D(n,r),t}(I),P=function(){function e(e){var t=(void 0===e?{}:e).RefreshToken;this.token=t||""}return e.prototype.getToken=function(){return this.token},e}(),C="aws-amplify/5.0.4",k="undefined"!=typeof navigator&&"ReactNative"===navigator.product,N=function(){function e(e){var t=void 0===e?{}:e,n=t.IdToken,r=t.RefreshToken,i=t.AccessToken,s=t.ClockDrift;if(null==i||null==n)throw new Error("Id token and Access Token must be present.");this.idToken=n,this.refreshToken=r,this.accessToken=i,this.clockDrift=void 0===s?this.calculateClockDrift():s}var t=e.prototype;return t.getIdToken=function(){return this.idToken},t.getRefreshToken=function(){return this.refreshToken},t.getAccessToken=function(){return this.accessToken},t.getClockDrift=function(){return this.clockDrift},t.calculateClockDrift=function(){return Math.floor(new Date/1e3)-Math.min(this.accessToken.getIssuedAt(),this.idToken.getIssuedAt())},t.isValid=function(){var e=Math.floor(new Date/1e3)-this.clockDrift;return e<this.accessToken.getExpiration()&&e<this.idToken.getExpiration()},e}(),L=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],O=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],M=function(){function e(){}return e.prototype.getNowString=function(){var e=new Date,t=O[e.getUTCDay()],n=L[e.getUTCMonth()],r=e.getUTCDate(),i=e.getUTCHours();i<10&&(i="0"+i);var s=e.getUTCMinutes();s<10&&(s="0"+s);var o=e.getUTCSeconds();return o<10&&(o="0"+o),t+" "+n+" "+r+" "+i+":"+s+":"+o+" UTC "+e.getUTCFullYear()},e}(),V=function(){function e(e){var t=void 0===e?{}:e,n=t.Name,r=t.Value;this.Name=n||"",this.Value=r||""}var t=e.prototype;return t.getValue=function(){return this.Value},t.setValue=function(e){return this.Value=e,this},t.getName=function(){return this.Name},t.setName=function(e){return this.Name=e,this},t.toString=function(){return JSON.stringify(this)},t.toJSON=function(){return{Name:this.Name,Value:this.Value}},e}(),x={},F=function(){function e(){}return e.setItem=function(e,t){return x[e]=t,x[e]},e.getItem=function(e){return Object.prototype.hasOwnProperty.call(x,e)?x[e]:void 0},e.removeItem=function(e){return delete x[e]},e.clear=function(){return x={}},e}(),q=function(){function e(){try{this.storageWindow=window.localStorage,this.storageWindow.setItem("aws.cognito.test-ls",1),this.storageWindow.removeItem("aws.cognito.test-ls")}catch(e){this.storageWindow=F}}return e.prototype.getStorage=function(){return this.storageWindow},e}(),$="undefined"!=typeof navigator?k?"react-native":navigator.userAgent:"nodejs",j=function(){function e(e){if(null==e||null==e.Username||null==e.Pool)throw new Error("Username and Pool information are required.");this.username=e.Username||"",this.pool=e.Pool,this.Session=null,this.client=e.Pool.client,this.signInUserSession=null,this.authenticationFlowType="USER_SRP_AUTH",this.storage=e.Storage||(new q).getStorage(),this.keyPrefix="CognitoIdentityServiceProvider."+this.pool.getClientId(),this.userDataKey=this.keyPrefix+"."+this.username+".userData"}var t=e.prototype;return t.setSignInUserSession=function(e){this.clearCachedUserData(),this.signInUserSession=e,this.cacheTokens()},t.getSignInUserSession=function(){return this.signInUserSession},t.getUsername=function(){return this.username},t.getAuthenticationFlowType=function(){return this.authenticationFlowType},t.setAuthenticationFlowType=function(e){this.authenticationFlowType=e},t.initiateAuth=function(e,t){var n=this,r=e.getAuthParameters();r.USERNAME=this.username;var i=0!==Object.keys(e.getValidationData()).length?e.getValidationData():e.getClientMetadata(),s={AuthFlow:"CUSTOM_AUTH",ClientId:this.pool.getClientId(),AuthParameters:r,ClientMetadata:i};this.getUserContextData()&&(s.UserContextData=this.getUserContextData()),this.client.request("InitiateAuth",s,function(e,r){if(e)return t.onFailure(e);var i=r.ChallengeName,s=r.ChallengeParameters;return"CUSTOM_CHALLENGE"===i?(n.Session=r.Session,t.customChallenge(s)):(n.signInUserSession=n.getCognitoUserSession(r.AuthenticationResult),n.cacheTokens(),t.onSuccess(n.signInUserSession))})},t.authenticateUser=function(e,t){return"USER_PASSWORD_AUTH"===this.authenticationFlowType?this.authenticateUserPlainUsernamePassword(e,t):"USER_SRP_AUTH"===this.authenticationFlowType||"CUSTOM_AUTH"===this.authenticationFlowType?this.authenticateUserDefaultAuth(e,t):t.onFailure(new Error("Authentication flow type is invalid."))},t.authenticateUserDefaultAuth=function(e,t){var n,r,i=this,o=new S(this.pool.getUserPoolName()),a=new M,l={};null!=this.deviceKey&&(l.DEVICE_KEY=this.deviceKey),l.USERNAME=this.username,o.getLargeAValue(function(h,d){h&&t.onFailure(h),l.SRP_A=d.toString(16),"CUSTOM_AUTH"===i.authenticationFlowType&&(l.CHALLENGE_NAME="SRP_A");var f=0!==Object.keys(e.getValidationData()).length?e.getValidationData():e.getClientMetadata(),p={AuthFlow:i.authenticationFlowType,ClientId:i.pool.getClientId(),AuthParameters:l,ClientMetadata:f};i.getUserContextData(i.username)&&(p.UserContextData=i.getUserContextData(i.username)),i.client.request("InitiateAuth",p,function(l,h){if(l)return t.onFailure(l);var d=h.ChallengeParameters;i.username=d.USER_ID_FOR_SRP,i.userDataKey=i.keyPrefix+"."+i.username+".userData",n=new u(d.SRP_B,16),r=new u(d.SALT,16),i.getCachedDeviceKeyAndPassword(),o.getPasswordAuthenticationKey(i.username,e.getPassword(),n,r,function(e,n){e&&t.onFailure(e);var r=a.getNowString(),u=s.hp.concat([s.hp.from(i.pool.getUserPoolName(),"utf8"),s.hp.from(i.username,"utf8"),s.hp.from(d.SECRET_BLOCK,"base64"),s.hp.from(r,"utf8")]),l=new c.Sha256(n);l.update(u);var p=l.digestSync(),g=s.hp.from(p).toString("base64"),_={};_.USERNAME=i.username,_.PASSWORD_CLAIM_SECRET_BLOCK=d.SECRET_BLOCK,_.TIMESTAMP=r,_.PASSWORD_CLAIM_SIGNATURE=g,null!=i.deviceKey&&(_.DEVICE_KEY=i.deviceKey);var m=function(e,t){return i.client.request("RespondToAuthChallenge",e,function(n,r){return n&&"ResourceNotFoundException"===n.code&&-1!==n.message.toLowerCase().indexOf("device")?(_.DEVICE_KEY=null,i.deviceKey=null,i.randomPassword=null,i.deviceGroupKey=null,i.clearCachedDeviceKeyAndPassword(),m(e,t)):t(n,r)})},y={ChallengeName:"PASSWORD_VERIFIER",ClientId:i.pool.getClientId(),ChallengeResponses:_,Session:h.Session,ClientMetadata:f};i.getUserContextData()&&(y.UserContextData=i.getUserContextData()),m(y,function(e,n){return e?t.onFailure(e):i.authenticateUserInternal(n,o,t)})})})})},t.authenticateUserPlainUsernamePassword=function(e,t){var n=this,r={};if(r.USERNAME=this.username,r.PASSWORD=e.getPassword(),r.PASSWORD){var i=new S(this.pool.getUserPoolName());this.getCachedDeviceKeyAndPassword(),null!=this.deviceKey&&(r.DEVICE_KEY=this.deviceKey);var s=0!==Object.keys(e.getValidationData()).length?e.getValidationData():e.getClientMetadata(),o={AuthFlow:"USER_PASSWORD_AUTH",ClientId:this.pool.getClientId(),AuthParameters:r,ClientMetadata:s};this.getUserContextData(this.username)&&(o.UserContextData=this.getUserContextData(this.username)),this.client.request("InitiateAuth",o,function(e,r){return e?t.onFailure(e):n.authenticateUserInternal(r,i,t)})}else t.onFailure(new Error("PASSWORD parameter is required"))},t.authenticateUserInternal=function(e,t,n){var r=this,i=e.ChallengeName,o=e.ChallengeParameters;if("SMS_MFA"===i)return this.Session=e.Session,n.mfaRequired(i,o);if("SELECT_MFA_TYPE"===i)return this.Session=e.Session,n.selectMFAType(i,o);if("MFA_SETUP"===i)return this.Session=e.Session,n.mfaSetup(i,o);if("SOFTWARE_TOKEN_MFA"===i)return this.Session=e.Session,n.totpRequired(i,o);if("CUSTOM_CHALLENGE"===i)return this.Session=e.Session,n.customChallenge(o);if("NEW_PASSWORD_REQUIRED"===i){this.Session=e.Session;var a=null,c=null,u=[],l=t.getNewPasswordRequiredChallengeUserAttributePrefix();if(o&&(a=JSON.parse(e.ChallengeParameters.userAttributes),c=JSON.parse(e.ChallengeParameters.requiredAttributes)),c)for(var h=0;h<c.length;h++)u[h]=c[h].substr(l.length);return n.newPasswordRequired(a,u)}if("DEVICE_SRP_AUTH"===i)return this.Session=e.Session,void this.getDeviceResponse(n);this.signInUserSession=this.getCognitoUserSession(e.AuthenticationResult),this.challengeName=i,this.cacheTokens();var d=e.AuthenticationResult.NewDeviceMetadata;if(null==d)return n.onSuccess(this.signInUserSession);t.generateHashDevice(e.AuthenticationResult.NewDeviceMetadata.DeviceGroupKey,e.AuthenticationResult.NewDeviceMetadata.DeviceKey,function(i){if(i)return n.onFailure(i);var o={Salt:s.hp.from(t.getSaltDevices(),"hex").toString("base64"),PasswordVerifier:s.hp.from(t.getVerifierDevices(),"hex").toString("base64")};r.verifierDevices=o.PasswordVerifier,r.deviceGroupKey=d.DeviceGroupKey,r.randomPassword=t.getRandomPassword(),r.client.request("ConfirmDevice",{DeviceKey:d.DeviceKey,AccessToken:r.signInUserSession.getAccessToken().getJwtToken(),DeviceSecretVerifierConfig:o,DeviceName:$},function(t,i){return t?n.onFailure(t):(r.deviceKey=e.AuthenticationResult.NewDeviceMetadata.DeviceKey,r.cacheDeviceKeyAndPassword(),!0===i.UserConfirmationNecessary?n.onSuccess(r.signInUserSession,i.UserConfirmationNecessary):n.onSuccess(r.signInUserSession))})})},t.completeNewPasswordChallenge=function(e,t,n,r){var i=this;if(!e)return n.onFailure(new Error("New password is required."));var s=new S(this.pool.getUserPoolName()),o=s.getNewPasswordRequiredChallengeUserAttributePrefix(),a={};t&&Object.keys(t).forEach(function(e){a[o+e]=t[e]}),a.NEW_PASSWORD=e,a.USERNAME=this.username;var c={ChallengeName:"NEW_PASSWORD_REQUIRED",ClientId:this.pool.getClientId(),ChallengeResponses:a,Session:this.Session,ClientMetadata:r};this.getUserContextData()&&(c.UserContextData=this.getUserContextData()),this.client.request("RespondToAuthChallenge",c,function(e,t){return e?n.onFailure(e):i.authenticateUserInternal(t,s,n)})},t.getDeviceResponse=function(e,t){var n=this,r=new S(this.deviceGroupKey),i=new M,o={};o.USERNAME=this.username,o.DEVICE_KEY=this.deviceKey,r.getLargeAValue(function(a,l){a&&e.onFailure(a),o.SRP_A=l.toString(16);var h={ChallengeName:"DEVICE_SRP_AUTH",ClientId:n.pool.getClientId(),ChallengeResponses:o,ClientMetadata:t,Session:n.Session};n.getUserContextData()&&(h.UserContextData=n.getUserContextData()),n.client.request("RespondToAuthChallenge",h,function(t,o){if(t)return e.onFailure(t);var a=o.ChallengeParameters,l=new u(a.SRP_B,16),h=new u(a.SALT,16);r.getPasswordAuthenticationKey(n.deviceKey,n.randomPassword,l,h,function(t,r){if(t)return e.onFailure(t);var u=i.getNowString(),l=s.hp.concat([s.hp.from(n.deviceGroupKey,"utf8"),s.hp.from(n.deviceKey,"utf8"),s.hp.from(a.SECRET_BLOCK,"base64"),s.hp.from(u,"utf8")]),h=new c.Sha256(r);h.update(l);var d=h.digestSync(),f=s.hp.from(d).toString("base64"),p={};p.USERNAME=n.username,p.PASSWORD_CLAIM_SECRET_BLOCK=a.SECRET_BLOCK,p.TIMESTAMP=u,p.PASSWORD_CLAIM_SIGNATURE=f,p.DEVICE_KEY=n.deviceKey;var g={ChallengeName:"DEVICE_PASSWORD_VERIFIER",ClientId:n.pool.getClientId(),ChallengeResponses:p,Session:o.Session};n.getUserContextData()&&(g.UserContextData=n.getUserContextData()),n.client.request("RespondToAuthChallenge",g,function(t,r){return t?e.onFailure(t):(n.signInUserSession=n.getCognitoUserSession(r.AuthenticationResult),n.cacheTokens(),e.onSuccess(n.signInUserSession))})})})})},t.confirmRegistration=function(e,t,n,r){var i={ClientId:this.pool.getClientId(),ConfirmationCode:e,Username:this.username,ForceAliasCreation:t,ClientMetadata:r};this.getUserContextData()&&(i.UserContextData=this.getUserContextData()),this.client.request("ConfirmSignUp",i,function(e){return e?n(e,null):n(null,"SUCCESS")})},t.sendCustomChallengeAnswer=function(e,t,n){var r=this,i={};i.USERNAME=this.username,i.ANSWER=e;var s=new S(this.pool.getUserPoolName());this.getCachedDeviceKeyAndPassword(),null!=this.deviceKey&&(i.DEVICE_KEY=this.deviceKey);var o={ChallengeName:"CUSTOM_CHALLENGE",ChallengeResponses:i,ClientId:this.pool.getClientId(),Session:this.Session,ClientMetadata:n};this.getUserContextData()&&(o.UserContextData=this.getUserContextData()),this.client.request("RespondToAuthChallenge",o,function(e,n){return e?t.onFailure(e):r.authenticateUserInternal(n,s,t)})},t.sendMFACode=function(e,t,n,r){var i=this,o={};o.USERNAME=this.username,o.SMS_MFA_CODE=e;var a=n||"SMS_MFA";"SOFTWARE_TOKEN_MFA"===a&&(o.SOFTWARE_TOKEN_MFA_CODE=e),null!=this.deviceKey&&(o.DEVICE_KEY=this.deviceKey);var c={ChallengeName:a,ChallengeResponses:o,ClientId:this.pool.getClientId(),Session:this.Session,ClientMetadata:r};this.getUserContextData()&&(c.UserContextData=this.getUserContextData()),this.client.request("RespondToAuthChallenge",c,function(e,n){if(e)return t.onFailure(e);if("DEVICE_SRP_AUTH"!==n.ChallengeName){if(i.signInUserSession=i.getCognitoUserSession(n.AuthenticationResult),i.cacheTokens(),null==n.AuthenticationResult.NewDeviceMetadata)return t.onSuccess(i.signInUserSession);var r=new S(i.pool.getUserPoolName());r.generateHashDevice(n.AuthenticationResult.NewDeviceMetadata.DeviceGroupKey,n.AuthenticationResult.NewDeviceMetadata.DeviceKey,function(e){if(e)return t.onFailure(e);var o={Salt:s.hp.from(r.getSaltDevices(),"hex").toString("base64"),PasswordVerifier:s.hp.from(r.getVerifierDevices(),"hex").toString("base64")};i.verifierDevices=o.PasswordVerifier,i.deviceGroupKey=n.AuthenticationResult.NewDeviceMetadata.DeviceGroupKey,i.randomPassword=r.getRandomPassword(),i.client.request("ConfirmDevice",{DeviceKey:n.AuthenticationResult.NewDeviceMetadata.DeviceKey,AccessToken:i.signInUserSession.getAccessToken().getJwtToken(),DeviceSecretVerifierConfig:o,DeviceName:$},function(e,r){return e?t.onFailure(e):(i.deviceKey=n.AuthenticationResult.NewDeviceMetadata.DeviceKey,i.cacheDeviceKeyAndPassword(),!0===r.UserConfirmationNecessary?t.onSuccess(i.signInUserSession,r.UserConfirmationNecessary):t.onSuccess(i.signInUserSession))})})}else i.getDeviceResponse(t)})},t.changePassword=function(e,t,n,r){if(null==this.signInUserSession||!this.signInUserSession.isValid())return n(new Error("User is not authenticated"),null);this.client.request("ChangePassword",{PreviousPassword:e,ProposedPassword:t,AccessToken:this.signInUserSession.getAccessToken().getJwtToken(),ClientMetadata:r},function(e){return e?n(e,null):n(null,"SUCCESS")})},t.enableMFA=function(e){if(null==this.signInUserSession||!this.signInUserSession.isValid())return e(new Error("User is not authenticated"),null);var t=[];t.push({DeliveryMedium:"SMS",AttributeName:"phone_number"}),this.client.request("SetUserSettings",{MFAOptions:t,AccessToken:this.signInUserSession.getAccessToken().getJwtToken()},function(t){return t?e(t,null):e(null,"SUCCESS")})},t.setUserMfaPreference=function(e,t,n){if(null==this.signInUserSession||!this.signInUserSession.isValid())return n(new Error("User is not authenticated"),null);this.client.request("SetUserMFAPreference",{SMSMfaSettings:e,SoftwareTokenMfaSettings:t,AccessToken:this.signInUserSession.getAccessToken().getJwtToken()},function(e){return e?n(e,null):n(null,"SUCCESS")})},t.disableMFA=function(e){if(null==this.signInUserSession||!this.signInUserSession.isValid())return e(new Error("User is not authenticated"),null);this.client.request("SetUserSettings",{MFAOptions:[],AccessToken:this.signInUserSession.getAccessToken().getJwtToken()},function(t){return t?e(t,null):e(null,"SUCCESS")})},t.deleteUser=function(e,t){var n=this;if(null==this.signInUserSession||!this.signInUserSession.isValid())return e(new Error("User is not authenticated"),null);this.client.request("DeleteUser",{AccessToken:this.signInUserSession.getAccessToken().getJwtToken(),ClientMetadata:t},function(t){return t?e(t,null):(n.clearCachedUser(),e(null,"SUCCESS"))})},t.updateAttributes=function(e,t,n){var r=this;if(null==this.signInUserSession||!this.signInUserSession.isValid())return t(new Error("User is not authenticated"),null);this.client.request("UpdateUserAttributes",{AccessToken:this.signInUserSession.getAccessToken().getJwtToken(),UserAttributes:e,ClientMetadata:n},function(e,n){return e?t(e,null):r.getUserData(function(){return t(null,"SUCCESS",n)},{bypassCache:!0})})},t.getUserAttributes=function(e){if(null==this.signInUserSession||!this.signInUserSession.isValid())return e(new Error("User is not authenticated"),null);this.client.request("GetUser",{AccessToken:this.signInUserSession.getAccessToken().getJwtToken()},function(t,n){if(t)return e(t,null);for(var r=[],i=0;i<n.UserAttributes.length;i++){var s={Name:n.UserAttributes[i].Name,Value:n.UserAttributes[i].Value},o=new V(s);r.push(o)}return e(null,r)})},t.getMFAOptions=function(e){if(null==this.signInUserSession||!this.signInUserSession.isValid())return e(new Error("User is not authenticated"),null);this.client.request("GetUser",{AccessToken:this.signInUserSession.getAccessToken().getJwtToken()},function(t,n){return t?e(t,null):e(null,n.MFAOptions)})},t.createGetUserRequest=function(){return this.client.promisifyRequest("GetUser",{AccessToken:this.signInUserSession.getAccessToken().getJwtToken()})},t.refreshSessionIfPossible=function(e){var t=this;return void 0===e&&(e={}),new Promise(function(n){var r=t.signInUserSession.getRefreshToken();r&&r.getToken()?t.refreshSession(r,n,e.clientMetadata):n()})},t.getUserData=function(e,t){var n=this;if(null==this.signInUserSession||!this.signInUserSession.isValid())return this.clearCachedUserData(),e(new Error("User is not authenticated"),null);var r=this.getUserDataFromCache();if(r)if(this.isFetchUserDataAndTokenRequired(t))this.fetchUserData().then(function(e){return n.refreshSessionIfPossible(t).then(function(){return e})}).then(function(t){return e(null,t)}).catch(e);else try{return void e(null,JSON.parse(r))}catch(t){return this.clearCachedUserData(),void e(t,null)}else this.fetchUserData().then(function(t){e(null,t)}).catch(e)},t.getUserDataFromCache=function(){return this.storage.getItem(this.userDataKey)},t.isFetchUserDataAndTokenRequired=function(e){var t=(e||{}).bypassCache;return void 0!==t&&t},t.fetchUserData=function(){var e=this;return this.createGetUserRequest().then(function(t){return e.cacheUserData(t),t})},t.deleteAttributes=function(e,t){var n=this;if(null==this.signInUserSession||!this.signInUserSession.isValid())return t(new Error("User is not authenticated"),null);this.client.request("DeleteUserAttributes",{UserAttributeNames:e,AccessToken:this.signInUserSession.getAccessToken().getJwtToken()},function(e){return e?t(e,null):n.getUserData(function(){return t(null,"SUCCESS")},{bypassCache:!0})})},t.resendConfirmationCode=function(e,t){var n={ClientId:this.pool.getClientId(),Username:this.username,ClientMetadata:t};this.client.request("ResendConfirmationCode",n,function(t,n){return t?e(t,null):e(null,n)})},t.getSession=function(e,t){if(void 0===t&&(t={}),null==this.username)return e(new Error("Username is null. Cannot retrieve a new session"),null);if(null!=this.signInUserSession&&this.signInUserSession.isValid())return e(null,this.signInUserSession);var n="CognitoIdentityServiceProvider."+this.pool.getClientId()+"."+this.username,r=n+".idToken",i=n+".accessToken",s=n+".refreshToken",o=n+".clockDrift";if(this.storage.getItem(r)){var a=new U({IdToken:this.storage.getItem(r)}),c=new R({AccessToken:this.storage.getItem(i)}),u=new P({RefreshToken:this.storage.getItem(s)}),l=parseInt(this.storage.getItem(o),0)||0,h=new N({IdToken:a,AccessToken:c,RefreshToken:u,ClockDrift:l});if(h.isValid())return this.signInUserSession=h,e(null,this.signInUserSession);if(!u.getToken())return e(new Error("Cannot retrieve a new session. Please authenticate."),null);this.refreshSession(u,e,t.clientMetadata)}else e(new Error("Local storage is missing an ID Token, Please authenticate"),null)},t.refreshSession=function(e,t,n){var r=this,i=this.pool.wrapRefreshSessionCallback?this.pool.wrapRefreshSessionCallback(t):t,s={};s.REFRESH_TOKEN=e.getToken();var o="CognitoIdentityServiceProvider."+this.pool.getClientId(),a=o+".LastAuthUser";if(this.storage.getItem(a)){this.username=this.storage.getItem(a);var c=o+"."+this.username+".deviceKey";this.deviceKey=this.storage.getItem(c),s.DEVICE_KEY=this.deviceKey}var u={ClientId:this.pool.getClientId(),AuthFlow:"REFRESH_TOKEN_AUTH",AuthParameters:s,ClientMetadata:n};this.getUserContextData()&&(u.UserContextData=this.getUserContextData()),this.client.requestWithRetry("InitiateAuth",u,function(t,n){if(t)return"NotAuthorizedException"===t.code&&r.clearCachedUser(),i(t,null);if(n){var s=n.AuthenticationResult;return Object.prototype.hasOwnProperty.call(s,"RefreshToken")||(s.RefreshToken=e.getToken()),r.signInUserSession=r.getCognitoUserSession(s),r.cacheTokens(),i(null,r.signInUserSession)}})},t.cacheTokens=function(){var e="CognitoIdentityServiceProvider."+this.pool.getClientId(),t=e+"."+this.username+".idToken",n=e+"."+this.username+".accessToken",r=e+"."+this.username+".refreshToken",i=e+"."+this.username+".clockDrift",s=e+".LastAuthUser";this.storage.setItem(t,this.signInUserSession.getIdToken().getJwtToken()),this.storage.setItem(n,this.signInUserSession.getAccessToken().getJwtToken()),this.storage.setItem(r,this.signInUserSession.getRefreshToken().getToken()),this.storage.setItem(i,""+this.signInUserSession.getClockDrift()),this.storage.setItem(s,this.username)},t.cacheUserData=function(e){this.storage.setItem(this.userDataKey,JSON.stringify(e))},t.clearCachedUserData=function(){this.storage.removeItem(this.userDataKey)},t.clearCachedUser=function(){this.clearCachedTokens(),this.clearCachedUserData()},t.cacheDeviceKeyAndPassword=function(){var e="CognitoIdentityServiceProvider."+this.pool.getClientId()+"."+this.username,t=e+".deviceKey",n=e+".randomPasswordKey",r=e+".deviceGroupKey";this.storage.setItem(t,this.deviceKey),this.storage.setItem(n,this.randomPassword),this.storage.setItem(r,this.deviceGroupKey)},t.getCachedDeviceKeyAndPassword=function(){var e="CognitoIdentityServiceProvider."+this.pool.getClientId()+"."+this.username,t=e+".deviceKey",n=e+".randomPasswordKey",r=e+".deviceGroupKey";this.storage.getItem(t)&&(this.deviceKey=this.storage.getItem(t),this.randomPassword=this.storage.getItem(n),this.deviceGroupKey=this.storage.getItem(r))},t.clearCachedDeviceKeyAndPassword=function(){var e="CognitoIdentityServiceProvider."+this.pool.getClientId()+"."+this.username,t=e+".deviceKey",n=e+".randomPasswordKey",r=e+".deviceGroupKey";this.storage.removeItem(t),this.storage.removeItem(n),this.storage.removeItem(r)},t.clearCachedTokens=function(){var e="CognitoIdentityServiceProvider."+this.pool.getClientId(),t=e+"."+this.username+".idToken",n=e+"."+this.username+".accessToken",r=e+"."+this.username+".refreshToken",i=e+".LastAuthUser",s=e+"."+this.username+".clockDrift";this.storage.removeItem(t),this.storage.removeItem(n),this.storage.removeItem(r),this.storage.removeItem(i),this.storage.removeItem(s)},t.getCognitoUserSession=function(e){var t=new U(e),n=new R(e),r=new P(e);return new N({IdToken:t,AccessToken:n,RefreshToken:r})},t.forgotPassword=function(e,t){var n={ClientId:this.pool.getClientId(),Username:this.username,ClientMetadata:t};this.getUserContextData()&&(n.UserContextData=this.getUserContextData()),this.client.request("ForgotPassword",n,function(t,n){return t?e.onFailure(t):"function"==typeof e.inputVerificationCode?e.inputVerificationCode(n):e.onSuccess(n)})},t.confirmPassword=function(e,t,n,r){var i={ClientId:this.pool.getClientId(),Username:this.username,ConfirmationCode:e,Password:t,ClientMetadata:r};this.getUserContextData()&&(i.UserContextData=this.getUserContextData()),this.client.request("ConfirmForgotPassword",i,function(e){return e?n.onFailure(e):n.onSuccess("SUCCESS")})},t.getAttributeVerificationCode=function(e,t,n){if(null==this.signInUserSession||!this.signInUserSession.isValid())return t.onFailure(new Error("User is not authenticated"));this.client.request("GetUserAttributeVerificationCode",{AttributeName:e,AccessToken:this.signInUserSession.getAccessToken().getJwtToken(),ClientMetadata:n},function(e,n){return e?t.onFailure(e):"function"==typeof t.inputVerificationCode?t.inputVerificationCode(n):t.onSuccess("SUCCESS")})},t.verifyAttribute=function(e,t,n){if(null==this.signInUserSession||!this.signInUserSession.isValid())return n.onFailure(new Error("User is not authenticated"));this.client.request("VerifyUserAttribute",{AttributeName:e,Code:t,AccessToken:this.signInUserSession.getAccessToken().getJwtToken()},function(e){return e?n.onFailure(e):n.onSuccess("SUCCESS")})},t.getDevice=function(e){if(null==this.signInUserSession||!this.signInUserSession.isValid())return e.onFailure(new Error("User is not authenticated"));this.client.request("GetDevice",{AccessToken:this.signInUserSession.getAccessToken().getJwtToken(),DeviceKey:this.deviceKey},function(t,n){return t?e.onFailure(t):e.onSuccess(n)})},t.forgetSpecificDevice=function(e,t){if(null==this.signInUserSession||!this.signInUserSession.isValid())return t.onFailure(new Error("User is not authenticated"));this.client.request("ForgetDevice",{AccessToken:this.signInUserSession.getAccessToken().getJwtToken(),DeviceKey:e},function(e){return e?t.onFailure(e):t.onSuccess("SUCCESS")})},t.forgetDevice=function(e){var t=this;this.forgetSpecificDevice(this.deviceKey,{onFailure:e.onFailure,onSuccess:function(n){return t.deviceKey=null,t.deviceGroupKey=null,t.randomPassword=null,t.clearCachedDeviceKeyAndPassword(),e.onSuccess(n)}})},t.setDeviceStatusRemembered=function(e){if(null==this.signInUserSession||!this.signInUserSession.isValid())return e.onFailure(new Error("User is not authenticated"));this.client.request("UpdateDeviceStatus",{AccessToken:this.signInUserSession.getAccessToken().getJwtToken(),DeviceKey:this.deviceKey,DeviceRememberedStatus:"remembered"},function(t){return t?e.onFailure(t):e.onSuccess("SUCCESS")})},t.setDeviceStatusNotRemembered=function(e){if(null==this.signInUserSession||!this.signInUserSession.isValid())return e.onFailure(new Error("User is not authenticated"));this.client.request("UpdateDeviceStatus",{AccessToken:this.signInUserSession.getAccessToken().getJwtToken(),DeviceKey:this.deviceKey,DeviceRememberedStatus:"not_remembered"},function(t){return t?e.onFailure(t):e.onSuccess("SUCCESS")})},t.listDevices=function(e,t,n){if(null==this.signInUserSession||!this.signInUserSession.isValid())return n.onFailure(new Error("User is not authenticated"));var r={AccessToken:this.signInUserSession.getAccessToken().getJwtToken(),Limit:e};t&&(r.PaginationToken=t),this.client.request("ListDevices",r,function(e,t){return e?n.onFailure(e):n.onSuccess(t)})},t.globalSignOut=function(e){var t=this;if(null==this.signInUserSession||!this.signInUserSession.isValid())return e.onFailure(new Error("User is not authenticated"));this.client.request("GlobalSignOut",{AccessToken:this.signInUserSession.getAccessToken().getJwtToken()},function(n){return n?e.onFailure(n):(t.clearCachedUser(),e.onSuccess("SUCCESS"))})},t.signOut=function(e){var t=this;e&&"function"==typeof e?this.getSession(function(n,r){if(n)return e(n);t.revokeTokens(function(n){t.cleanClientData(),e(n)})}):this.cleanClientData()},t.revokeTokens=function(e){if(void 0===e&&(e=function(){}),"function"!=typeof e)throw new Error("Invalid revokeTokenCallback. It should be a function.");if(!this.signInUserSession)return e(new Error("User is not authenticated"));if(!this.signInUserSession.getAccessToken())return e(new Error("No Access token available"));var t=this.signInUserSession.getRefreshToken().getToken(),n=this.signInUserSession.getAccessToken();if(this.isSessionRevocable(n)&&t)return this.revokeToken({token:t,callback:e});e()},t.isSessionRevocable=function(e){if(e&&"function"==typeof e.decodePayload)try{return!!e.decodePayload().origin_jti}catch(e){}return!1},t.cleanClientData=function(){this.signInUserSession=null,this.clearCachedUser()},t.revokeToken=function(e){var t=e.token,n=e.callback;this.client.requestWithRetry("RevokeToken",{Token:t,ClientId:this.pool.getClientId()},function(e){if(e)return n(e);n()})},t.sendMFASelectionAnswer=function(e,t){var n=this,r={};r.USERNAME=this.username,r.ANSWER=e;var i={ChallengeName:"SELECT_MFA_TYPE",ChallengeResponses:r,ClientId:this.pool.getClientId(),Session:this.Session};this.getUserContextData()&&(i.UserContextData=this.getUserContextData()),this.client.request("RespondToAuthChallenge",i,function(r,i){return r?t.onFailure(r):(n.Session=i.Session,"SMS_MFA"===e?t.mfaRequired(i.ChallengeName,i.ChallengeParameters):"SOFTWARE_TOKEN_MFA"===e?t.totpRequired(i.ChallengeName,i.ChallengeParameters):void 0)})},t.getUserContextData=function(){return this.pool.getUserContextData(this.username)},t.associateSoftwareToken=function(e){var t=this;null!=this.signInUserSession&&this.signInUserSession.isValid()?this.client.request("AssociateSoftwareToken",{AccessToken:this.signInUserSession.getAccessToken().getJwtToken()},function(t,n){return t?e.onFailure(t):e.associateSecretCode(n.SecretCode)}):this.client.request("AssociateSoftwareToken",{Session:this.Session},function(n,r){return n?e.onFailure(n):(t.Session=r.Session,e.associateSecretCode(r.SecretCode))})},t.verifySoftwareToken=function(e,t,n){var r=this;null!=this.signInUserSession&&this.signInUserSession.isValid()?this.client.request("VerifySoftwareToken",{AccessToken:this.signInUserSession.getAccessToken().getJwtToken(),UserCode:e,FriendlyDeviceName:t},function(e,t){return e?n.onFailure(e):n.onSuccess(t)}):this.client.request("VerifySoftwareToken",{Session:this.Session,UserCode:e,FriendlyDeviceName:t},function(e,t){if(e)return n.onFailure(e);r.Session=t.Session;var i={};i.USERNAME=r.username;var s={ChallengeName:"MFA_SETUP",ClientId:r.pool.getClientId(),ChallengeResponses:i,Session:r.Session};r.getUserContextData()&&(s.UserContextData=r.getUserContextData()),r.client.request("RespondToAuthChallenge",s,function(e,t){return e?n.onFailure(e):(r.signInUserSession=r.getCognitoUserSession(t.AuthenticationResult),r.cacheTokens(),n.onSuccess(r.signInUserSession))})})},e}();function B(){}function K(e){var t="function"==typeof Map?new Map:void 0;return K=function(e){if(null===e||!function(e){try{return-1!==Function.toString.call(e).indexOf("[native code]")}catch(t){return"function"==typeof e}}(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,n)}function n(){return function(e,t,n){if(J())return Reflect.construct.apply(null,arguments);var r=[null];r.push.apply(r,t);var i=new(e.bind.apply(e,r));return n&&H(i,n.prototype),i}(e,arguments,W(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),H(n,e)},K(e)}function J(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(J=function(){return!!e})()}function H(e,t){return H=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},H(e,t)}function W(e){return W=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},W(e)}n(916),B.prototype.userAgent=C;var Q=function(e){function t(t,n,r,i){var s;return(s=e.call(this,t)||this).code=n,s.name=r,s.statusCode=i,s}return r=e,(n=t).prototype=Object.create(r.prototype),n.prototype.constructor=n,H(n,r),t;var n,r}(K(Error)),z=function(){function e(e,t,n){this.endpoint=t||"https://cognito-idp."+e+".amazonaws.com/";var r=(n||{}).credentials;this.fetchOptions=r?{credentials:r}:{}}var t=e.prototype;return t.promisifyRequest=function(e,t){var n=this;return new Promise(function(r,i){n.request(e,t,function(e,t){e?i(new Q(e.message,e.code,e.name,e.statusCode)):r(t)})})},t.requestWithRetry=function(e,t,n){var r,i,s=this;(r=[t],i=5e3,void 0===i&&(i=X),Z(function(t){return new Promise(function(n,r){s.request(e,t,function(e,t){e?r(e):n(t)})})},r,function(e){return function(t){var n=100*Math.pow(2,t)+100*Math.random();return!(n>e)&&n}}(i))).then(function(e){return n(null,e)}).catch(function(e){return n(e)})},t.request=function(e,t,n){var r,i,s,o={"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":"AWSCognitoIdentityProviderService."+e,"X-Amz-User-Agent":(r=B.category?" "+B.category:"",i=B.framework?" framework/"+B.framework:"",""+B.prototype.userAgent+r+i),"Cache-Control":"no-store"},a=Object.assign({},this.fetchOptions,{headers:o,method:"POST",mode:"cors",body:JSON.stringify(t)});fetch(this.endpoint,a).then(function(e){return s=e,e},function(e){if(e instanceof TypeError)throw new Error("Network error");throw e}).then(function(e){return e.json().catch(function(){return{}})}).then(function(e){if(s.ok)return n(null,e);var t=(e.__type||e.code).split("#").pop(),r=new Error(e.message||e.Message||null);return r.name=t,r.code=t,n(r)}).catch(function(e){if(s&&s.headers&&s.headers.get("x-amzn-errortype"))try{var t=s.headers.get("x-amzn-errortype").split(":")[0],r=new Error(s.status?s.status.toString():null);return r.code=t,r.name=t,r.statusCode=s.status,n(r)}catch(t){return n(e)}else e instanceof Error&&"Network error"===e.message&&(e.code="NetworkError");return n(e)})},e}(),G={debug:function(){}},Y=function(e){return e&&e.nonRetryable};function Z(e,t,n,r){if(void 0===r&&(r=1),"function"!=typeof e)throw Error("functionToRetry must be a function");return G.debug(e.name+" attempt #"+r+" with args: "+JSON.stringify(t)),e.apply(void 0,t).catch(function(i){if(G.debug("error on "+e.name,i),Y(i))throw G.debug(e.name+" non retryable error",i),i;var s=n(r,t,i);if(G.debug(e.name+" retrying in "+s+" ms"),!1!==s)return new Promise(function(e){return setTimeout(e,s)}).then(function(){return Z(e,t,n,r+1)});throw i})}var X=3e5,ee=function(){function e(e,t){var n=e||{},r=n.UserPoolId,i=n.ClientId,s=n.endpoint,o=n.fetchOptions,a=n.AdvancedSecurityDataCollectionFlag;if(!r||!i)throw new Error("Both UserPoolId and ClientId are required.");if(r.length>55||!/^[\w-]+_[0-9a-zA-Z]+$/.test(r))throw new Error("Invalid UserPoolId format.");var c=r.split("_")[0];this.userPoolId=r,this.clientId=i,this.client=new z(c,s,o),this.advancedSecurityDataCollectionFlag=!1!==a,this.storage=e.Storage||(new q).getStorage(),t&&(this.wrapRefreshSessionCallback=t)}var t=e.prototype;return t.getUserPoolId=function(){return this.userPoolId},t.getUserPoolName=function(){return this.getUserPoolId().split("_")[1]},t.getClientId=function(){return this.clientId},t.signUp=function(e,t,n,r,i,s){var o=this,a={ClientId:this.clientId,Username:e,Password:t,UserAttributes:n,ValidationData:r,ClientMetadata:s};this.getUserContextData(e)&&(a.UserContextData=this.getUserContextData(e)),this.client.request("SignUp",a,function(t,n){if(t)return i(t,null);var r={Username:e,Pool:o,Storage:o.storage},s={user:new j(r),userConfirmed:n.UserConfirmed,userSub:n.UserSub,codeDeliveryDetails:n.CodeDeliveryDetails};return i(null,s)})},t.getCurrentUser=function(){var e="CognitoIdentityServiceProvider."+this.clientId+".LastAuthUser",t=this.storage.getItem(e);if(t){var n={Username:t,Pool:this,Storage:this.storage};return new j(n)}return null},t.getUserContextData=function(e){if("undefined"!=typeof AmazonCognitoAdvancedSecurityData){var t=AmazonCognitoAdvancedSecurityData;if(this.advancedSecurityDataCollectionFlag){var n=t.getData(e,this.userPoolId,this.clientId);if(n)return{EncodedData:n}}return{}}},e}();n(596);class te extends Error{constructor(e,t){if(Array.isArray(e)&&e.length<=2){let n=e[1];if(e.length>2)for(let t=2;t<e.length&&"string"==typeof e[t];t++)n+=e[t];super((n||"Something went wrong.").trim()),this.name=t?.name||"SKAPI",this.code=t?.code||e[0]||"ERROR",t?.cause&&(this.cause=t.cause)}else super((e?.message||("string"==typeof e?e:"Something went wrong.")).trim()),"string"==typeof e?(this.name=t?.name||"SKAPI",this.code=t?.code||"ERROR",t?.cause&&(this.cause=t.cause)):e instanceof Error?(this.cause=e,this.name=e.name,e.hasOwnProperty("code")&&(this.code=e.code)):"object"==typeof e&&e?.code&&e?.message&&(this.name=t?.name||"SKAPI",this.code=t?.code||"ERROR",this.cause=e?.cause)}}const ne="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",re=BigInt(62);class ie{static hash(e){"string"!=typeof e&&(console.warn("coercing non-string value to empty string"),e="");const t=ie.sb(e);let n,r,i,s,o=1732584193,a=-271733879,c=-1732584194,u=271733878;for(let e=0;e<t.length;e+=16)n=o,r=a,i=c,s=u,o=ie.ff(o,a,c,u,t[e],7,-680876936),u=ie.ff(u,o,a,c,t[e+1],12,-389564586),c=ie.ff(c,u,o,a,t[e+2],17,606105819),a=ie.ff(a,c,u,o,t[e+3],22,-1044525330),o=ie.ff(o,a,c,u,t[e+4],7,-176418897),u=ie.ff(u,o,a,c,t[e+5],12,1200080426),c=ie.ff(c,u,o,a,t[e+6],17,-1473231341),a=ie.ff(a,c,u,o,t[e+7],22,-45705983),o=ie.ff(o,a,c,u,t[e+8],7,1770035416),u=ie.ff(u,o,a,c,t[e+9],12,-1958414417),c=ie.ff(c,u,o,a,t[e+10],17,-42063),a=ie.ff(a,c,u,o,t[e+11],22,-1990404162),o=ie.ff(o,a,c,u,t[e+12],7,1804603682),u=ie.ff(u,o,a,c,t[e+13],12,-40341101),c=ie.ff(c,u,o,a,t[e+14],17,-1502002290),a=ie.ff(a,c,u,o,t[e+15],22,1236535329),o=ie.gg(o,a,c,u,t[e+1],5,-165796510),u=ie.gg(u,o,a,c,t[e+6],9,-1069501632),c=ie.gg(c,u,o,a,t[e+11],14,643717713),a=ie.gg(a,c,u,o,t[e],20,-373897302),o=ie.gg(o,a,c,u,t[e+5],5,-701558691),u=ie.gg(u,o,a,c,t[e+10],9,38016083),c=ie.gg(c,u,o,a,t[e+15],14,-660478335),a=ie.gg(a,c,u,o,t[e+4],20,-405537848),o=ie.gg(o,a,c,u,t[e+9],5,568446438),u=ie.gg(u,o,a,c,t[e+14],9,-1019803690),c=ie.gg(c,u,o,a,t[e+3],14,-187363961),a=ie.gg(a,c,u,o,t[e+8],20,1163531501),o=ie.gg(o,a,c,u,t[e+13],5,-1444681467),u=ie.gg(u,o,a,c,t[e+2],9,-51403784),c=ie.gg(c,u,o,a,t[e+7],14,1735328473),a=ie.gg(a,c,u,o,t[e+12],20,-1926607734),o=ie.hh(o,a,c,u,t[e+5],4,-378558),u=ie.hh(u,o,a,c,t[e+8],11,-2022574463),c=ie.hh(c,u,o,a,t[e+11],16,1839030562),a=ie.hh(a,c,u,o,t[e+14],23,-35309556),o=ie.hh(o,a,c,u,t[e+1],4,-1530992060),u=ie.hh(u,o,a,c,t[e+4],11,1272893353),c=ie.hh(c,u,o,a,t[e+7],16,-155497632),a=ie.hh(a,c,u,o,t[e+10],23,-1094730640),o=ie.hh(o,a,c,u,t[e+13],4,681279174),u=ie.hh(u,o,a,c,t[e],11,-358537222),c=ie.hh(c,u,o,a,t[e+3],16,-722521979),a=ie.hh(a,c,u,o,t[e+6],23,76029189),o=ie.hh(o,a,c,u,t[e+9],4,-640364487),u=ie.hh(u,o,a,c,t[e+12],11,-421815835),c=ie.hh(c,u,o,a,t[e+15],16,530742520),a=ie.hh(a,c,u,o,t[e+2],23,-995338651),o=ie.ii(o,a,c,u,t[e],6,-198630844),u=ie.ii(u,o,a,c,t[e+7],10,1126891415),c=ie.ii(c,u,o,a,t[e+14],15,-1416354905),a=ie.ii(a,c,u,o,t[e+5],21,-57434055),o=ie.ii(o,a,c,u,t[e+12],6,1700485571),u=ie.ii(u,o,a,c,t[e+3],10,-1894986606),c=ie.ii(c,u,o,a,t[e+10],15,-1051523),a=ie.ii(a,c,u,o,t[e+1],21,-2054922799),o=ie.ii(o,a,c,u,t[e+8],6,1873313359),u=ie.ii(u,o,a,c,t[e+15],10,-30611744),c=ie.ii(c,u,o,a,t[e+6],15,-1560198380),a=ie.ii(a,c,u,o,t[e+13],21,1309151649),o=ie.ii(o,a,c,u,t[e+4],6,-145523070),u=ie.ii(u,o,a,c,t[e+11],10,-1120210379),c=ie.ii(c,u,o,a,t[e+2],15,718787259),a=ie.ii(a,c,u,o,t[e+9],21,-343485551),o=ie.ad(o,n),a=ie.ad(a,r),c=ie.ad(c,i),u=ie.ad(u,s);return ie.rh(o)+ie.rh(a)+ie.rh(c)+ie.rh(u)}static rh(e){let t="";for(let n=0;n<=3;n++)t+=ie.alphabet.charAt(e>>8*n+4&15)+ie.alphabet.charAt(e>>8*n&15);return t}static ad(e,t){const n=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(n>>16)<<16|65535&n}static rl(e,t){return e<<t|e>>>32-t}static cm(e,t,n,r,i,s){return ie.ad(ie.rl(ie.ad(ie.ad(t,e),ie.ad(r,s)),i),n)}static ff(e,t,n,r,i,s,o){return ie.cm(t&n|~t&r,e,t,i,s,o)}static gg(e,t,n,r,i,s,o){return ie.cm(t&r|n&~r,e,t,i,s,o)}static hh(e,t,n,r,i,s,o){return ie.cm(t^n^r,e,t,i,s,o)}static ii(e,t,n,r,i,s,o){return ie.cm(n^(t|~r),e,t,i,s,o)}static sb(e){let t;const n=1+(e.length+8>>6),r=new Array(16*n);for(t=0;t<16*n;t++)r[t]=0;for(t=0;t<e.length;t++)r[t>>2]|=e.charCodeAt(t)<<t%4*8;return r[t>>2]|=128<<t%4*8,r[16*n-2]=8*e.length,r}}function se(e){if(0===e)return ne[0];let t="";for(;e>0;)t=ne[e%62]+t,e=Math.floor(e/62);return t}function oe(e){return e.split("").reverse().reduce((e,t,n)=>e+ne.indexOf(t)*62**n,0)}function ae(e=6){let t="";let n=0;for(;n<e;)t+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".charAt(Math.floor(62*Math.random())),n+=1;return t}function ce(){return"undefined"==typeof window||!!window?._runningInNodeJS}function ue(){return!ce()&&"undefined"!=typeof document&&"function"==typeof document.createElement}ie.alphabet="0123456789abcdef";const le=ue(),he="undefined"!=typeof SubmitEvent,de="undefined"!=typeof HTMLFormElement;function fe(e,t,n){let r={},i=[];function s(e){let t;try{t=JSON.stringify(e)}catch(e){throw new te("Invalid data type.",{code:"INVALID_REQUEST"})}return new Blob([t]).size}function o(e,r,i){if(t?.ignoreEmpty&&""===i)return;if(t?.nullIfEmpty&&""===i&&(i=null),"function"==typeof n){let e=n(r,i);void 0!==e&&(i=e)}let s=r.split("[").map(e=>{let t=e.replace("]",""),n=Number(t);return isNaN(n)||t.includes(".")?('"'===t[0]&&'"'===t[t.length-1]||"'"===t[0]&&"'"===t[t.length-1])&&(t=t.replace(/"/g,"").replace(/'/g,"")):t=n,t}),o=e;if("number"==typeof s[0])throw new te("Form key cannot start with an array index.",{code:"INVALID_REQUEST"});for(let e=0;e<s.length;e++){let t=s[e];if(e<s.length-1){if(void 0===o[t]){let n=s[e+1];o[t]="number"==typeof n?[]:{}}o=o[t]}else void 0===o[t]?o[t]=i:Array.isArray(o[t])?o[t].push(i):o[t]=[o[t],i]}}function a(e,t,n){if(n instanceof File)e.push({name:t,file:n});else if(n instanceof FileList&&n&&n.length>0)for(let r=0;r<=n.length-1;r++){let i=n.item(r);i&&e.push({name:t,file:i})}}let c=e=>{e.name&&("number"===e.type?e.value&&o(r,e.name,Number(e.value)):"checkbox"===e.type||"radio"===e.type?e.checked?""===e.value&&"checkbox"===e.type||"on"===e.value||"true"===e.value?o(r,e.name,!0):"false"===e.value?o(r,e.name,!1):e.value&&o(r,e.name,e.value):"checkbox"===e.type&&(""===e.value||"on"===e.value||"true"===e.value?o(r,e.name,!1):"false"===e.value&&o(r,e.name,!0)):"file"===e.type?e.files&&e.files.length>0&&a(i,e.name,e.files):o(r,e.name,e.value))};if(le&&(e instanceof HTMLInputElement||e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement)){if(c(e),s(r)>2097152)throw new te("Data should not exceed 2MB",{code:"INVALID_REQUEST"});return{data:r,files:i}}if(le&&e instanceof FormData){for(let t of e.entries()){let e=t[0],n=t[1];if(n instanceof File||n instanceof FileList)a(i,e,n);else if(n instanceof Blob){let t=n;if("application/json"===t.type)try{let n=JSON.parse(t.text());o(r,e,n)}catch(n){o(r,e,t)}}else o(r,e,n)}if(s(r)>2097152)throw new te("Data should not exceed 2MB",{code:"INVALID_REQUEST"});return{data:r,files:i}}if(le&&he&&e instanceof SubmitEvent&&(e=e.target),le&&de&&e instanceof HTMLFormElement){let t=e.querySelectorAll("input"),n=e.querySelectorAll("select"),a=e.querySelectorAll("textarea");for(let e=0;e<n.length;e++){let t=n[e];t.name&&o(r,t.name,t.value)}for(let e=0;e<a.length;e++){let t=a[e];t.name&&o(r,t.name,t.value)}for(let e=0;e<t.length;e++)c(t[e]);if(s(r)>2097152)throw new te("Data should not exceed 2MB",{code:"INVALID_REQUEST"});return{data:r,files:i}}if(s(e)>2097152)throw new te("Data should not exceed 2MB",{code:"INVALID_REQUEST"});return{data:e,files:i}}function pe(e){let t={};for(let n in e){let r=e[n],i={auth_time:"log",sub:"user_id"};if(!["aud","cognito:username","event_id","exp","iat","iss","jti","origin_jti","secret_key","token_use"].includes(n))if(i[n])t[i[n]]=r;else if(n.includes("custom:"))t[n.replace("custom:","")]=r;else if("address"===n){let e=r;if(e&&"object"==typeof e&&Object.keys(e).length){if(e?.formatted)try{t[n]=JSON.parse(e.formatted)}catch(r){t[n]=e.formatted}}else t[n]=e}else t[n]=r}for(let e of["address_public","birthdate_public","email_public","gender_public","phone_number_public","access_group"])e.includes("_public")?t.hasOwnProperty(e.split("_")[0])?t[e]=!!t.hasOwnProperty(e)&&!!Number(t[e]):delete t[e]:t[e]=t.hasOwnProperty(e)?Number(t[e]):0;for(let e of["email","phone_number"])t.hasOwnProperty(e)?t[e+"_verified"]=!0===t[e+"_verified"]:delete t[e+"_verified"];return t}function ge(e){if(7===(e=function(e){const t=String(e);if(!t.startsWith("s1_"))return t;const n=function(e,t=!1){const n=String(e).replace(/-/g,"+").replace(/_/g,"/"),r=n.length%4?"=".repeat(4-n.length%4):"",i=Buffer.from(n+r,"base64");return t?JSON.parse(i.toString("utf8")):i}(t.slice(3));if(n.length<21)throw new Error("INVALID_PARAMETER: Corrupt compressed token.");const r=n[0];if(1!==r)throw new Error(`INVALID_PARAMETER: Unsupported token version: ${r}`);const i=n[1],s=n[2],o=5+n[3],a=o+n[4];if(n.length!==a+16)throw new Error("INVALID_PARAMETER: Corrupt compressed token length.");return`${ye(be(n.subarray(5,o)),i)}-${ye(be(n.subarray(o,a)),s)}-${function(e){const t=Buffer.from(e).toString("hex");return[t.slice(0,8),t.slice(8,12),t.slice(12,16),t.slice(16,20),t.slice(20)].join("-")}(n.subarray(a,a+16))}`}(e)).split("-").length){const t=e.split("-");let n,r;try{n=["us31","us72","ap51","ap22","ap41","eu71","ap21","us32","us71","af51","ap31","ap43","ap23","ap42","ca01","eu01","eu72","eu51","eu73","eu11","me51","sa31"][oe(t[1][0])],r=t.slice(2).join("-")}catch(e){throw new Error("INVALID_PARAMETER: Service ID is invalid.")}if(!n)throw new Error("INVALID_PARAMETER: Service ID is invalid.");return{service:n+t[0]+t[1].slice(1),owner:r}}return{service:e,owner:""}}function _e(e,t){const n=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f","g","h","i","j","k","l"][["us31","us72","ap51","ap22","ap41","eu71","ap21","us32","us71","af51","ap31","ap43","ap23","ap42","ca01","eu01","eu72","eu51","eu73","eu11","me51","sa31"].indexOf(e.slice(0,4))];return function(e){const t=String(e).match(/^([0-9A-Za-z]+)-([0-9A-Za-z]+)-([0-9a-fA-F-]{36})$/);if(!t)throw new Error("INVALID_PARAMETER: Input must match <base62>-<base62>-<uuid>.");const[,n,r,i]=t,s=me(n),o=me(r),a=we(s),c=we(o),u=function(e){const t=String(e).replace(/-/g,"");if(!/^[0-9a-fA-F]{32}$/.test(t))throw new Error("INVALID_PARAMETER: Invalid UUID format.");return Buffer.from(t,"hex")}(i);if(n.length>255||r.length>255||a.length>255||c.length>255)throw new Error("INVALID_PARAMETER: Input parts are too long to encode.");return`s1_${function(e){if(Buffer)return Buffer.from(e).toString("base64");let t="";const n=new Uint8Array(e);for(let e=0;e<n.length;e+=32768){const r=n.subarray(e,e+32768);t+=String.fromCharCode.apply(null,Array.from(r))}if("function"==typeof btoa)return btoa(t);throw new Error("No base64 encoder available in this environment.")}(Buffer.concat([Buffer.from([1,n.length,r.length,a.length,c.length]),a,c,u])).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}`}(`${e.slice(4,-4)}-${n}${e.slice(-4)}-${t}`)}function me(e){let t=0n;for(const n of e){const e=ne.indexOf(n);if(e<0)throw new Error(`INVALID_PARAMETER: Invalid base62 character: ${n}`);t=t*re+BigInt(e)}return t}function ye(e,t=1){if(e<0n)throw new Error("INVALID_PARAMETER: Negative values are not supported.");if(0n===e)return"0".repeat(Math.max(1,t));let n="",r=e;for(;r>0n;){const e=Number(r%re);n=ne[e]+n,r/=re}return n.length<t&&(n="0".repeat(t-n.length)+n),n}function we(e){if(0n===e)return Buffer.from([0]);const t=[];let n=e;for(;n>0n;)t.push(Number(0xffn&n)),n>>=8n;return t.reverse(),Buffer.from(t)}function be(e){let t=0n;for(const n of e)t=(t<<8n)+BigInt(n);return t}function Ae(e,t,n=[],r=null){function i(e){return e&&"object"==typeof e&&!Array.isArray(e)&&Object.keys(e).length}function s(e){return Array.isArray(e)&&e.length}if(null===r&&!i(t))throw'Argument "struct" is required.';let o=null!==r?` in key "${r}" is invalid.`:". Parameter should be type <object>.";if(s(t)){let i="";t.forEach(e=>{["string","number","boolean","object","array"].includes(e)?i+=`Type<${e}>, `:"function"!=typeof e&&(i+=JSON.stringify(e,null,2)+", ")}),i=i?" Should be: "+i.slice(0,-2):"";let s,a=!1,c="";for(let i of t)try{s=Ae(e,i,n,r),a=!0;break}catch(e){c="function"==typeof i?e?.message||e:"",a=!1}if(!a)throw c||`Invalid type "${typeof e}"${o}${i}.`;return s}if(i(e)){if(i(t))for(let i in t){let o=(null===r?"":r)+(null!==r?"["+i+"]":i);if(!e.hasOwnProperty(i)){if(n.includes(o))throw`Key "${o}" is required.`;s(t[i])&&"function"==typeof t[i][t[i].length-1]&&(e[i]=t[i][t[i].length-1]())}}if("object"===t)return e;if("function"==typeof t)return t(e);for(let i in e){let o=(null===r?"":r)+(null!==r?"["+i+"]":i);if(s(t)||t.hasOwnProperty(i))if(s(e[i])){if("array"===t[i])continue;if("function"==typeof t[i]){e[i]=t[i](e[i]);continue}for(let r=0;r<e[i].length;r++)e[i][r]=Ae(e[i][r],t[i],n,o+`[${r}]`)}else e[i]=Ae(e[i],t[i],n,o)}return e}if("function"==typeof t)return t(e);if("array"===t&&Array.isArray(e)||t===typeof e||e===t)return e;if(null==e||(a=e)&&"object"==typeof a&&!Array.isArray(a)&&!Object.keys(a).length)return e;var a;throw`Invalid type "${typeof e}"${o} Should be: ${["string","number","boolean","object","array"].includes(t)?`Type<${t}>`:JSON.stringify(t,null,2)}`}const ve={UserId:function(e,t="User ID"){if(!e)throw new te(`${t} is empty.`,{code:"INVALID_PARAMETER"});if("string"!=typeof e)throw new te(`${t} should be type: string.`,{code:"INVALID_PARAMETER"});if(!e.match(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i))throw new te(`${t} is invalid.`,{code:"INVALID_PARAMETER"});return e},PhoneNumber:function(e){if(e&&("string"!=typeof e||"+"!==e.charAt(0)||isNaN(Number(e.substring(1)))))throw new te('"phone_number" is invalid. The format should be "+00123456789". Type: string.',{code:"INVALID_PARAMETER"});return e||""},Birthdate:function(e){if(e){if("string"!=typeof e)throw new te('"birthdate" is invalid. The format should be "yyyy-mm-dd". Type: string.',{code:"INVALID_PARAMETER"});{let t=new RegExp(/([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))/);if(10!==e.length||3!==e.split("-").length||!t.test(e))throw new te('"birthdate" is invalid. The format should be "yyyy-mm-dd". Type: string.',{code:"INVALID_PARAMETER"})}}return e||""},Password:function(e){if(!e)throw new te('"password" is required.',{code:"INVALID_PARAMETER"});if("string"!=typeof e)throw new te('"password" should be type: string.',{code:"INVALID_PARAMETER"});if(e.length<6)throw new te('"password" should be at least 6 characters.',{code:"INVALID_PARAMETER"});if(e.length>60)throw new te('"password" can be up to 60 characters max.',{code:"INVALID_PARAMETER"});return e},Email:function(e,t="email"){if(!e)throw new te(`"${t}" is required.`,{code:"INVALID_PARAMETER"});if("string"!=typeof e)throw new te(`"${t}"should be type: string.`,{code:"INVALID_PARAMETER"});if(e.length<5)throw new te(`"${t}" should be at least 5 characters.`,{code:"INVALID_PARAMETER"});if(/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/.test(e)&&(e=e.trim()).split("@")[1].split(".").length>=2)return e.toLowerCase();throw new te(`"${e}" is an invalid email.`,{code:"INVALID_PARAMETER"})},Url:function(e){const t="undefined"!=typeof window,n=(()=>{let e=t&&window.location.origin||null;return e&&"/"===e.slice(-1)&&(e=e.slice(0,-1)),e})();let r=e=>{if("string"==typeof e){if("*"===e)return"*";{let r,i=e.trim();if("/"===i[0]&&n){if("file:"===n.slice(0,5))throw new te(`"${e}" is an invalid url. Relative URL does not work on local file system. Use full URL string.`,{code:"INVALID_PARAMETER"});i=n+i}else if("."===i[0]&&n){if("file:"===n.slice(0,5))throw new te(`"${e}" is an invalid url. Relative URL does not work on local file system. Use full URL string.`,{code:"INVALID_PARAMETER"});let r=t?window.location.href.split("?")[0]:"";"/"!==r.slice(-1)&&(r+="/"),i=r+i.slice(1)}try{r=new URL(i)}catch(t){throw new te(`"${e}" is an invalid url.`,{code:"INVALID_PARAMETER"})}if(r.protocol)return r.href}}throw new te(`"${e}" is an invalid url.`,{code:"INVALID_PARAMETER"})};return Array.isArray(e)?e.map(e=>r(e)):r(e)},specialChars:function(e,t="parameter",n=!1,r=!1){let i=e=>{if("string"!=typeof e)throw new te(`${t} should be type: <string | string[]>.`,{code:"INVALID_PARAMETER"});if(!r&&e.includes(" "))throw new te(`${t} should not have whitespace.`,{code:"INVALID_PARAMETER"});if(!n&&e.includes("."))throw new te(`${t} should not have periods.`,{code:"INVALID_PARAMETER"});if(/[!#$%&*{};'"|<>\/~]/.test(e))throw new te(`${t} should not have special characters. Allowed special characters are: [ \\ ] ^ _ \` : ; < = > ? @ ( ) + , -`,{code:"INVALID_PARAMETER"})};if(Array.isArray(e))for(let t of e)i(t);else i(e);return e},Params:function(e,t,n=[],r){let i=fe(e,r).data;t.service="string",t.owner="string";let s={};for(let e in t)if(i&&"object"==typeof i&&!Array.isArray(i)&&i.hasOwnProperty(e))if("function"==typeof i[e])s[e]=i[e];else try{s[e]=JSON.parse(JSON.stringify(i[e]))}catch(t){s[e]=i[e]}try{return Ae(s,t,n)}catch(e){throw new te(e,{code:"INVALID_PARAMETER"})}},checkParams:Ae};let Ee=null;function Se(e){let t={tkid:"ticket_id",cond:"condition",stmp:"timestamp",actn:"action",cnt:"count",ttl:"time_to_live",plch:"placeholder",hash:"hash",desc:"description",pmc:"limit_per_user"},n={};for(let r in e)if("tkid"===r){let t=e[r].split("#");if(1===t.length){n.ticket_id=t[0];continue}n.ticket_id=t[1],n.consume_id=t[2],n.user_id=t[3];let i=t[2].slice(-4);if(n.is_test=":CHK"===i,!e.stmp){let e=t[2].slice(0,-4);/^[0-9]+$/.test(e)?n.timestamp=parseInt(e,10):n.timestamp=oe(t[2].slice(0,-4))}}else t[r]?n[t[r]]=e[r]:n[r]=e[r];return n}async function Ie(e){if(!e.ticket_id)throw new te("Ticket ID is required.",{code:"INVALID_PARAMETER"});if(!e.method)throw new te('Method is required. Should be either "GET" or "POST"',{code:"INVALID_PARAMETER"});let t=e.ticket_id;return await this.__connection,Se(await ft.bind(this)(`https://${this.service.slice(0,4)}.${this.customApiDomain}/auth/consume/${this.service}/${this.owner}/${t}`,e?.data||{},{method:e.method,auth:!!e?.auth}))}async function Te(e,t){await this.__connection;let n=await ft.bind(this)("ticket",Object.assign({exec:"list"},e||{}),{auth:!0,fetchOptions:t});return n.list=n.list.map(Se),n}async function Re(e,t){await this.__connection;let n=await ft.bind(this)("ticket",Object.assign({exec:"consumed"},e||{}),{auth:!0,fetchOptions:t});return n.list=n.list.map(Se),n}async function De(e){return ft.bind(this)("register-ticket",Object.assign({exec:"reg"},e),{auth:!0})}async function Ue(e){return ft.bind(this)("register-ticket",Object.assign({exec:"unreg"},e),{auth:!0})}async function Pe(){if(await this.__connection,this.session){const e=Math.floor(Date.now()/1e3),t=this.session.getIdToken().getExpiration();if(t<e){this.log("request:requesting new token",null);try{await ke.bind(this)().getSession({refreshToken:!0}),this.log("request:received new tokens",{exp:this.session?.idToken?.payload?.exp,currentTime:e,expiresIn:t-e,token:this.session?.accessToken?.jwtToken,refreshToken:this.session?.refreshToken?.token})}catch(e){throw this.log("request:new token error",e),new te("User login is required.",{code:"INVALID_REQUEST"})}}else this.log("request:tokens",{exp:this.session.idToken.payload.exp,currentTime:e,expiresIn:t-e,token:this.session.accessToken.jwtToken,refreshToken:this.session.refreshToken.token});return this.session?.idToken?.jwtToken}throw this.log("request:no session",null),xe.bind(this)(),new te("User login is required.",{code:"INVALID_REQUEST"})}function Ce(e,t){return new Promise((n,r)=>{t.refreshSession(e.getRefreshToken(),(e,t)=>{this.log("getSession:refreshSessionCallback",{refreshErr:e,refreshedSession:t}),e?(xe.bind(this)(),r(e)):t.isValid()?n(t):(xe.bind(this)(),r(new te("Invalid session.",{code:"INVALID_REQUEST"})))})})}function ke(){if(!this.userPool)throw new te("User pool is missing",{code:"INVALID_REQUEST"});const e=()=>{let e=pe(Ee.getSignInUserSession().getIdToken().payload||null);return this.log("normalized user attribute",e),this.__user=e,e},t=async t=>new Promise((n,r)=>{this.log("getSession:option",t);let{refreshToken:i=!1,skipUserUpdateEventTrigger:s=!1}=t||{};if(i&&s&&(s=!1),Ee=this.userPool.getCurrentUser(),!Ee)return this.log("getSession:cognitoUser",Ee),xe.bind(this)(),void r(null);let o=t=>{let n=t.getIdToken().payload;if(this.log("getSession:respond:sessionAttribute",n),n["custom:service"]!==this.service)throw this.log("getSession:respond","invalid service, signing out"),xe.bind(this)(),new te("Invalid session.",{code:"INVALID_REQUEST"});return this.session=t,e(),s||this._runOnUserUpdateListeners(this.user),this.session};Ee.getSession((e,t)=>{if(this.log("getSession:getSessionCallback",{err:e,session:t}),!t)return xe.bind(this)(),void r(new te("Current session does not exist.",{code:"INVALID_REQUEST"}));if(e)return void Ce.bind(this)(t,Ee).then(e=>n(o(e))).catch(r);const s=Math.floor(Date.now()/1e3),a=t.getIdToken(),c=a.getExpiration(),u=c<s;if(this.log("getSession:currentTime",s),this.log("getSession:idTokenExp",c),this.log("getSession:isExpired",u),this.log("getSession:existingBearerToken",this.bearerToken),this.bearerToken=a.getJwtToken(),u||i||!t.isValid())Ce.bind(this)(t,Ee).then(e=>n(o(e))).catch(r);else try{n(o(t))}catch(e){r(e)}})}),n=(e,t)=>{let n=t||e.includes(this.service+"-")?e:this.service+"-"+ie.hash(e);return{cognitoUser:new j({Username:n,Pool:this.userPool}),cognitoUsername:n}};return{getSession:t,authenticateUser:(e,r,s=!1,o=!1)=>new Promise((a,c)=>{this.__request_signup_confirmation=null,this.__disabledAccount=null;let u=n(e,s),l=u.cognitoUsername,h=new i({Username:l,Password:r});u.cognitoUser.authenticateUser(h,{newPasswordRequired:(e,n)=>{this.__disabledAccount=null,this.__request_signup_confirmation=l,"PASS"===e["custom:signup_ticket"]||"MEMBER"===e["custom:signup_ticket"]||"OIDPASS"===e["custom:signup_ticket"]?u.cognitoUser.completeNewPasswordChallenge(r,{},{onSuccess:e=>{Ee=u.cognitoUser,t().then(e=>a(this.user))},onFailure:e=>{c(new te(e.message||"Failed to authenticate user.",{code:e.code}))}}):c(new te("User's signup confirmation is required.",{code:"SIGNUP_CONFIRMATION_NEEDED"}))},onSuccess:e=>t({skipUserUpdateEventTrigger:!0}).then(e=>{this.__disabledAccount=null,this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user),a(this.user)}),onFailure:e=>{let t=[],{parsed:n,code:r}=Ne(e),i="string"==typeof e?.message?e.message:"";if("NotAuthorizedException"===r?i.includes("User is disabled.")?(this.__disabledAccount=l,t=["This account is disabled.","USER_IS_DISABLED"]):t=o?["The account already exists.","ACCOUNT_EXISTS"]:["Incorrect username or password.","INCORRECT_USERNAME_OR_PASSWORD"]:"UserNotFoundException"===r?t=["Incorrect username or password.","INCORRECT_USERNAME_OR_PASSWORD"]:"UserNotConfirmedException"===r?(this.__request_signup_confirmation=l,t=["User's signup confirmation is required.","SIGNUP_CONFIRMATION_NEEDED"]):"TooManyRequestsException"!==r&&"LimitExceededException"!==r||(t=["Too many attempts. Please try again later.","REQUEST_EXCEED"]),"SIGNUP_CONFIRMATION_NEEDED"===n.code&&(this.__request_signup_confirmation=l),t.length){let n=t[1],r=t[0];c(new te(r,{code:n,cause:e}))}else c(n)}})}),createCognitoUser:n,signup:(e,t,n)=>new Promise((r,i)=>{this.userPool.signUp(e,t,n,null,(e,t)=>{if(e){let{parsed:t,code:n}=Ne(e),r=[];return"UsernameExistsException"===n?r=["The account already exists.","EXISTS"]:"InvalidPasswordException"===n?r=["Invalid password. Password must be at least 6 characters.","INVALID_PARAMETER"]:"InvalidParameterException"===n?r=[t.message||"Invalid parameter.","INVALID_PARAMETER"]:"TooManyRequestsException"===n||"LimitExceededException"===n?r=["Too many attempts. Please try again later.","REQUEST_EXCEED"]:"CodeDeliveryFailureException"===n?r=["Failed to deliver verification code.","CODE_DELIVERY_FAILURE"]:"UserLambdaValidationException"===n&&(r=[t.message||"Signup validation failed.","INVALID_REQUEST"]),void(r.length?i(new te(r[0],{code:r[1],cause:e})):i(t))}r(t)})})}}function Ne(e){let t="string"==typeof e?.code&&e.code.trim()?e.code.trim():"ERROR",n=(("string"==typeof e?.message?e.message:"string"==typeof e?e:"An error occurred.")||"An error occurred.").trim();n||(n="An error occurred.");let r=n.match(/#([A-Za-z0-9_]+)\s*:\s*([\s\S]+)/),i=r?.[1]?.trim()||t,s=r?.[2]?.trim()||n;return{parsed:new te(s,{code:i,cause:e}),code:t}}async function Le(e){await this.__authConnection;let t=e?.refreshToken||!1;if(!t)return this.user;try{return await ke.bind(this)().getSession(Object.assign({skipUserUpdateEventTrigger:!t,refreshToken:t},e)),this.user}catch(e){return null}}async function Oe(e){await this.__connection,e=ve.Params(e,{token:"string",id:"string",merge:e=>{if(void 0===e)return!1;if("string"==typeof e)return[e];if(Array.isArray(e))for(let t of e)if("string"!=typeof t)throw new te('"merge" array items should be type: <string>.',{code:"INVALID_PARAMETER"});if("boolean"!=typeof e&&!Array.isArray(e))throw new te('"merge" should be type: <boolean | string[]>.',{code:"INVALID_PARAMETER"});return e}});let t=await ft.bind(this)("openid-logger",e),n=t.logger.split("#"),r=this.service+"-"+n[0],i=n[1];return{userProfile:await ke.bind(this)().authenticateUser(r,i,!0,!0),openid:t.openid}}async function Me(e){await this.__authConnection,this.log("loginWithToken:params",e);const t=function(e){const t=e.split(".");if(3!==t.length)throw new Error("Invalid JWT format");const n=function(e){const t="undefined"!=typeof globalThis?globalThis:void 0;if(t?.Buffer)return t.Buffer.from(e,"base64").toString("utf8");if("function"==typeof atob){const t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return"undefined"!=typeof TextDecoder?(new TextDecoder).decode(n):t}throw new Error("No base64 decoder available in this environment")}(t[1].replace(/-/g,"+").replace(/_/g,"/"));return JSON.parse(n)}((e=ve.Params(e,{idToken:"string",accessToken:"string",refreshToken:"string"},["idToken"])).idToken);if(this.log("loginWithToken:idTokenPayload",t),t["custom:service"]!==this.service)throw new te("Token does not belong to this service.",{code:"INVALID_REQUEST"});const n=Math.floor(Date.now()/1e3);if(t.exp&&t.exp<n)throw new te("Token has expired.",{code:"INVALID_REQUEST"});if(this.__user=pe(t),this.session=null,e.accessToken&&e.refreshToken)try{if(this.session=new N({IdToken:new U({IdToken:e.idToken}),AccessToken:new R({AccessToken:e.accessToken}),RefreshToken:new P({RefreshToken:e.refreshToken})}),this.log("loginWithToken:session",this.session),this.log("loginWithToken:CognitoUser",j),this.log("loginWithToken:userPool",this.userPool),j&&this.userPool){this.log("loginWithToken:cognito:username",t["cognito:username"]);let e={Username:t["cognito:username"],Pool:this.userPool};this.log("loginWithToken:cognitoUserParams",e),Ee=new j(e),Ee.setSignInUserSession(this.session),this.log("loginWithToken:cognitoUserRestored",{cognitoUserType:typeof Ee,cognitoUserKeys:Object.keys(Ee||{}),cognitoUser:Ee})}}catch(e){this.log("loginWithToken:err",e);try{this.log("loginWithToken:err:stringified",JSON.stringify(e))}catch(t){this.log("loginWithToken:err:stringifyFail",String(e))}try{const t=Object.keys(e||{}),n=Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(e||{}):[],r=Object.getOwnPropertyDescriptors?Object.getOwnPropertyDescriptors(e||{}):{};this.log("loginWithToken:createSessionError:allKeys",{keys:t,symbols:n,descriptors:r})}catch(e){this.log("loginWithToken:createSessionError:allKeysFail",String(e))}}return this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user),this.user}async function Ve(){return await this.__connection,this.__user?.service===this.service?this.__user?.owner===this.host:(await Fe.bind(this)(),!1)}async function xe(e=!1){let t=null;Ee&&(e?t=new Promise((e,t)=>{Ee.globalSignOut({onSuccess:t=>{this.log("globalSignOut:success",t),e(t)},onFailure:e=>{this.log("globalSignOut:error",e),t(e)}})}):Ee.signOut());let n={session:null,__startKeyHistory:{},__cached_requests:{},__user:null};t&&(t=await t);for(let e in n)this[e]=n[e];return this._runOnUserUpdateListeners(null),this._runOnLoginListeners(null),t}async function Fe(e){await this.__connection;let{data:t}=fe(e);return await xe.bind(this)(t?.global),"SUCCESS: The user has been logged out."}async function qe(){if(!this.__request_signup_confirmation)throw new te("Least one login attempt is required.",{code:"INVALID_REQUEST"});return await ft.bind(this)("confirm-signup",{username:this.__request_signup_confirmation})}async function $e(e=!1){if("string"==typeof e)e=ve.Url(e);else if("boolean"!=typeof e)throw new te("Argument should be type: <boolean | string>.",{code:"INVALID_REQUEST"});if(!this.__disabledAccount)throw new te("Least one signin attempt of disabled account is required.",{code:"INVALID_REQUEST"});return await ft.bind(this)("recover-account",{username:this.__disabledAccount,redirect:e}),"SUCCESS: Recovery e-mail has been sent."}async function je(e){let t=ve.Params(e,{username:"string",email:"string",password:"string"},["password"]);if(await this.__authConnection,t.email)try{ve.Email(t.email)}catch(e){t.username=t.email,delete t.email}if(!t.username&&!t.email)throw new te('Least one of "username" or "email" is required.',{code:"INVALID_PARAMETER"});return await ke.bind(this)().authenticateUser(t.username||t.email,t.password)}async function Be(e,t){await this.__authConnection;let n={username:"string",password:e=>ve.Password(e),email:e=>ve.Email(e),name:"string",address:e=>e?"string"==typeof e?e:"object"==typeof e?JSON.stringify(e):void 0:"",gender:"string",birthdate:e=>e?ve.Birthdate(e):"",phone_number:e=>e?ve.PhoneNumber(e):"",email_public:["boolean",()=>!1],address_public:["boolean",()=>!1],gender_public:["boolean",()=>!1],birthdate_public:["boolean",()=>!1],phone_number_public:["boolean",()=>!1],access_group:"number",misc:"string",picture:e=>e?ve.Url(e):"",profile:e=>e?ve.Url(e):"",family_name:"string",given_name:"string",middle_name:"string",nickname:"string",website:e=>e?ve.Url(e):""},r=ve.Params(e||{},n,["email","password"]);await Fe.bind(this)(),t=ve.Params(t||{},{email_subscription:e=>{if("boolean"!=typeof e)throw new te('"option.email_subscription" should be type: <boolean>.',{code:"INVALID_PARAMETER"});if(!t?.signup_confirmation)throw new te('"option.signup_confirmation" is required for email subscription.',{code:"INVALID_PARAMETER"});return e},signup_confirmation:e=>{let t=e;if("string"==typeof e)t=ve.Url(e);else{if("boolean"!=typeof e)throw new te('"option.signup_confirmation" should be type: <string | boolean>.',{code:"INVALID_PARAMETER"});t=e}if(t&&!r.email)throw new te('"email" is required for signup confirmation.',{code:"INVALID_PARAMETER"});return t},login:e=>{if("boolean"==typeof e){if(t.signup_confirmation&&e)throw new te('"login" is not allowed when "option.signup_confirmation" is true.',{code:"INVALID_PARAMETER"});return e}throw new te('"option.login" should be type: boolean.',{code:"INVALID_PARAMETER"})}});let i=t?.login||!1;if(r.signup_confirmation=t?.signup_confirmation||!1,r.email_subscription=t?.email_subscription||!1,r.email_public&&!r.signup_confirmation)throw new te('"option.signup_confirmation" should be true if "email_public" is set to true.',{code:"INVALID_PARAMETER"});r.service=this.service,r.owner=this.owner;let s=ke.bind(this)().createCognitoUser(r.username||r.email);for(let e of["email_public","address_public","gender_public","birthdate_public","phone_number_public"])r[e]=r[e]?"1":"0";r.access_group&&(r.access_group=r.access_group.toString());let o=(await ft.bind(this)("signupkey",{username:s.cognitoUsername,signup_confirmation:"boolean"==typeof r.signup_confirmation?JSON.stringify(r.signup_confirmation):r.signup_confirmation,email_subscription:r.email_subscription})).split(":"),a=o.slice(1).join(":"),c=[new V({Name:"custom:signup",Value:o[0]}),new V({Name:"locale",Value:a.split("#")[1]}),new V({Name:"custom:signup_ticket",Value:a})];for(let e in n){let t=["email_public","address_public","gender_public","birthdate_public","phone_number_public","misc","service","owner"];""!==r[e]&&"username"!==e&&"password"!==e&&"access_group"!==e&&(t.includes(e)?c.push(new V({Name:"custom:"+e,Value:r[e]})):c.push(new V({Name:e,Value:r[e]})))}return await ke.bind(this)().signup(s.cognitoUsername,r.password,c),r.signup_confirmation?(Ee=s.cognitoUser,this.__request_signup_confirmation=s.cognitoUsername,"SUCCESS: The account has been created. User's signup confirmation is required."):i?je.bind(this)({email:r.username||r.email,password:r.password}):"SUCCESS: The account has been created."}async function Ke(){await this.__connection;let e=await ft.bind(this)("remove-account",{disable:this.__user.user_id},{auth:!0});return await Fe.bind(this)(),e}async function Je(e){await this.__connection;let t=ve.Params(e,{email:e=>ve.Email(e),code:["number","string"],new_password:e=>ve.Password(e)},["email","code","new_password"]),n=t.code,r=t.new_password;return"number"==typeof n&&(n=n.toString()),new Promise(async(e,i)=>{ke.bind(this)().createCognitoUser(t.email).cognitoUser.confirmPassword(n,r,{onSuccess:t=>{e("SUCCESS: New password has been set.")},onFailure:e=>{i(new te(e?.message||"Failed to reset password.",{code:e?.code||"ERROR",cause:e}))}})})}async function He(e,t){let n;if(await this.__connection,!Ee)throw new te("The user has to be logged in.",{code:"INVALID_REQUEST"});if("email"===e||"phone_number"===e){if(!this.__user.hasOwnProperty(e))throw new te(`No ${"email"===e?"e-mail":"phone number"} to verify`,{code:"INVALID_REQUEST"});return this.__user?.[`${e}_verified`]?`SUCCESS: "${e}" is verified.`:(n=(t?ve.Params(t,{code:["string"]}):{}).code||"",new Promise((t,r)=>{let i={onSuccess:i=>{n?ke.bind(this)().getSession({refreshToken:!0}).then(()=>{this.__user&&(this.__user[e+"_verified"]=!0),t(`SUCCESS: "${e}" is verified.`)}).catch(e=>{r(e)}):t("SUCCESS: Verification code has been sent.")},onFailure:e=>{r(new te(e.message||"Failed to request verification code.",{code:e?.code}))}};n?Ee?.verifyAttribute(e,n,i):(i.inputVerificationCode=null,Ee?.getAttributeVerificationCode(e,i))}))}}function We(e){return He.bind(this)("phone_number",e)}function Qe(e){return He.bind(this)("email",e)}async function ze(e){await this.__connection;let t=ve.Params(e,{email:e=>ve.Email(e)},["email"]);return new Promise(async(e,n)=>{ke.bind(this)().createCognitoUser(t.email).cognitoUser.forgotPassword({onSuccess:t=>{e("SUCCESS: Verification code has been sent.")},onFailure:e=>{let{parsed:t,code:r}=Ne(e),i={UserNotFoundException:"NOT_EXISTS",InvalidParameterException:"INVALID_PARAMETER",NotAuthorizedException:"INVALID_REQUEST",LimitExceededException:"REQUEST_EXCEED",TooManyRequestsException:"REQUEST_EXCEED",CodeDeliveryFailureException:"CODE_DELIVERY_FAILURE"}[r]||t.code||r||"ERROR";n(new te(t.message,{code:i,cause:e}))}})})}async function Ge(e){if(await this.__connection,!this.session)throw new te("User login is required.",{code:"INVALID_REQUEST"});let t=ve.Params(e,{current_password:"string",new_password:"string"});if(!t?.current_password)throw new te('"current_password" is required to change password.',{code:"INVALID_PARAMETER"});if(!t?.new_password)throw new te('"new_password" is required to change password.',{code:"INVALID_PARAMETER"});return ve.Password(t.current_password),ve.Password(t.new_password),new Promise((e,n)=>{Ee.changePassword(t.current_password,t.new_password,(t,r)=>{if(t)if("InvalidParameterException"===t?.code)n(new te("Invalid password parameter.",{code:"INVALID_PARAMETER"}));else if("NotAuthorizedException"===t?.code)n(new te("Incorrect password.",{code:"INVALID_REQUEST"}));else if("TooManyRequestsException"===t?.code||"LimitExceededException"===t?.code)n(new te("Too many attempts. Please try again later.",{code:"REQUEST_EXCEED"}));else{let{parsed:e,code:r}=Ne(t);n(e)}else e("SUCCESS: Password has been changed.")})})}async function Ye(e){if(await this.__connection,!this.session)throw new te("User login is required.",{code:"INVALID_REQUEST"});let t=ve.Params(e||{},{user_id:e=>ve.UserId(e),email:e=>ve.Email(e),address:e=>e?"string"==typeof e?e:"object"==typeof e?JSON.stringify(e):void 0:"",name:"string",gender:"string",birthdate:e=>e?ve.Birthdate(e):"",phone_number:e=>e?ve.PhoneNumber(e):"",email_public:"boolean",phone_number_public:"boolean",address_public:"boolean",gender_public:"boolean",birthdate_public:"boolean",misc:"string",picture:e=>e?ve.Url(e):"",profile:e=>e?ve.Url(e):"",family_name:"string",given_name:"string",middle_name:"string",nickname:"string",website:e=>e?ve.Url(e):""});if(t&&"object"==typeof t&&!Object.keys(t).length)return this.user;t.email&&(t.preferred_username=this.service+"-"+ie.hash(t.email));let n=[["email_public","email_verified","User's e-mail should be verified to set"],["phone_number_public","phone_number_verified","User's phone number should be verified to set"]];if(this.__user)for(let e of n)if(t[e[0]]&&!this.__user[e[1]])throw new te(`${e[2]} "${e[0]}" to true.`,{code:"INVALID_REQUEST"});let r=[];for(let e in t)if(t[e]!==this.user[e]){if(["email_public","phone_number_public","address_public","gender_public","birthdate_public","misc"].includes(e)){let n=t[e];"boolean"==typeof n&&(n=n?"1":"0"),t["custom:"+e]=n,r.push(e)}}else r.push(e);for(let e of r)delete t[e];if(t.user_id){if(t.user_id!==this.user.user_id)return ft.bind(this)("admin-edit-profile",{attributes:t},{auth:!0});delete t.user_id}if(t&&"object"==typeof t&&Object.keys(t).length){let e=[];for(let n in t)e.push(new V({Name:n,Value:t[n]}));return await new Promise((t,n)=>{Ee?.updateAttributes(e,(e,r)=>{e&&n([e?.code||e?.name,e?.message||"Failed to update user settings."]),t(r)})}),await ke.bind(this)().getSession({refreshToken:!0}),this.user}return this.user}async function Ze(e,t){(e=fe(e).data)||(e={searchFor:"timestamp",condition:">",value:0},t||(t={}),t.ascending=!1),await this.__connection;const n={user_id:e=>Array.isArray(e)?e.map(e=>ve.UserId(e)):ve.UserId(e),email:"string",phone_number:"string",locale:e=>{if("string"!=typeof e||"string"==typeof e&&e.length>5)throw new te('Value of "locale" should be a country code.',{code:"INVALID_PARAMETER"});return e},name:"string",address:"string",gender:"string",birthdate:e=>ve.Birthdate(e),subscribers:"number",timestamp:"number",access_group:"number",approved:"string"};if(e=ve.Params(e,{searchFor:["user_id","name","email","phone_number","address","gender","birthdate","locale","subscribers","timestamp","access_group","approved"],condition:[">",">=","=","<","<=","gt","gte","eq","lt","lte",()=>"="],value:t=>{let r=n[e.searchFor];if("function"==typeof r)return r(t);if(typeof t!==r)throw new te(`Value does not match the type of "${e.searchFor}" index.`,{code:"INVALID_PARAMETER"});return t},range:t=>{let r=n[e.searchFor];if("function"==typeof r)return r(t);if(typeof t!==r)throw new te(`Range does not match the type of "${e.searchFor}" index.`,{code:"INVALID_PARAMETER"});return t}},["searchFor","value"]),e?.condition&&"="!==e?.condition&&e.hasOwnProperty("range"))throw new te("Conditions does not apply on range search.",{code:"INVALID_PARAMETER"});if("user_id"===e.searchFor&&("="!==e.condition||e.range))throw new te(`Conditions are not allowed on "${e.searchFor}"`,{code:"INVALID_PARAMETER"});if("string"==typeof e?.value&&!e?.value)throw new te("Value should not be an empty string.",{code:"INVALID_PARAMETER"});if("string"==typeof e?.searchFor&&!e?.searchFor)throw new te('"searchFor" should not be an empty string.',{code:"INVALID_PARAMETER"});return ft.bind(this)("get-users",e,{auth:!0,fetchOptions:t})}async function Xe(e){await this.__connection;let t=await ft.bind(this)("last-verified-email",e,{auth:!0});return t.includes("SUCCESS")?(await ke.bind(this)().getSession({refreshToken:!0}),this.user):t}async function et(e){return await this.__connection,e=ve.Params(e,{username:ve.Email,redirect:ve.Url},["username"]),await ft.bind(this)("request-username-change",e,{auth:!0})}var tt=class{version="1.1.0";items=[];breakWhenError=!1;batchSize=1;onProgress;activeCount=0;currentCycleCompleted=[];stopProcessing=!1;get batchToProcess(){return Math.ceil(this.items.length/this.batchSize)}constructor(e){if(this.breakWhenError=!!e?.breakWhenError,this.batchSize=e?.batchSize??1,"number"!=typeof this.batchSize||this.batchSize<1)throw new Error("batchSize must be at least 1");if(e?.onProgress){if("function"!=typeof e.onProgress)throw new Error("onProgress must be a function");this.onProgress=e.onProgress}}add(e){const t=Array.isArray(e)?e:[e];for(const e of t){if("function"!=typeof e)throw new Error("Each job must be a function that returns a Promise");this.items.push(e)}this.processNext()}processNext(){if(this.stopProcessing||0===this.items.length||this.activeCount>0)return;const e=this.items.splice(0,this.batchSize);this.activeCount=e.length,this.currentCycleCompleted=new Array(e.length),e.forEach((e,t)=>{Promise.resolve().then(()=>e()).then(e=>(this.finalizeJob(t,e,!1),e)).catch(e=>(this.finalizeJob(t,e,!0),e))})}finalizeJob(e,t,n){if(this.currentCycleCompleted[e]=t,this.activeCount-=1,n&&this.breakWhenError&&(this.stopProcessing=!0,this.items=[]),0!==this.activeCount)return;const r=this.currentCycleCompleted.slice();this.currentCycleCompleted=[],this.onProgress&&this.onProgress({batchToProcess:this.batchToProcess,itemsToProcess:this.items.length,completed:r}),this.processNext()}terminate(){this.items=[]}};let nt=null;const rt="undefined"!=typeof SubmitEvent,it="undefined"!=typeof HTMLFormElement,st=ue();let ot=0;function at(e){if(!e)return null;const t=Number(e);if(Number.isFinite(t))return Math.max(0,1e3*t);const n=Date.parse(e);return Number.isNaN(n)?null:Math.max(0,n-Date.now())}function ct(e,t){return t>0?e/t*100:0}let ut=e=>{const{auth:t,type:n,endpoints:r}=e,i=r[0],s=r[1];if(ot++,"admin"===n){const e=Object.entries(i).filter(([e,n])=>e.includes(t?"_private":"_public")&&"get_users_private"!==e&&"service_public"!==e&&"string"==typeof n).map(([,e])=>e);if(!e.length)throw new te("No available admin gateways.",{code:"INVALID_REQUEST"});return e[ot%e.length]}if("record"===n){const e=Object.entries(s).filter(([e,n])=>e.includes(t?"record_private":"record_public")&&"string"==typeof n).map(([,e])=>e);if(!e.length)throw new te("No available record gateways.",{code:"INVALID_REQUEST"});return e[ot%e.length]}throw new te("Invalid gateway type.",{code:"INVALID_REQUEST"})};async function lt(e,t){const n=await Promise.all([this.admin_endpoint,this.record_endpoint]),r=n[0],i=n[1];let s=e.split("?"),o=s.length>1?"?"+s[1]:"";switch(e=s[0]){case"get-users":return r.get_users_private+e+o;case"service":return r.service_public+e+o;case"get-newsletters":case"get-public-newsletters":case"subscribe-newsletter":case"subscribe-public-newsletter":case"signupkey":case"admin-newsletter-request":case"admin-signup":case"confirm-signup":case"openid-logger":case"block-account":case"admin-edit-profile":case"remove-account":case"post-secure":case"recover-account":case"mock":case"grant-access":case"last-verified-email":case"ticket":case"register-ticket":case"get-newsletter-subscription":case"request-username-change":case"send-inquiry":case"register-newsletter-group":case"newsletter-group-endpoint":case"invitation-list":case"csr":return ut.bind(this)({auth:t,type:"admin",endpoints:n})+e+o;case"post-record":case"bulk-records":return(t?i.post_private:i.post_public)+e+o;case"get-records":return(t?i.get_private:i.get_public)+e+o;case"del-files":case"del-records":return i.del_private+e+o;case"store-subscription":case"get-vapid-public-key":case"push-notification":case"delete-subscription":case"subscription":case"get-subscription":case"get-table":case"get-tag":case"get-uniqueid":case"get-index":case"get-signed-url":case"grant-private-access":case"request-private-access-key":case"get-ws-group":case"check-schema":case"get-feed":case"castspell":case"dopamine":case"getspell":return ut.bind(this)({auth:t,type:"record",endpoints:n})+e+o;default:return ve.Url(e)+o}}const ht={};function dt(){nt&&(nt.terminate(),nt=null)}async function ft(e,t=null,n,r){this.log("request",{url:e,data:t,options:n,_etc:r||{}}),n=n||{};let{auth:i=!1,method:s="post",bypassAwaitConnection:o=!1}=n;s=s.toUpperCase();let a=null,c=t?.service||this.service,u=t?.owner||this.owner,l=null,h=await lt.bind(this)(e,!!i);if(!o&&(a=await this.__connection,!a))throw new te("Invalid connection. The service could have been disabled, or has a restricted CORS.",{code:"INVALID_REQUEST"});i&&(l=await Pe.bind(this)());let d={},{fetchMore:f=!1,progress:p}=n?.fetchOptions||{};if(n?.fetchOptions&&Object.keys(n.fetchOptions).length){for(let e of["limit","startKey","ascending"])n.fetchOptions.hasOwnProperty(e)&&(d[e]=n.fetchOptions[e]);d=ve.Params(d,{limit:e=>{if("number"!=typeof e)throw new te("Fetch limit should be a number.",{code:"INVALID_REQUEST"});if(e>1e3)throw new te("Fetch limit should be below 1000.",{code:"INVALID_REQUEST"});return e},startKey:e=>e,ascending:"boolean"})}let g=r?.ignoreService?{}:{service:c,owner:u};Object.assign(g,d),(t=fe(t).data)?t&&"object"==typeof t&&(t=Object.assign(g,t)):t=g;let _=`${s}:${i?"auth":"public"}:${e}`,m=(()=>{if(t&&"object"==typeof t&&Object.keys(t).length&&!(st&&t instanceof FormData)){function e(t){return"object"==typeof t&&null!==t?Object.keys(t).sort().reduce((n,r)=>("object"==typeof t[r]&&null!==t[r]?n[r]=e(t[r]):n[r]=t[r],n),{}):t}return ie.hash(_+"/"+JSON.stringify(e(t)))}return ie.hash(_+"/"+c)})(),{requestKey:y,requestKeyWithStartKey:w}=pt.bind(this)({params:t,url:e,fetchMore:f,hashedParams:m});if(!y||y&&"object"==typeof y)return y;if(this.log("requestKey",w),"string"==typeof w&&ht[w]instanceof Promise)return this.log("request:returning pending",w),ht[w];let b={Accept:"*/*"};if(Object.prototype.hasOwnProperty.call(n,"contentType")&&void 0!==n.contentType){const e=null===n.contentType?"application/x-www-form-urlencoded":n.contentType;e&&(b["Content-Type"]=e)}else!st||FormData,b["Content-Type"]="application/json";l&&(b.Authorization=l);let A={public_identifier:this.__public_identifier,service:c,owner:u};b["Content-Meta"]=JSON.stringify(A);let v={headers:b};if(n?.responseType&&(v.responseType=n.responseType),"GET"===s){if(t){let e=[];if(e=st&&t instanceof FormData?Array.from(t.entries()).map(([e,t])=>{const n="string"==typeof t?t:t.name;return encodeURIComponent(e)+"="+encodeURIComponent(n)}):Object.keys(t).map(e=>{let n=t[e];return"string"!=typeof n&&(n=JSON.stringify(n)),encodeURIComponent(e)+"="+encodeURIComponent(n)}),e.length){const t=h.includes("?")?h.endsWith("?")||h.endsWith("&")?"":"&":"?";h+=t+e.join("&")}}v.body=null}else if(st&&t instanceof FormData)v.body=t;else if("application/x-www-form-urlencoded"===b["Content-Type"]&&t&&"object"==typeof t){const e=new URLSearchParams;for(let n of Object.keys(t)){const r=t[n];e.append(n,"string"==typeof r?r:JSON.stringify(r))}v.body=e.toString()}else v.body="string"==typeof t?t:t?JSON.stringify(t):null;if(v.method=s,null===nt){let e={batchSize:this.requestBatchSize,breakWhenError:!1,onProgress:e=>{this.onBatchProcess.forEach(t=>t(e))}};nt=new tt(e)}return this.log("request-opt",v),new Promise((t,n)=>{nt.add([async()=>{let r=gt.bind(this)(h,v,p);ht[w]=r;try{let n=_t.bind(this)({hashedParam:y,requestKeyWithStartKey:w,url:e,fetched:await r});return delete ht[w],this.log("request:end",n),t(n),n}catch(e){throw delete ht[w],this.log("request:err",e),n(e),e}}])})}function pt(e){let{params:t={},url:n,fetchMore:r=!1,hashedParams:i}=e||{};if(t.startKey){if(("object"!=typeof t.startKey||!Object.keys(t.startKey).length)&&"start"!==t.startKey&&"end"!==t.startKey)throw new te(`"${t.startKey}" is invalid startKey key.`,{code:"INVALID_PARAMETER"});"start"===t.startKey&&(r=!1,delete t.startKey)}if(!r){if(this.__cached_requests?.[n]?.[i]&&delete this.__cached_requests[n][i],this.__startKeyHistory?.[n]?.[i]){if(Array.isArray(this.__startKeyHistory[n][i])&&this.__startKeyHistory[n][i].length)for(let e of this.__startKeyHistory[n][i]){let t=i+ie.hash(e);this.__cached_requests?.[n]&&this.__cached_requests?.[n]?.[t]&&delete this.__cached_requests[n][t]}delete this.__startKeyHistory[n][i]}return{requestKeyWithStartKey:i,requestKey:i}}if(!Array.isArray(this.__startKeyHistory?.[n]?.[i]))return{requestKeyWithStartKey:i,requestKey:i};let s=this.__startKeyHistory[n][i],o=s[s.length-1],a=i;if(o){if("end"===o)return{requestKey:{list:[],startKey:"end",endOfList:!0,startKeyHistory:s},requestKeyWithStartKey:a};a+=ie.hash(o),t.startKey=JSON.parse(o)}return this.__cached_requests?.[n]?.[a]?{requestKey:this.__cached_requests[n][a],requestKeyWithStartKey:a}:{requestKeyWithStartKey:a,requestKey:i}}function gt(e,t,n){return new Promise((r,i)=>{let s=new XMLHttpRequest;for(var o in s.open(t.method||"GET",e),t.headers||{})s.setRequestHeader(o,t.headers[o]);t.responseType&&(s.responseType=t.responseType),s.onload=()=>{if(s.status<400)if("json"==t.responseType||"blob"==t.responseType)r(s.response);else{let e=s.responseText;try{e=JSON.parse(e)}catch(e){}r(e)}else if(429===s.status){let o=at(s.getResponseHeader("Retry-After"));null!==o?setTimeout(()=>{gt(e,t,n).then(r,i)},o):i("Too many requests")}else{let e=s.status,n=["INVALID_CORS","INVALID_REQUEST","SERVICE_DISABLED","INVALID_PARAMETER","ERROR","EXISTS","NOT_EXISTS"],r="blob"==t.responseType?s.response:s.responseText;try{r=JSON.parse(r)}catch(e){}if("string"==typeof r){let e=r.split(":"),t=e.splice(0,1)[0].trim(),s=e.join(":").trim();i(new te(s||r,{code:n.includes(t)?t:"ERROR"}))}else if("object"==typeof r&&r?.message){let t=r?.code||(e?e.toString():null)||"ERROR",n=r.message,s=r?.cause;"string"==typeof n&&(n=n.trim()),i(new te(n,{cause:s,code:t}))}else i(r)}},s.onerror=()=>i("Network error"),s.onabort=()=>i("Aborted"),s.ontimeout=()=>i("Timeout"),"function"==typeof n&&(s.onprogress=e=>{n({status:"download",progress:ct(e.loaded,e.total),loaded:e.loaded,total:e.total,abort:()=>s.abort()})},s.upload&&(s.upload.onprogress=e=>{n({status:"upload",progress:ct(e.loaded,e.total),loaded:e.loaded,total:e.total,abort:()=>s.abort()})})),s.send(t.body)})}function _t(e){let{hashedParam:t,requestKeyWithStartKey:n,url:r,fetched:i}=e;if(!i?.startKey)return i;this.__startKeyHistory.hasOwnProperty(r)||(this.__startKeyHistory[r]={}),this.__startKeyHistory[r].hasOwnProperty(t)||(this.__startKeyHistory[r][t]=[]);let s="end"===i.startKey?"end":JSON.stringify(i.startKey);return this.__startKeyHistory[r][t].includes(s)||this.__startKeyHistory[r][t].push(s),this.__cached_requests?.[r]||(this.__cached_requests[r]={}),this.__cached_requests[r][n]=i,Object.assign({startKeyHistory:this.__startKeyHistory[r][t]},i)}async function mt(e,t){await this.__connection;let{record_id:n,service:r=this.service,progress:i}=t;if(!n)throw new te('"record_id" is required.',{code:"INVALID_PARAMETER"});if(rt&&e instanceof SubmitEvent&&(e=e.target),it&&e instanceof HTMLFormElement&&(e=new FormData(e)),!(st&&e instanceof FormData))throw new te('"fileList" should be a FormData or HTMLFormElement.',{code:"INVALID_PARAMETER"});let s,o={reserved_key:ae(),service:r,request:"post"};t?.record_id&&(o.id=t.record_id);let a=(e,t,n)=>new Promise((r,i)=>{s=new XMLHttpRequest,s.open("POST",e),s.onload=()=>{let o=s.responseText;try{o=JSON.parse(o)}catch(e){}if(s.status>=200&&s.status<300)r(o);else if(429===s.status){let o=at(s.getResponseHeader("Retry-After"));null!==o?setTimeout(()=>{a(e,t,n).then(r,i)},o):i("Too many requests")}else i(o)},s.onerror=()=>i("Network error"),s.onabort=()=>i("Aborted"),s.ontimeout=()=>i("Timeout"),s.upload&&"function"==typeof n&&(s.upload.onprogress=n),s.send(t)});function c(e){const t="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";if(0===e)return t[0];let n="";for(;e>0;)n=t[e%62]+n,e=Math.floor(e/62);return n}return null===nt&&(nt=new tt({batchSize:this.requestBatchSize,breakWhenError:!1})),new Promise((t,n)=>{nt.add([async()=>{let n=[],r=[],u=[];for(let[t,l]of e.entries()){if(!(l instanceof File))continue;let e=Object.assign({key:t+"/"+l.name,sizeKey:c(l.size),contentType:l.type||null},o),{fields:h=null,url:d,cdn:f}=await ft.bind(this)("get-signed-url",e,{auth:!!this.__user});u.push(f);let p=new FormData;for(let e in h)p.append(e,h[e]);p.append("file",l);try{await a(d,p,"function"==typeof i?e=>i({status:"upload",progress:ct(e.loaded,e.total),currentFile:l,completed:n,failed:r,loaded:e.loaded,total:e.total,abort:()=>s.abort()}):null),n.push(l)}catch(e){r.push(l)}}return t({completed:n,failed:r,bin_endpoints:u}),{completed:n,failed:r,bin_endpoints:u}}])})}const yt={};function wt(e){let{preventMultipleCalls:t=!1}=e||{};return function(e,n,r){const i=r.value;r.value=function(...e){let r=e[0],s=!0,o=null,a="",c={},u=!1;if(rt&&r instanceof SubmitEvent){r.preventDefault();let e=window.location.href;o=r.target;let t=new URL(o.action);a=t.href;let n=a?a.match(/(?<=\{).*?(?=\})/g):"";if(n)for(let e of n){if(!e)continue;let t=o.querySelector(`[name="${e}"]`);if(t)if("file"===t.type)for(let n=0;n<=t.files.length-1;n++)t.files[n]&&(c[e]||(c[e]=[]),c[e].push(new Promise((e,r)=>{let i=new FileReader;i.onload=function(){e(i.result)},i.readAsDataURL(t.files[n]),i.onerror=r})));else a=a.replace(`{${e}}`,t.value)}null===o.getAttribute("action")?s=!1:u=t.href===e}const l=async e=>{if(a)for(let e in c)c[e].length&&(a=a.replace(`{${e}}`,(await Promise.all(c[e])).join(",")));return o&&s&&(window.sessionStorage.setItem(`${this.service}:${ie.hash(a)}`,JSON.stringify(e)),u?window.location.replace(a):window.location.href=a),e};let h;const d=async()=>{try{if(h=i.bind(this)(...e),h instanceof Promise){let e=await h;return l(e)}return l(h)}catch(e){throw(e=>{throw e instanceof te?e.name=n+"()":e=e instanceof Error?e:new te(e,{name:n+"()"}),e})(e)}};if(t){let e=`${n}:${this?.__public_identifier||""}:${this?.service||""}:${this?.owner||""}`;return yt?.[e]||(yt[e]=d().finally(()=>{delete yt[e]})),yt[e]}return d()}}}async function bt(){await this.__connection;let e=`${this.service}:${ie.hash(window.location.href.split("?")[0])}`,t=window.sessionStorage.getItem(e);if(window.sessionStorage.removeItem(e),null!==t){try{t=JSON.parse(t)}catch(e){}return t}return null}const At=/[\u0000-\u001F\u007F]|\u{10FFFF}/u,vt=/[\/!*#]/;function Et(e,t,n={}){const{allowEmpty:r=!1,maxLength:i,blockKeyDelimiters:s=!1,disallowLeadingDollar:o=!1}=n;if("string"!=typeof e)throw new te(`"${t}" should be type: <string>.`,{code:"INVALID_PARAMETER"});if(!r&&0===e.length)throw new te(`"${t}" is required.`,{code:"INVALID_PARAMETER"});if(i&&e.length>i)throw new te(`"${t}" should be <= ${i} characters.`,{code:"INVALID_PARAMETER"});if(At.test(e)||e.includes("􏿿"))throw new te(`"${t}" cannot include control characters or unsupported sentinel characters.`,{code:"INVALID_PARAMETER"});if(s&&vt.test(e))throw new te(`"${t}" cannot include reserved delimiters: / ! * #`,{code:"INVALID_PARAMETER"});if(o&&e.startsWith("$"))throw new te(`"${t}" cannot start with "$".`,{code:"INVALID_PARAMETER"});return e}function St(e,t="table.name"){return Et(e,t,{allowEmpty:!1,maxLength:128,blockKeyDelimiters:!0})}function It(e,t="tag"){return Et(e,t,{allowEmpty:!1,maxLength:64,blockKeyDelimiters:!0})}function Tt(e,t="index.name"){return Et(e,t,{allowEmpty:!1,maxLength:128,blockKeyDelimiters:!0,disallowLeadingDollar:!0})}function Rt(e,t="index.value"){return Et(e,t,{allowEmpty:!0,maxLength:256})}function Dt(e){if(void 0===e)return 0;if("number"==typeof e){if(e>99||e<0)throw new te('"table.access_group" value should be within a range of 0 ~ 99.',{code:"INVALID_REQUEST"})}else{if("string"!=typeof e)throw new te('"table.access_group" should be type: <number | string>.',{code:"INVALID_PARAMETER"});if(void 0===(e={private:"private",public:0,authorized:1,admin:99}[e]))throw new te('"table.access_group" is invalid.',{code:"INVALID_PARAMETER"})}if(!this.__user&&e)throw new te("Unsigned users have no access to records with access group.",{code:"INVALID_REQUEST"});return e}function Ut(e){if("number"==typeof e){if(e>4503599627370496||e<-4503599627370496)throw new te("Number value should be within range -4503599627370496 ~ +4503599627370496",{code:"INVALID_PARAMETER"});return e}if("boolean"==typeof e)return e;if("string"==typeof e)return Rt(e,"index.value");throw new te('"index.value" should be type: <number | boolean | string>.',{code:"INVALID_PARAMETER"})}function Pt(e){let t={table:{name:[e=>St(e,"table.name")],access_group:[Dt.bind(this)],subscription:e=>{if("string"==typeof e)return ve.UserId(e,'User ID in "subscription"'),e}},reference:"string",index:{name:["$updated","$uploaded","$referenced_count","$user_id",e=>Tt(e,"index.name")],value:t=>{const n={$updated:"number",$uploaded:"number",$referenced_count:"number",$user_id:ve.UserId};if(n.hasOwnProperty(e.index.name)){let r=n[e.index.name];if("function"==typeof r)return r(t);if(r!==typeof t)throw new te(`"index.value" should be type: ${r}.`,{code:"INVALID_PARAMETER"});return t}return"string"!=typeof t||t?Ut(t):""},condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq"],range:t=>function(e,t){if(!t.index||!("value"in t.index))throw new te('"index.value" is required.',{code:"INVALID_PARAMETER"});if("$record_id"===t.index.name)throw new te(`Cannot do "index.range" on ${t.index.name}`,{code:"INVALID_PARAMETER"});if(typeof t.index.value!=typeof e)throw new te('"index.range" type should match the type of "index.value".',{code:"INVALID_PARAMETER"});return"string"==typeof e?Rt(e,"index.range"):e}(t,e)},tag:e=>{if(null==e)return e;if("string"==typeof e)return It(e,"tag");throw new te('"tag" should be type: string.',{code:"INVALID_PARAMETER"})},private_key:"string"};return t.index&&t.index.hasOwnProperty("range")&&t.index.hasOwnProperty("condition")&&delete t.index.range,t}const Ct={};async function kt(e,t){if(e?.rec&&"called from postRecord"!==t){let t=window.sessionStorage.getItem(`${this.service}:post:${e.rec}`);if(t){try{e=JSON.parse(t)}catch(e){}window.sessionStorage.removeItem(`${this.service}:post:${e.rec}`)}}const n={user_id:"",record_id:"",updated:0,uploaded:0,readonly:!1,table:{name:"",access_group:0,subscription:{is_subscription_record:!1,upload_to_feed:!1,notify_subscribers:!1,feed_referencing_records:!1,notify_referencing_records:!1}},referenced_count:0,source:{referencing_limit:null,prevent_multiple_referencing:!1,can_remove_referencing_records:!1,only_granted_can_reference:!1},ip:"",bin:{}};let r=!1;function i(e){let t="**"==e?"private":parseInt(e);return t=0==t?"public":1==t?"authorized":99==t?"admin":t,t}const s={ip:e=>{let t=e.split("#"),i=t[0];t.length>1&&(n.unique_id=t[1]),"R"===i.slice(-1)?(n.readonly=!0,i=i.slice(0,-1)):n.readonly=!1,/^\d{1,3}-\d{1,3}-\d{1,3}-\d{1,3}$/.test(i)&&(i=i.split("-").join("."),r=!0),n.ip=i},rec:e=>{if(!e)return;n.record_id=e;let t=oe(e.substring(0,e.length-9));n.uploaded=t},usr:e=>{n.user_id=e},tbl:e=>{if(e&&!n.table.name){let t=e.split("/");n.table.name=t[0],n.table.access_group=i(t[2]),t?.[3]&&(n.table.subscription.is_subscription_record=!0)}},usr_tbl:e=>{let t=e.split("/");n.user_id||(n.user_id=t[0]),n.table.name||(n.table.name=t[1],n.table.access_group=i(t[3]),t?.[4]&&(n.table.subscription.is_subscription_record=!0))},idx:e=>{if(!e)return;let t=e.split("!"),r=t.splice(0,1)[0],i=function(e){let t=e.substring(3);switch(e.substring(0,3)){case"!S%":return t;case"!N%":let n=t.split("."),r=Number(n[0])-4503599627370496;return 1===n.length?r:parseFloat(r.toString()+"."+n[1]);case"!B%":return"1"===t;case"!L%":case"!D%":try{return JSON.parse(t)}catch(e){throw new te("Value parse error.",{code:"PARSE_ERROR"})}default:return e}}("!"+t.join("!"));n.index={name:r,value:i}},ref:e=>{e&&(n.reference=e.split("/")[0])},tags:e=>{n.tags=e},upd:e=>{n.updated=e},acpt_mrf:e=>{n.source.prevent_multiple_referencing=!e},ref_limt:e=>{n.source.referencing_limit=e},rfd:e=>{n.referenced_count=e},bin:async e=>{let t={},r=n?.reference||null;if(Array.isArray(e)){const n=await Promise.all(e.map(async e=>{try{let t=e.split("/").slice(3).join("/"),n=t.split("/");if(n.length<12)return null;let s=decodeURIComponent(n[n.length-1]),o=decodeURIComponent(n[10]),a=n[9],c=n[8],u=i(n[6]),l=e;"public"!==u&&(l=await Lt.bind(this)(e,{dataType:"endpoint",_ref:r}));let h={access_group:u,filename:s,url:l,path:t,size:oe(a),uploaded:oe(c),getFile:(e,t)=>{let n={dataType:e||"download",progress:t,_ref:r,_update:h};return Lt.bind(this)(l,n)}};return{pathKey:o,obj:h}}catch{return null}}));for(let e of n)e&&(t[e.pathKey]?t[e.pathKey].push(e.obj):t[e.pathKey]=[e.obj])}n.bin=t},prv_acs:e=>{for(let t in e)["notify_subscribers","upload_to_feed","feed_referencing_records","notify_referencing_records"].includes(t)?n.table.subscription[t]=e[t]:n.source[t]=e[t]},data:e=>{let t=e;"!D%{}"===e?t={}:"!L%[]"===e&&(t=[]),n.data=t}};if(e.record_id)return e;for(let t in s)if(e.hasOwnProperty(t)){let n=s[t](e[t]);n instanceof Promise&&await n}return r&&(n.user_id="anonymous:"+n.user_id),n}async function Nt(e){let{endpoints:t}=e;if("string"==typeof t&&(t=[t]),!Array.isArray(t))throw new te('"endpoints" should be type: array | string.',{code:"INVALID_PARAMETER"});let n=await ft.bind(this)("del-files",{endpoints:t,storage:"records"},{auth:!0,method:"post"}),r=[];for(let e in n)r.push(kt.bind(this)(n[e]));return Promise.all(r)}async function Lt(e,t){if("string"!=typeof e)throw new te('"url" should be type: string.',{code:"INVALID_PARAMETER"});let n=e.split("?"),r=n.shift()||"",i=n.length?"?"+n.join("?"):"",s=ve.Url(r);e=s+i;let o=!1,a=s.split("/"),c=a[2].split("."),u=null;3===c.length&&"skapi"===c[1]&&(u=c[0],o=!0);let l=a.slice(3),h=!1;if(!o&&("auth"===l[0]||"publ"===l[0]))try{ve.UserId(l[2]),ve.UserId(l[3]),h="auth"==l[0],o=!0}catch{throw new te("Invalid file url.",{code:"INVALID_PARAMETER"})}let d=u?null:l[1];if(t=ve.Params(t,{expires:["number",()=>0],dataType:["base64","blob","endpoint","text","info",()=>"download"],progress:"function",_ref:"string",_update:e=>e}),"info"===t?.dataType)return{url:e,filename:l[l.length-1],fileKey:l[l.length-2],access_group:"**"===l[6]?"private":"01"===l[6]?"authorized":"00"===l[6]?"public":parseInt(l[6]),uploader:l[3],record_id:"records"===l[4]?l[5]:"N/A",filesize:oe(l[9]),uploaded:oe(l[8])};let f=e.split("/").slice(-1)[0],p=t.expires;if(p){if(!o)throw new te("Expires option can only be used on skapi cdn endpoints.",{code:"INVALID_PARAMETER"});if(p<0)throw new te('"config.expires" should be > 0. (seconds)',{code:"INVALID_PARAMETER"});let t={request:u?"get-host":"get",id:u||l[5],key:e,expires:p};d&&(t.service=d),e=(await ft.bind(this)("get-signed-url",t,{auth:!0})).url}else if(h){let n=Math.floor(Date.now()/1e3);if(!this.bearerToken&&(!this.session?.idToken?.payload?.exp||this.session.idToken.payload.exp<n)){this.log("getFile:requesting new token",null);try{await ke.bind(this)().getSession({refreshToken:!0}),this.log("getFile:received new tokens",{exp:this.session?.idToken?.payload?.exp,currTime:n,expiresIn:this.session?.idToken?.payload?.exp-n,token:this.session?.accessToken?.jwtToken,refreshToken:this.session?.refreshToken?.token})}catch(e){throw this.log("getFile:new token error",e),new te("User login is required.",{code:"INVALID_REQUEST"})}}let r=this.bearerToken||this.session?.idToken?.jwtToken;if(!r||!this.user?.user_id)throw new te("User login is required.",{code:"INVALID_REQUEST"});e+=`${e.includes("?")?"&":"?"}t=${encodeURIComponent(r)}`;let i="**"===l[6]?"**":parseInt(l[6]),s=this.user?.access_group??-1;if(this.user.user_id!==l[3]&&("**"===i||s<i)){let n=l[5];if(this.__private_access_key[n]&&"string"==typeof this.__private_access_key[n])e+=`&p=${encodeURIComponent(this.__private_access_key[n])}`;else if(this.owner!==this.host)try{let r=await this.requestPrivateRecordAccessKey({record_id:n,reference_id:t?._ref});e+=`&p=${encodeURIComponent(r)}`}catch(e){}}}if("endpoint"===t?.dataType)return t._update&&(t._update.url=e),e;if("download"===t?.dataType){let t=document.createElement("a");return t.href=e,document.body.appendChild(t),t.setAttribute("download",f),t.target="_blank",t.click(),document.body.removeChild(t),null}return new Promise(async(n,r)=>{try{let r=await ft.bind(this)(e,null,{method:"get",contentType:null,responseType:"text"===t?.dataType?"text":"blob",fetchOptions:{progress:t?.progress}},{ignoreService:!0});if("base64"===t?.dataType){const e=new FileReader;e.onloadend=()=>n(e.result),e.readAsDataURL(r)}else n(r)}catch(e){r(e)}})}async function Ot(e,t=!1){e=fe(e,{ignoreEmpty:!0}).data||{},"string"==typeof e?.table&&(e.table={name:e.table,access_group:0});let n="",r=function(e){if(!e.record_id&&!e.unique_id)return null;let t={};return e?.service&&(t.service=e.service),e?.owner&&(t.owner=e.owner),e?.record_id?t.record_id=ve.specialChars(e.record_id,"record_id",!1,!1):e?.unique_id&&(t.unique_id=e.unique_id),t}(e);if(r)n=(e=r).record_id||e.unique_id,"string"==typeof n&&("string"==typeof this.__private_access_key?.[n]&&(e.private_key=this.__private_access_key?.[n]||void 0),this.__my_unique_ids[n]&&(t?delete this.__my_unique_ids[n]:e.record_id=this.__my_unique_ids[n]));else{let t=await Ve.bind(this)(),r=e?.reference,i="";r?.record_id||r?.unique_id?(n=r.record_id||r.unique_id,n&&"string"==typeof this.__private_access_key?.[n]&&(e.private_key=this.__private_access_key?.[n]||void 0),e.reference=n):r?.user_id&&(i=r.user_id,e.reference=i),e=ve.Params(e||{},Pt.bind(this)(e),i||t?[]:["table"],{ignoreEmpty:!0})}return{query:e,is_reference_fetch:n}}async function Mt(e,t){await this.__connection;let n=await Ot.bind(this)(e),r=n.is_reference_fetch,i=await ft.bind(this)("get-records",n.query,{fetchOptions:t,auth:!!this.__user,method:this.__user?"post":"get"});r&&i?.reference_private_key&&"string"==typeof i.reference_private_key&&(this.__private_access_key[r]=i.reference_private_key);let s=[];for(let e in i.list)s.push(kt.bind(this)(i.list[e]));return i.list=await Promise.all(s),i}async function Vt(e,t,n){await this.__connection;let r="";if(!t)throw new te('"config" argument is required.',{code:"INVALID_PARAMETER"});let i=!this.__user;if("string"==typeof t.table&&(t.table={name:t.table}),!t.record_id){if(!t.table||"object"!=typeof t.table)throw new te('"table.name" is required.',{code:"INVALID_PARAMETER"});Object.prototype.hasOwnProperty.call(t.table,"access_group")||(t.table.access_group=0)}t.table?.subscription&&(t.table?.subscription?.is_subscription_record?Object.assign(t.table.subscription,{group:1}):!1!==t.table?.subscription?.is_subscription_record&&(t.record_id||t.table.subscription?.is_subscription_record)||Object.assign(t.table.subscription,{group:null}),delete t.table.subscription?.is_subscription_record);let s=ve.Params(t||{},{record_id:["string",()=>{if(!t.table||!t.table.name)throw new te('"table.name" is required.',{code:"INVALID_PARAMETER"})}],unique_id:"string",readonly:"boolean",table:{name:e=>St(e,"table.name"),subscription:{group:e=>1===e?1:null,upload_to_feed:"boolean",notify_subscribers:"boolean",feed_referencing_records:"boolean",notify_referencing_records:"boolean"},access_group:Dt.bind(this)},source:{referencing_limit:e=>{if(null===e)return null;if("number"==typeof e){if(0>e)throw new te('"reference_limit" should be >= 0',{code:"INVALID_PARAMETER"});if(e>4503599627370546)throw new te('"reference_limit" should be <= 4503599627370546',{code:"INVALID_PARAMETER"});return e}throw new te('"reference_limit" should be type: <number | null>',{code:"INVALID_PARAMETER"})},prevent_multiple_referencing:"boolean",can_remove_referencing_records:"boolean",only_granted_can_reference:"boolean",allow_granted_to_grant_others:"boolean",referencing_index_restrictions:e=>{if(void 0===e)return;if(!e)return null;if(Array.isArray(e)&&!e.length)return null;let t={name:[e=>Tt(e,'"name" in "index_restrictions"')],value:e=>Ut(e),condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne",()=>null],range:t=>{if(null!==t&&typeof e.value!=typeof t)throw new te('Index restriction "range" type should match the type of "value".',{code:"INVALID_PARAMETER"});if(!e.hasOwnProperty("value"))throw new te('Index restriction "value" is required.',{code:"INVALID_PARAMETER"});return t}};Array.isArray(e)||(e=[e]);let n=e.map(e=>ve.Params(e,t));if(n.length)for(let e of n)e.condition&&e.hasOwnProperty("range")&&delete e.range;return n}},reference:e=>{if(null===e)return{record_id:null};if(e){if("string"==typeof e)return r=e,this.__my_unique_ids[e]?this.__my_unique_ids[e]:e;if("object"!=typeof e)throw new te('"reference" should be type: <string | object>.',{code:"INVALID_PARAMETER"});return ve.Params(e,{unique_id:"string",record_id:e=>null==e?e:(r=e,"string"==typeof this.__private_access_key?.[e]&&(t.reference_private_key=this.__private_access_key[e]||void 0),ve.specialChars(e,'"reference.record_id"',!1,!1))})}},index:{name:e=>Tt(e,"index.name"),value:e=>Ut(e)},tags:e=>{if(null==e)return e;if("string"==typeof e&&(e=e.split(",").map(e=>e.trim())),!Array.isArray(e))throw new te('"tag" should be type: <string | string[]>.',{code:"INVALID_PARAMETER"});return e.map(e=>It(e,"tag"))},remove_bin:e=>{if(!e)return null;let t=[];if(!Array.isArray(e))throw new te('"remove_bin" should be type: <string[] | BinaryFile[] | null>',{code:"INVALID_PARAMETER"});for(let n of e)if("string"==typeof n)t.push(decodeURIComponent(n.split("?")[0]));else{if(!(n.url&&n.size&&n.filename))throw new te('"remove_bin" should be type: <string[] | BinaryFile[] | null>',{code:"INVALID_PARAMETER"});{let e=n.url.split("/").slice(0,3).join("/")+"/"+n.path;t.push(e)}}return t},progress:"function"}),o=t.progress||null;delete s.progress;let a={auth:!!this.__user,method:"post"},c=null,u=[],l=fe(e);if(n&&Array.isArray(n)&&n.length&&(u=u.concat(n)),l.files&&Array.isArray(l.files)&&l.files.length&&(u=u.concat(l.files)),i){if(s.record_id)throw new te("Public users cannot update existing records.",{code:"INVALID_REQUEST"});if("public"!==s.table.access_group&&0!==s.table.access_group)throw new te("Public users can only post records to public tables.",{code:"INVALID_REQUEST"});if(s.table.subscription)throw new te("Public users cannot post subscription records.",{code:"INVALID_REQUEST"});if(s.remove_bin)throw new te("Public users cannot remove files from records.",{code:"INVALID_REQUEST"});if(s.unique_id)throw new te("Public users cannot set unique_id for records.",{code:"INVALID_REQUEST"})}c=Object.assign({data:l.data},s);let h={};"function"==typeof o&&(h.progress=o),Object.keys(h).length&&Object.assign(a,{fetchOptions:h});let d=await ft.bind(this)("post-record",c,a);if(ue()&&u.length){let e=new FormData;for(let t of u)e.append(t.name,t.file,t.file.name);let t={record_id:d.rec,progress:o};s.hasOwnProperty("service")&&(t.service=s.service);let{bin_endpoints:n}=await mt.bind(this)(e,t);d.bin?d.bin.push(...n):d.bin=n}r&&"string"==typeof d?.reference_private_key&&(this.__private_access_key[r]=d.reference_private_key),window.sessionStorage.setItem(`${this.service}:post:${d.rec}`,JSON.stringify(d));let f=await kt.bind(this)(d,"called from postRecord");return f.unique_id&&(this.__my_unique_ids[f.unique_id]=f.record_id,window.sessionStorage.setItem(`${this.service}:uniqueids`,JSON.stringify(this.__my_unique_ids))),f}async function xt(e){if(await this.__connection,!Array.isArray(e)||!e.length)throw new te('"params" should be a non-empty array.',{code:"INVALID_PARAMETER"});let t,n,r=!this.__user,i=[],s=null,o=e=>{if(null===e)return null;if("number"==typeof e){if(0>e)throw new te('"reference_limit" should be >= 0',{code:"INVALID_PARAMETER"});if(e>4503599627370546)throw new te('"reference_limit" should be <= 4503599627370546',{code:"INVALID_PARAMETER"});return e}throw new te('"reference_limit" should be type: <number | null>',{code:"INVALID_PARAMETER"})},a=e.map((e,a)=>{if(!e||"object"!=typeof e||Array.isArray(e))throw new te(`"params[${a}]" should be type: <object>.`,{code:"INVALID_PARAMETER"});if("string"==typeof e.table&&(e.table={name:e.table}),!e.record_id){if(!e.table||"object"!=typeof e.table)throw new te('"table.name" is required.',{code:"INVALID_PARAMETER"});Object.prototype.hasOwnProperty.call(e.table,"access_group")||(e.table.access_group=0)}e.table?.subscription&&(e.table?.subscription?.is_subscription_record?Object.assign(e.table.subscription,{group:1}):!1!==e.table?.subscription?.is_subscription_record&&(e.record_id||e.table.subscription?.is_subscription_record)||Object.assign(e.table.subscription,{group:null}),delete e.table.subscription?.is_subscription_record);let c=ve.Params(e||{},{record_id:["string",()=>{if(!e.table||!e.table.name)throw new te('"table.name" is required.',{code:"INVALID_PARAMETER"})}],unique_id:"string",readonly:"boolean",data:e=>e,table:{name:e=>St(e,"table.name"),subscription:{group:e=>1===e?1:null,upload_to_feed:"boolean",notify_subscribers:"boolean",feed_referencing_records:"boolean",notify_referencing_records:"boolean"},access_group:Dt.bind(this)},source:{referencing_limit:o,prevent_multiple_referencing:"boolean",can_remove_referencing_records:"boolean",only_granted_can_reference:"boolean",allow_granted_to_grant_others:"boolean",referencing_index_restrictions:e=>{if(void 0===e)return;if(!e)return null;if(Array.isArray(e)&&!e.length)return null;let t={name:[e=>Tt(e,'"name" in "index_restrictions"')],value:e=>Ut(e),condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne",()=>null],range:t=>{if(null!==t&&typeof e.value!=typeof t)throw new te('Index restriction "range" type should match the type of "value".',{code:"INVALID_PARAMETER"});if(!e.hasOwnProperty("value"))throw new te('Index restriction "value" is required.',{code:"INVALID_PARAMETER"});return t}};Array.isArray(e)||(e=[e]);let n=e.map(e=>ve.Params(e,t));if(n.length)for(let e of n)e.condition&&e.hasOwnProperty("range")&&delete e.range;return n}},reference:t=>{if(null===t)return{record_id:null};if(t){if("string"==typeof t)return this.__my_unique_ids[t]?this.__my_unique_ids[t]:(i.push(t),t);if("object"!=typeof t)throw new te('"reference" should be type: <string | object>.',{code:"INVALID_PARAMETER"});return ve.Params(t,{unique_id:"string",record_id:t=>null==t?t:(i.push(t),"string"==typeof this.__private_access_key?.[t]&&(e.reference_private_key=this.__private_access_key[t]||void 0),ve.specialChars(t,'"reference.record_id"',!1,!1))})}},index:{name:e=>Tt(e,"index.name"),value:e=>Ut(e)},tags:e=>{if(null==e)return e;if("string"==typeof e&&(e=e.split(",").map(e=>e.trim())),!Array.isArray(e))throw new te('"tag" should be type: <string | string[]>.',{code:"INVALID_PARAMETER"});return e.map(e=>It(e,"tag"))},remove_bin:e=>{if(!e)return null;let t=[];if(!Array.isArray(e))throw new te('"remove_bin" should be type: <string[] | BinaryFile[] | null>',{code:"INVALID_PARAMETER"});for(let n of e)if("string"==typeof n)t.push(decodeURIComponent(n.split("?")[0]));else{if(!(n.url&&n.size&&n.filename))throw new te('"remove_bin" should be type: <string[] | BinaryFile[] | null>',{code:"INVALID_PARAMETER"});{let e=n.url.split("/").slice(0,3).join("/")+"/"+n.path;t.push(e)}}return t},progress:"function"});if(r){if(c.record_id)throw new te("Public users cannot update existing records.",{code:"INVALID_REQUEST"});if("public"!==c.table.access_group&&0!==c.table.access_group)throw new te("Public users can only post records to public tables.",{code:"INVALID_REQUEST"});if(c.table.subscription)throw new te("Public users cannot post subscription records.",{code:"INVALID_REQUEST"});if(c.remove_bin)throw new te("Public users cannot remove files from records.",{code:"INVALID_REQUEST"});if(c.unique_id)throw new te("Public users cannot set unique_id for records.",{code:"INVALID_REQUEST"})}if("function"==typeof c.progress&&null===s&&(s=c.progress),void 0!==c.service)if(void 0===t)t=c.service;else if(t!==c.service)throw new te('All bulk params should share the same "service" value.',{code:"INVALID_PARAMETER"});if(void 0!==c.owner)if(void 0===n)n=c.owner;else if(n!==c.owner)throw new te('All bulk params should share the same "owner" value.',{code:"INVALID_PARAMETER"});return delete c.progress,delete c.service,delete c.owner,c}),c={_is_bulk_:a};void 0!==t&&(c.service=t),void 0!==n&&(c.owner=n);let u={auth:!!this.__user,method:"post"},l={};"function"==typeof s&&(l.progress=s),Object.keys(l).length&&Object.assign(u,{fetchOptions:l});let h=await ft.bind(this)("bulk-records",c,u),d=await Promise.all(h.map(e=>kt.bind(this)(e,"called from postRecord")));for(let e=0;e<h.length;e++){let t=h[e],n=d[e];if(t?.rec&&window.sessionStorage.setItem(`${this.service}:post:${t.rec}`,JSON.stringify(t)),"string"==typeof t?.reference_private_key)for(let e of i)this.__private_access_key[e]=t.reference_private_key;n?.unique_id&&(this.__my_unique_ids[n.unique_id]=n.record_id)}return Object.keys(this.__my_unique_ids).length&&window.sessionStorage.setItem(`${this.service}:uniqueids`,JSON.stringify(this.__my_unique_ids)),d}async function Ft(e,t){let n=await ft.bind(this)("get-table",ve.Params(e||{},{table:"string",condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}),Object.assign({auth:!!this.__user},{fetchOptions:t})),r={cnt_rec:"number_of_records",tbl:"table",srvc:"service"};if(Array.isArray(n?.list))for(let e of n.list)for(let t in r)e.hasOwnProperty(t)&&(e[r[t]]=e[t],delete e[t]);return n}async function qt(e,t){if(!e?.table)throw new te('"table" is required.',{code:"INVALID_PARAMETER"});let n=ve.Params(e||{},{table:"string",index:e=>Tt(e,"index.name"),order:{by:["average_number","total_number","number_count","average_bool","total_bool","bool_count","string_count","index_name","number_of_records"],value:["string","number","boolean"],condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}},["table"]);if(n.hasOwnProperty("order")){if(!n.order?.by)throw new te('"order.by" is required.',{code:"INVALID_PARAMETER"});if(n.order.hasOwnProperty("condition")&&!n.order.hasOwnProperty("value"))throw new te('"value" is required for "condition".',{code:"INVALID_PARAMETER"});if(n.hasOwnProperty("index")&&"."!==n.index.substring(n.index.length-1))throw new te('"index" should be a parent index name of the compound index when using "order.by"',{code:"INVALID_PARAMETER"})}let r=await ft.bind(this)("get-index",n,Object.assign({auth:!!this.__user},{fetchOptions:t})),i={cnt_bool:"boolean_count",cnt_numb:"number_count",totl_numb:"total_number",totl_bool:"total_bool",avrg_numb:"average_number",avrg_bool:"average_bool",cnt_str:"string_count"};return Array.isArray(r?.list)&&(r.list=r.list.map(e=>{let t=e.idx.split("/"),n={table:t[1],index:t[2],number_of_records:e.cnt_rec};for(let t in i)Object.prototype.hasOwnProperty.call(e,t)&&(n[i[t]]=e[t]);return n})),r}async function $t(e,t){let n=await ft.bind(this)("get-tag",ve.Params(e||{},{table:"string",tag:"string",condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}),Object.assign({auth:!!this.__user},{fetchOptions:t}));return Array.isArray(n?.list)&&(n.list=n.list.map(e=>{let t=e.tag.split("/");return{table:t[1],tag:t[0],number_of_records:e.cnt_rec}})),n}async function jt(e,t){let n=await ft.bind(this)("get-uniqueid",ve.Params(e||{},{unique_id:"string",condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}),Object.assign({auth:!!this.__user},{fetchOptions:t}));if(Array.isArray(n?.list))for(let e in n.list){let t=n.list[e];n.list[e]={unique_id:t.unq,record_id:t.rec}}return n}async function Bt(e,t){await this.__connection;let n=await Ot.bind(this)(e,!0),r=n.is_reference_fetch,i=await ft.bind(this)("del-records",n.query,{auth:!0,fetchOptions:t});return r&&"string"==typeof i?.reference_private_key&&(this.__private_access_key[r]=i.reference_private_key),i?.message||i}function Kt(e){return Qt.bind(this)({record_id:e.record_id,user_id:e.user_id,execute:"add"})}function Jt(e){return Qt.bind(this)({record_id:e.record_id,user_id:e.user_id||null,execute:"remove"})}async function Ht(e,t){let n={record_id:e.record_id||void 0,user_id:e.user_id||void 0,execute:"list"};if(!n.record_id&&!n.user_id)throw new te("Either record_id or user_id must be provided.",{code:"INVALID_PARAMETER"});if(n.user_id)if("string"==typeof n.user_id)ve.UserId(n.user_id),n.user_id=[n.user_id];else{if(!Array.isArray(n.user_id))throw new te("user_id should be type: <string | string[]>",{code:"INVALID_PARAMETER"});for(let e of n.user_id)ve.UserId(e)}let r=await ft.bind(this)("grant-private-access",n,{auth:!0,fetchOptions:t});return r.list=r.list.map(e=>(e.rec_usr?(e.record_id=e.rec_usr.split("/")[0],e.user_id=e.rec_usr.split("/")[1]):e.usr_rec&&(e.user_id=e.usr_rec.split("/")[0],e.record_id=e.usr_rec.split("/")[1]),e)),r}function Wt(e){let t=e.record_id,n=e.reference_id||void 0;if(!t)throw new te("Record ID is required.",{code:"INVALID_PARAMETER"});if("string"!=typeof t)throw new te("Record ID should be type: <string | string[]>",{code:"INVALID_PARAMETER"});if(n&&"string"!=typeof n)throw new te("Reference ID should be type: <string>",{code:"INVALID_PARAMETER"});if("string"==typeof this.__private_access_key[t])return Promise.resolve(this.__private_access_key[t]);if(Ct[t])return Ct[t];let r=ft.bind(this)("request-private-access-key",{record_id:t,reference_id:n},{auth:!0}).then(e=>{let n="string"==typeof e?e:e?.private_key;if("string"!=typeof n)throw new te("Invalid private access key response.",{code:"ERROR"});return this.__private_access_key[t]=n,n}).finally(()=>{delete Ct[t]});return Ct[t]=r,r}function Qt(e){e.execute;let t=ve.Params(e,{record_id:"string",user_id:e=>{if(!e)throw new te("User ID is required.",{code:"INVALID_PARAMETER"});let t=e;if("string"==typeof t&&(t=[t]),t.length>100)throw new te("Cannot process more than 100 users at once.",{code:"INVALID_REQUEST"});for(let e of t)ve.UserId(e,'User ID in "user_id"');return t},execute:["add","remove"]},["execute","record_id","user_id"]);return t.user_id||(t.user_id=null),ft.bind(this)("grant-private-access",t,{auth:!0})}const zt={},Gt={},Yt={},Zt={},Xt={};let en,tn={},nn={};function rn(e,t,n){e[t]||(e[t]=[]),e[t].push(n)}async function sn(e,t,n){let r=[];if(e[t]){for(let i of e[t])if(i){let e=n(i);e instanceof Promise&&(e=await e),r.push(e)}delete e[t]}return r}async function on(e,t){if(!this?.session?.accessToken?.jwtToken)throw new te("Access token is required.",{code:"INVALID_PARAMETER"});let n=await this.__socket;async function r(e,t,n){this.log("answerSdpOffer from",t),await zt[t].setRemoteDescription(new RTCSessionDescription(e));const r=await zt[t].createAnswer();await zt[t].setLocalDescription(r),n.send(JSON.stringify({action:"rtc",uid:t,content:{sdpanswer:r},token:this.session.accessToken.jwtToken}))}zt?.[t]?e?(await sn(nn,t,e=>r.bind(this)(e,t,n)),await r.bind(this)(e,t,n)):await sn(nn,t,e=>r.bind(this)(e,t,n)):e&&rn(nn,t,e)}async function an(e,t){if(this.log("receiveIceCandidate",e),zt?.[t]&&zt[t]?.remoteDescription&&zt[t]?.remoteDescription?.type){if(!e)return sn(tn,t,e=>zt[t].addIceCandidate(e));await sn(tn,t,e=>zt[t].addIceCandidate(e)),await zt[t].addIceCandidate(e)}else rn(tn,t,e)}async function cn(e){if("undefined"==typeof window||window._runningInNodeJS)throw new te("WebRTC is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});ve.Params(e,{cid:e=>{if("string"!=typeof e)throw new te('"cid" should be type: <string>.',{code:"INVALID_PARAMETER"});if(e&&"cid:"!==e.slice(0,4))throw new te('"cid" should be a valid connection id.',{code:"INVALID_PARAMETER"});return e},close:"boolean"});let t=await this.__socket,{cid:n,close_all:r=!1}=e||{};if(!r&&!n)throw new te('"cid" is required.',{code:"INVALID_PARAMETER"});let i=e=>{if(!e)throw new te('"cid" is required.',{code:"INVALID_PARAMETER"});if(delete nn[e],delete tn[e],Gt[e]&&Object.values(Gt[e]).forEach(e=>{"closed"!==e.readyState&&e.close()}),delete Gt[e],zt?.[e]){"closed"!==zt[e].connectionState&&(zt[e].close(),t.send(JSON.stringify({action:"rtc",uid:e,content:{hungup:this.user.user_id},token:this.session.accessToken.jwtToken})));let n={type:"connectionstatechange",target:zt[e],timestamp:(new Date).toISOString(),state:zt[e].connectionState,iceState:zt[e].iceConnectionState,signalingState:zt[e].signalingState};Xt[e]&&Xt[e](n),this.log("closeRTC",n)}delete Xt[e],delete Zt[e],delete Yt[e],delete zt[e]};if(r)for(let e in zt)i(e);else i(n);this.log("Cleaning up media stream..."),this.__mediaStream&&(this.__mediaStream.getTracks().forEach(e=>{e.stop()}),this.__mediaStream=null)}async function un(e){if(e instanceof MediaStream)return e;if(!e.video&&!e.audio){const e=new MediaStream,t=document.createElement("canvas");t.width=1,t.height=1;const n=t.captureStream().getVideoTracks()[0];return e.addTrack(n),e}return window.navigator.mediaDevices.getUserMedia(e)}async function ln(e,t){if("undefined"==typeof window||window._runningInNodeJS)throw new te("WebRTC is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if("function"!=typeof t)throw new te("Callback is required.",{code:"INVALID_PARAMETER"});if(!this?.session?.accessToken?.jwtToken)throw new te("Access token is required.",{code:"INVALID_PARAMETER"});e=ve.Params(e,{cid:e=>{if("string"!=typeof e)throw new te('"cid" should be type: <string>.',{code:"INVALID_PARAMETER"});if(e&&"cid:"!==e.slice(0,4))throw new te('"cid" should be a valid connection id.',{code:"INVALID_PARAMETER"});return e},ice:["string",()=>"stun:stun.skapi.com:3468"],media:e=>e,channels:["text-chat","file-transfer","video-chat","voice-chat","gaming",{ordered:"boolean",maxPacketLifeTime:"number",maxRetransmits:"number",protocol:"string"},()=>[{ordered:!0,maxPacketLifeTime:10,protocol:"default"}]]},["cid"]);let{cid:n,ice:r}=e;if(!(e?.media instanceof MediaStream)&&(e?.media?.video||e?.media?.audio)&&"localhost"!==window.location.hostname&&"https:"!==window.location.protocol)throw new te("Media stream is only supported on either localhost or https.",{code:"INVALID_REQUEST"});let i=this.__socket?await this.__socket:this.__socket;if(!i)throw new te("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});if(1!==i.readyState)throw new te("Realtime connection is not ready.",{code:"INVALID_REQUEST"});const s={iceServers:[{urls:r}]};zt?.[n]||(zt[n]=new RTCPeerConnection(s)),e?.media&&(this.__mediaStream=await un(e.media),this.__mediaStream.getTracks().forEach(e=>{zt[n].addTrack(e,this.__mediaStream)})),Xt[n]=t,Gt[n]||(Gt[n]={});for(let t=0;t<e.channels.length;t++){let r=e.channels[t];if("string"==typeof r)switch(r){case"text-chat":r={ordered:!0,maxRetransmits:10,protocol:"text-chat"};break;case"file-transfer":r={ordered:!1,maxPacketLifeTime:3e3,protocol:"file-transfer"};break;case"video-chat":r={ordered:!0,maxRetransmits:10,protocol:"video-chat"};break;case"voice-chat":r={ordered:!0,maxRetransmits:10,protocol:"voice-chat"};break;case"gaming":r={ordered:!1,maxPacketLifeTime:100,protocol:"gaming"};break;default:r={ordered:!0,maxRetransmits:10,protocol:"default"}}let i=r.protocol||"default";if(Object.keys(Gt[n]).includes(i))throw new te(`Data channel with the protocol "${i}" already exists.`,{code:"INVALID_REQUEST"});let s=zt[n].createDataChannel(i,r);Gt[n][i]=s}for(let e in Gt[n]){let t=Gt[n][e];gn.bind(this)(n,t)}return pn.bind(this)(n,["onnegotiationneeded"]),await dn.bind(this)(n),{hangup:()=>Yt[n]&&Yt[n](!1),connection:new Promise(e=>{Yt[n]=(t=>{if(this.log("receiver picked up the call",n),!t)return cn.bind(this)({cid:n}),null;zt[n].onnegotiationneeded=()=>{this.log("onnegotiationneeded",`sending offer to "${n}".`),dn.bind(this)(n),Xt[n]&&Xt[n]({type:"negotiationneeded",target:zt[n],timestamp:(new Date).toISOString(),signalingState:zt[n].signalingState,connectionState:zt[n].iceConnectionState,gatheringState:zt[n].iceGatheringState})},e({target:zt[n],channels:Gt[n],hangup:()=>cn.bind(this)({cid:n}),media:this.__mediaStream})}).bind(this)})}}function hn(e){return async(t,n)=>{t=fe(t=t||{}).data;let r=e.sender_cid,i=await this.__socket;if(!Zt[r])return null;if("function"!=typeof n)throw new te("Callback is required.",{code:"INVALID_PARAMETER"});if(!(t?.media instanceof MediaStream)&&(t?.media?.video||t?.media?.audio)&&"localhost"!==window.location.hostname&&"https:"!==window.location.protocol)throw new te("Media stream is only supported on either localhost or https.",{code:"INVALID_REQUEST"});let{ice:s="stun:stun.skapi.com:3468"}=t;return zt?.[r]||(zt[r]=new RTCPeerConnection({iceServers:[{urls:s}]})),t?.media&&(this.__mediaStream=await un(t.media),this.__mediaStream.getTracks().forEach(e=>{zt[r].addTrack(e,this.__mediaStream)})),delete Zt[r],Xt[r]=n,Gt[r]||(Gt[r]={}),zt[r].ondatachannel=e=>{this.log("ondatachannel",`received data channel "${e.channel.label}".`);const t=e.channel;Gt[r][t.label]=t,gn.bind(this)(r,t)},pn.bind(this)(r,["onnegotiationneeded"]),await on.bind(this)(null,r),await an.bind(this)(null,r),i.send(JSON.stringify({action:"rtc",uid:r,content:{pickup:this.user.user_id},token:this.session.accessToken.jwtToken})),{target:zt[r],channels:Gt[r],hangup:()=>cn.bind(this)({cid:r}),media:this.__mediaStream}}}async function dn(e){if(!this?.session?.accessToken?.jwtToken)throw new te("Access token is required.",{code:"INVALID_PARAMETER"});this.log("sendOffer",e);let t=await this.__socket;const n=await zt[e].createOffer();await zt[e].setLocalDescription(n);let r=zt[e].localDescription;this.log("rtcSdpOffer to",r),t.send(JSON.stringify({action:"rtc",uid:e,content:{sdpoffer:r},token:this.session.accessToken.jwtToken}))}async function fn(e,t){if(!this?.session?.accessToken?.jwtToken)throw new te("Access token is required.",{code:"INVALID_PARAMETER"});this.log("sendIceCandidate to",t);let n=await this.__socket;if(!e.candidate)return void this.log("candidate-end","all ice candidates have been sent");let r=Xt[t]||(()=>{}),i=e.candidate;this.log("ice gathering state set to",zt[t].iceGatheringState),r({type:"icecandidate",target:zt[t],timestamp:(new Date).toISOString(),candidate:e.candidate.candidate,sdpMid:e.candidate.sdpMid,sdpMLineIndex:e.candidate.sdpMLineIndex,usernameFragment:e.candidate.usernameFragment,protocol:e.candidate.protocol,gatheringState:zt[t].iceGatheringState,connectionState:zt[t].iceConnectionState}),n.send(JSON.stringify({action:"rtc",uid:t,content:{candidate:i},token:this.session.accessToken.jwtToken}))}function pn(e,t){let n=new Set(t),r=Xt[e]||(e=>{}),i=zt[e];const s={ontrack:e=>{r({type:"track",target:i,timeStamp:e.timeStamp,streams:e.streams,track:e.track})},onicecandidate:t=>{fn.bind(this)(t,e),t.candidate?r({type:"icecandidate",target:i,timestamp:(new Date).toISOString(),candidate:t.candidate.candidate,sdpMid:t.candidate.sdpMid,sdpMLineIndex:t.candidate.sdpMLineIndex,usernameFragment:t.candidate.usernameFragment,protocol:t.candidate.protocol,gatheringState:i.iceGatheringState,connectionState:i.iceConnectionState}):r({type:"icecandidateend",target:i,timestamp:(new Date).toISOString()})},onicecandidateerror:e=>{r({type:"icecandidateerror",target:i,timestamp:(new Date).toISOString(),errorCode:e.errorCode,errorText:e.errorText,url:e.url,hostCandidate:e.hostCandidate,gatheringState:i.iceGatheringState,connectionState:i.iceConnectionState})},oniceconnectionstatechange:()=>{r({type:"iceconnectionstatechange",target:i,timestamp:(new Date).toISOString(),state:i.iceConnectionState,gatheringState:i.iceGatheringState,signalingState:i.signalingState})},onicegatheringstatechange:()=>{r({type:"icegatheringstatechange",target:i,timestamp:(new Date).toISOString(),state:i.iceGatheringState,connectionState:i.iceConnectionState,signalingState:i.signalingState})},onsignalingstatechange:()=>{r({type:"signalingstatechange",target:i,timestamp:(new Date).toISOString(),state:i.signalingState,connectionState:i.iceConnectionState,gatheringState:i.iceGatheringState})},onnegotiationneeded:()=>{dn.bind(this)(e),r({type:"negotiationneeded",target:i,timestamp:(new Date).toISOString(),signalingState:i.signalingState,connectionState:i.iceConnectionState,gatheringState:i.iceGatheringState})},onconnectionstatechange:()=>{r({type:"connectionstatechange",target:i,timestamp:(new Date).toISOString(),state:i.connectionState,iceState:i.iceConnectionState,signalingState:i.signalingState});let t=i.connectionState;"disconnected"!==t&&"failed"!==t&&"closed"!==t||cn.bind(this)({cid:e})}};for(const[e,t]of Object.entries(s))n.has(e)||(i[e]=t)}function gn(e,t,n){let r=new Set(n),i=Xt[e]||(e=>{});const s={onmessage:e=>{let n={type:e.type,target:t,timeStamp:e.timeStamp,data:e.data,lastEventId:e.lastEventId,origin:e.origin,readyState:t.readyState,bufferedAmount:t.bufferedAmount};this.log(`${t.label}: message`,e.data),i(n)},onerror:e=>{let n={type:e.type,target:t,timeStamp:e.timeStamp,error:e.error.message,errorCode:e.error.errorDetail,readyState:t.readyState,label:t.label};this.log(`${t.label}: error`,e.error.message),i(n)},onclose:n=>{let r={type:n.type,target:t,timeStamp:n.timeStamp,readyState:t.readyState,label:t.label,id:t.id};this.log(`${t.label}: closed`,null),i(r),Gt[e]&&(delete Gt[e][t.label],0===Object.keys(Gt[e]).length&&cn.bind(this)({cid:e}))},onbufferedamountlow:e=>{let n={target:t,bufferedAmount:t.bufferedAmount,bufferedAmountLowThreshold:t.bufferedAmountLowThreshold,type:e.type,timeStamp:e.timeStamp};this.log(`${t.label}: bufferedamountlow`,t.bufferedAmount),i(n)},onopen:e=>{this.log("dataChannel",`data channel: "${t.label}" is open and ready to send messages.`);let n={type:e.type,target:t,timeStamp:e.timeStamp,readyState:t.readyState,label:t.label,id:t.id,ordered:t.ordered,maxRetransmits:t.maxRetransmits,protocol:t.protocol};i(n)}};for(const[e,n]of Object.entries(s))r.has(e)||(t[e]=n)}let _n=null,mn=!0,yn=0;async function wn(){if("undefined"==typeof window||window._runningInNodeJS)throw new te("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.getProfile(),!this.session)throw new te("No access.",{code:"INVALID_REQUEST"});let e=await this.record_endpoint;return new WebSocket(e.websocket_private+"?token="+this.session.accessToken.jwtToken)}let bn=null;async function An(){if("undefined"==typeof window||window._runningInNodeJS)throw new te("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});mn=!0;let e=this.__socket?await this.__socket:this.__socket;cn.bind(this)({close_all:!0}),en&&Sn.bind(this)({group:null}),yn=0,_n&&(_n.terminate(),_n=null);try{e&&e.close()}catch(e){}return window.removeEventListener("visibilitychange",bn),this.__socket=null,null}async function vn(e,t=50,n){if("undefined"==typeof window||window._runningInNodeJS)throw new te("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if("function"!=typeof e)throw new te("Callback must be a function.",{code:"INVALID_REQUEST"});if("reconnect"===n){if(this.__socket instanceof Promise){let e=await this.__socket;if(e.readyState!==WebSocket.CLOSED&&e.readyState!==WebSocket.CLOSING)return this.__socket}}else if(mn&&(bn=()=>{document.hidden||mn||vn.bind(this)(e,0,"reconnect")},this.__socket instanceof Promise))return this.__socket;_n&&(_n.terminate(),_n=null),this.__socket=new Promise(async r=>{await Pe.bind(this)(),setTimeout(async()=>{let t=await wn.bind(this)();t.onopen=()=>{mn=!1,yn=0,"reconnect"!==n&&window.addEventListener("visibilitychange",bn),this.log("realtime onopen","Connected to WebSocket server."),e({type:"success",message:"Connected to WebSocket server."}),en&&t.send(JSON.stringify({action:"joinRoom",rid:en,token:this.session.accessToken.jwtToken}));const i=new Blob(['\n let interval = 15000; // Set interval time 15 seconds\n\n function runInterval() {\n postMessage({ type: "ping" });\n setTimeout(runInterval, interval); // Use setTimeout instead of setInterval\n }\n\n runInterval(); // Start interval\n '],{type:"application/javascript"});_n=new Worker(URL.createObjectURL(i)),_n.onmessage=e=>{1===t.readyState&&t.send(JSON.stringify({action:"keepAlive"}))},r(t)},t.onmessage=async n=>{let r,i="";try{i=JSON.parse(decodeURI(n.data)),this.log("socket onmessage",i)}catch(e){return}switch(!0){case!!i?.["#message"]:r="message";break;case!!i?.["#private"]:r="private";break;case!!i?.["#notice"]:r="notice";break;case!!i?.["#rtc"]:r="rtc";break;case!!i?.["#error"]:r="error"}if(!r)return;let s={type:r,message:i?.["#rtc"]||i?.["#message"]||i?.["#private"]||i?.["#notice"]||i?.["#error"]||null,sender:i?.["#user_id"]||null,sender_cid:i?.["#scid"]?"cid:"+i["#scid"]:null,sender_rid:i?.["#srid"]||null,code:i?.["#code"]||null};if("notice"===r)e(s);else if("rtc"===r){if(s.sender!==this.user.user_id){let n=s.message;if(n.hungup)return Yt[s.sender_cid]&&(Yt[s.sender_cid](!1),delete Yt[s.sender_cid]),Zt[s.sender_cid]&&delete Zt[s.sender_cid],zt?.[s.sender_cid]&&cn.bind(this)({cid:s.sender_cid}),s.type="rtc:closed",void e(s);if(n.candidate&&an.bind(this)(n.candidate,s.sender_cid),n.sdpoffer&&(on.bind(this)(n.sdpoffer,s.sender_cid),Zt[s.sender_cid]||(Zt[s.sender_cid]=s.sender_cid,delete s.message,s.connectRTC=hn.bind(this)(s),s.type="rtc:incoming",s.hangup=(()=>{zt[s.sender_cid]?cn.bind(this)({cid:s.sender_cid}):Zt[s.sender_cid]&&(delete Zt[s.sender_cid],t.send(JSON.stringify({action:"rtc",uid:s.sender_cid,content:{hungup:this.user.user_id},token:this.session.accessToken.jwtToken})))}).bind(this),e(s))),n.pickup&&Yt[s.sender_cid]&&(Yt[s.sender_cid](!0),delete Yt[s.sender_cid]),n.sdpanswer&&zt[s.sender_cid]){if("have-local-offer"!==zt[s.sender_cid].signalingState)throw new te("Invalid signaling state.",{code:"INVALID_REQUEST"});await zt[s.sender_cid].setRemoteDescription(new RTCSessionDescription(n.sdpanswer))}}}else e(s)},t.onclose=()=>{mn?(this.log("realtime onclose","WebSocket connection closed."),e({type:"close",message:"WebSocket connection closed."})):(this.log("realtime onclose","WebSocket unexpected close."),e({type:"error",message:"Skapi: WebSocket unexpected close."}),yn++,yn<3?(this.log("realtime onclose","Reconnecting to WebSocket server..."+yn),e({type:"reconnect",message:"Reconnecting to WebSocket server..."+yn}),vn.bind(this)(e,3e3,"reconnect")):(this.log("realtime onclose","Max reconnection attempts reached."),e({type:"error",message:"Skapi: Max reconnection attempts reached."})))},t.onerror=()=>{this.log("realtime onerror","WebSocket connection error."),e({type:"error",message:"Skapi: WebSocket connection error."})}},t)})}async function En(e,t,n){if("undefined"==typeof window||window._runningInNodeJS)throw new te("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});let r=this.__socket?await this.__socket:this.__socket;if(!r)throw new te("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});if(!t)throw new te("No recipient.",{code:"INVALID_REQUEST"});await Pe.bind(this)(),e=fe(e).data;let i="";if(n&&(n=ve.Params(n,{config:{always:"boolean"},title:"string",body:"string"},["title","body"]),i=JSON.stringify({title:n.title,body:n.body}),new Blob([i]).size>3072))throw new te("Notification size exceeds 3kb.",{code:"INVALID_PARAMETER"});if(1===r.readyState){try{ve.UserId(t),r.send(JSON.stringify({action:"sendMessage",uid:t,content:e,notification:i,notificationConfig:n?.config||{},token:`IdT:${this.service}:${this.owner}:`+(this.bearerToken||this.session?.idToken?.jwtToken||"null")}))}catch(s){if(this.log("postRealtime:err",{err:s}),en!==t)throw new te(`User has not joined to the recipient group. Run joinRealtime({ group: "${t}" })`,{code:"INVALID_REQUEST"});r.send(JSON.stringify({action:"broadcast",rid:t,content:e,notification:i,notificationConfig:n?.config||{},token:`IdT:${this.service}:${this.owner}:`+(this.bearerToken||this.session?.idToken?.jwtToken||"null")}))}return{type:"success",message:"Message sent."}}throw new te("Realtime connection is not open. Try reconnecting with connectRealtime().",{code:"INVALID_REQUEST"})}async function Sn(e){if("undefined"==typeof window||window._runningInNodeJS)throw new te("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});let t=this.__socket?await this.__socket:this.__socket;if(!t)throw new te("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});await Pe.bind(this)(),e=fe(e,{nullIfEmpty:!0}).data;let{group:n=null}=e;if(!n&&!en)return{type:"success",message:"Left realtime message group."};if(null!==n&&"string"!=typeof n)throw new te('"group" must be a string | null.',{code:"INVALID_PARAMETER"});return t.send(JSON.stringify({action:"joinRoom",rid:n,token:this.session.accessToken.jwtToken})),en=n,{type:"success",message:n?`Joined realtime message group: "${n}".`:"Left realtime message group."}}async function In(e,t){e=ve.Params(e,{user_id:e=>ve.UserId(e,'User ID in "user_id"'),group:["string",()=>{if(!en)throw new te('No group has been joined. Otherwise "group" is required.',{code:"INVALID_REQUEST"});return en}]});let n=await ft.bind(this)("get-ws-group",e,{fetchOptions:t,auth:!0,method:"post"});return n.list=n.list.map(e=>({user_id:e.uid.split("#")[1],cid:"cid:"+e.cid})),n}async function Tn(e,t){if(await this.__connection,e||(e={searchFor:"group",value:" ",condition:">"}),(e=ve.Params(e,{searchFor:["group","number_of_users",()=>"group"],value:["string","number",()=>e?.searchFor&&"number_of_users"===e?.searchFor?0:" "],condition:[">",">=","=","<","<=","!=","gt","gte","eq","lt","lte","ne"],range:["string","number"]})).condition||(" "!==e.value&&e.value?e.condition="=":e.condition=">"),e.range&&e.condition&&delete e.condition,"number_of_users"===e.searchFor&&"number"!=typeof e.value)throw new te('"value" must be a number.',{code:"INVALID_PARAMETER"});if("group"===e.searchFor&&"string"!=typeof e.value)throw new te('"value" must be a string.',{code:"INVALID_PARAMETER"});if(e.hasOwnProperty("range")&&typeof e.range!=typeof e.value)throw new te(`"range" must be a ${typeof e.value}.`,{code:"INVALID_PARAMETER"});let n=await ft.bind(this)("get-ws-group",e,{fetchOptions:t,auth:!0,method:"post"});return n.list=n.list.map(e=>({group:e.rid.split("#")[1],number_of_users:e.cnt})),n}const Rn="undefined"!=typeof FormData,Dn="undefined"!=typeof HTMLFormElement,Un="undefined"!=typeof SubmitEvent;async function Pn(e){let t=!1,n=e=>{for(let n in e)if("string"==typeof e[n]&&e[n].includes("$CLIENT_SECRET")){t=!0;break}};if(e=ve.Params(e,{url:e=>{if(!e||"string"!=typeof e)throw new te('"url" should be type: <string>.',{code:"INVALID_PARAMETER"});return ve.Url(e),e.includes("$CLIENT_SECRET")&&(t=!0),e},clientSecretName:"string",method:e=>{if(e&&"string"!=typeof e)throw new te('"method" should be either "GET" or "POST" or "DELETE" or "PUT".',{code:"INVALID_PARAMETER"});let t=e.toLowerCase();if("get"!==t&&"post"!==t&&"delete"!==t&&"put"!==t)throw new te('"method" should be either "GET" or "POST" or "DELETE" or "PUT".',{code:"INVALID_PARAMETER"});return t},headers:e=>{if(e&&"object"!=typeof e)throw new te('"headers" should be type: <object>.',{code:"INVALID_PARAMETER"});return n(e),e},data:e=>{if(e&&"object"!=typeof e)throw new te('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return n(e),e},params:e=>{if(e&&"object"!=typeof e)throw new te('"params" should be type: <object>.',{code:"INVALID_PARAMETER"});return n(e),e}},["clientSecretName","method","url"]),!t)throw new te(`At least one parameter value should include "$CLIENT_SECRET" in ${"post"===e.method.toLowerCase()?'"data"':'"params"'} or "headers".`,{code:"INVALID_PARAMETER"});await this.__connection;let r=!!this.__user;return ft.bind(this)("csr",e,{auth:r})}async function Cn(e){await this.__connection;let t={name:"string",email:e=>(ve.Email(e),e),subject:"string",message:"string"};return e=ve.Params(e,t,["name","email","subject","message"]),await ft.bind(this)("send-inquiry",e),"SUCCESS: Inquiry has been sent."}async function kn(e,t){if(await this.__connection,Rn&&e instanceof FormData||Dn&&e instanceof HTMLFormElement||Un&&e instanceof SubmitEvent){if(!t)throw new te("Url string as a second argument is required when form is passed.",{code:"INVALID_PARAMETER"});e={url:t,data:fe(e).data,sync:!0}}let n={url:e=>ve.Url(e),data:e=>e,sync:["boolean",()=>!0]};if(Array.isArray(e))for(let t of e)t=ve.Params(t,n);else e=ve.Params(e,n);return ft.bind(this)("post-secure",e,{auth:!0})}async function Nn(e,t){await this.__connection;let{auth:n=!1,method:r="POST",bypassAwaitConnection:i=!1,responseType:s,contentType:o,progress:a}=t||{};if(t=Object.assign({auth:n,method:r,bypassAwaitConnection:i,responseType:s,contentType:o},{fetchOptions:{progress:a}}),"object"!=typeof e&&("application/json"===o||void 0===o))throw new te('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return ft.bind(this)("mock",e,t)}async function Ln(e,t){await this.__connection,e=ve.Params(e||{},{access_group:e=>{if("authorized"===e&&(e=1),"public"===e&&(e=0),"number"!=typeof e)throw new te('"access_group" should be type number.',{code:"INVALID_PARAMETER"});if(e<0)throw new te('"access_group" should be zero or a positive number.',{code:"INVALID_PARAMETER"});if(e>this.__user.access_group)throw new te("User has no access.",{code:"INVALID_REQUEST"});return e}});let n=await ft.bind(this)("get-feed",e,{auth:!0,fetchOptions:t});for(let e in n.list)n.list[e]=await kt.bind(this)(n.list[e]);return n}function On(e){if(e===this.__user.user_id)throw new te('"user_id" cannot be the user\'s own ID.',{code:"INVALID_PARAMETER"});return ve.UserId(e,'"user_id"')}async function Mn(e,t){if(e=fe(e,{ignoreEmpty:!0}).data,!(e=ve.Params(e,{subscriber:e=>ve.UserId(e,'User ID in "subscriber"'),subscription:On.bind(this),blocked:"boolean"})).subscriber&&!e.subscription)throw new te('At least either "subscriber" or "subscription" should have a value.',{code:"INVALID_PARAMETER"});let n=await ft.bind(this)("get-subscription",e,Object.assign({auth:!0},{fetchOptions:t}));return n.list=n.list.map(e=>{let t={};if(e.sub){let n=e.sub.split("#");t.subscriber=n[2],t.subscription=n[0]}else t.subscriber=e.subscriber,t.subscription=e.subscription;return t.timestamp=e?.timestamp||e.stmp,t.blocked=e?.blocked||"N"===e.grp.substring(0,1),Object.assign(t,e.opt),t}),n}async function Vn(e){await this.__connection,e=ve.Params(e,{user_id:On.bind(this),get_feed:["boolean",()=>!1],get_notified:["boolean",()=>!1],get_email:e=>{if(e&&!this.__user.email||!this.__user.email_verified)throw new te("User has no verified email address.",{code:"INVALID_REQUEST"});return!!e}},["user_id"]);let t=await ft.bind(this)("subscription",{subscribe:e.user_id,option:{get_feed:e.get_feed,get_notified:e.get_notified,get_email:e.get_email||!1}},{auth:!0}),n={};if(t.sub){let e=t.sub.split("#");n.subscriber=e[2],n.subscription=e[0]}else n.subscriber=t.subscriber,n.subscription=t.subscription;return n.timestamp=t?.timestamp||t.stmp,n.blocked=t?.blocked||"N"===t.grp.substring(0,1),Object.assign(n,t.opt),n}async function xn(e){await this.__connection;let{user_id:t}=ve.Params(e,{user_id:On.bind(this)},["user_id"]);return await ft.bind(this)("subscription",{unsubscribe:t},{auth:!0})}async function Fn(e){await this.__connection;let{user_id:t}=ve.Params(e,{user_id:On.bind(this)},["user_id"]);return await ft.bind(this)("subscription",{block:t},{auth:!0})}async function qn(e){await this.__connection;let{user_id:t}=ve.Params(e,{user_id:On.bind(this)},["user_id"]);return await ft.bind(this)("subscription",{unblock:t},{auth:!0})}async function $n(e,t){await this.__connection;let n=await Ve.bind(this)();e=ve.Params(e,{user_id:e=>{if(e!==this.__user.user_id&&!n)throw new te("No access.",{code:"INVALID_REQUEST"});return e},group:e=>{if("public"===e&&(e=0),"authorized"===e&&(e=1),"number"!=typeof e)throw new te('"group" should be type number | "public" | "authorized".',{code:"INVALID_PARAMETER"});return e}});let r=await ft.bind(this)("get-newsletter-subscription",e,{auth:!0,fetchOptions:t||null}),i=r?.list||r,s=[];Array.isArray(i)||(i=[]);for(let e of i){let t=e.subt.split("#"),n=!0;"@"===t[0].charAt(0)&&(n=!1,t[0]=t[0].substring(1));let r=parseInt(t[0]);s.push({timestamp:e.stmp,group:r,subscribed_email:t[1],active:n})}return r?.list?(r.list=s,r):s}async function jn(e){await this.__connection;let t=ve.Params(e||{},{email:e=>Array.isArray(e)&&e.length>0?1===e.length?ve.Email(e[0]):e.map(e=>ve.Email(e)):ve.Email(e),group:["number","public","authorized","admin",e=>{if("string"!=typeof e||e.length>20||!/^[a-zA-Z0-9]+$/.test(e))throw new te('"group" should be an alphanumeric string without spaces and less than 20 characters.',{code:"INVALID_PARAMETER"});return e}],redirect:e=>ve.Url(e)},this.__user?["group"]:["email","group"]);return ft.bind(this)(`subscribe-${this.__user?"":"public-"}newsletter`,t,{auth:!!this.__user})}async function Bn(e){await this.__connection,e=ve.Params(e,{group:["number","public","authorized","admin"]},["group"]);let t=Object.assign({action:"unsubscribe"},e);return ft.bind(this)("subscribe-newsletter",t,{auth:!0})}async function Kn(e,t){let n=await Ve.bind(this)(),r={message_id:"string",timestamp:"number",read:"number",complaint:"number",subject:"string",bounced:"number"};e||(t=Object.assign({ascending:!1},t||{})),e=(e=fe(e).data)||{searchFor:"timestamp",value:Date.now(),condition:"<",group:"public"};let i=0===(e=ve.Params(e,{searchFor:["message_id","timestamp","subject","complaint","read","bounced"],value:t=>{if(typeof t!==r[e.searchFor])throw new te(`"value" type does not match the type of "${e.searchFor}" index.`,{code:"INVALID_PARAMETER"});if("string"==typeof t&&!t)throw new te('"value" should not be empty string.',{code:"INVALID_PARAMETER"});return t},range:t=>{if(!e.hasOwnProperty("value")||typeof t!=typeof e.value)throw new te('"range" should match type of "value".',{code:"INVALID_PARAMETER"});return t},condition:[">",">=","=","<","<=","gt","gte","eq","lt","lte",()=>"="],group:e=>{if("public"===e)return 0;if(!this.session)throw new te("User should be logged in.",{code:"INVALID_REQUEST"});if("authorized"===e)return 1;if("number"==typeof e){if(!n&&e>parseInt(this.user?.access_group||this.session?.idToken?.payload?.access_group))throw new te("User has no access.",{code:"INVALID_REQUEST"});return e}throw new te('"group" should be type: number | "public" | "authorized".',{code:"INVALID_PARAMETER"})}},["searchFor","value","group"])).group?"get-public-newsletters":"get-newsletters",s=await ft.bind(this)(i,e,Object.assign({method:"get",auth:"get-public-newsletters"!==i||!!this.__user},{fetchOptions:t})),o={message_id:"mid",timestamp:"stmp",complaint:"cmpl",read:"read",subject:"subj",bounced:"bnce",url:"url",delivered:"delv"},a={message_id:"",timestamp:0,complaint:0,read:0,subject:"",bounced:"",url:"",delivered:0};return s.list=s.list.map(e=>{let t={};for(let n in o)t[n]=e[o[n]]||a[n];return t.bounced=String(t.bounced),t}),s}async function Jn(e){let t=ve.Params(e,{user_id:e=>ve.UserId(e,'"user_id"')},["user_id"]);if(t=t?.service&&t?.owner?{service:t?.service,owner:t?.owner,block:t.user_id}:{block:t.user_id},!await Ve.bind(this)()){if(!this.__user)throw new te("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new te("Invalid access.",{code:"INVALID_REQUEST"})}return await ft.bind(this)("block-account",t,{auth:!0})}async function Hn(e){let t=ve.Params(e,{user_id:e=>ve.UserId(e,'"user_id"')},["user_id"]);if(t=t?.service&&t?.owner?{service:t?.service,owner:t?.owner,unblock:t.user_id}:{unblock:t.user_id},!await Ve.bind(this)()){if(!this.__user)throw new te("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new te("Invalid access.",{code:"INVALID_REQUEST"})}return await ft.bind(this)("block-account",t,{auth:!0})}async function Wn(e){let t=ve.Params(e,{user_id:e=>ve.UserId(e,'"user_id"')},["user_id"]);if(t=t?.service&&t?.owner?{service:t?.service,owner:t?.owner,delete:t.user_id}:{delete:t.user_id},!await Ve.bind(this)()){if(!this.__user)throw new te("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new te("Invalid access.",{code:"INVALID_REQUEST"})}return await ft.bind(this)("remove-account",t,{auth:!0})}async function Qn(e,t){let n={email:e=>ve.Email(e),password:e=>ve.Password(e),name:"string",username:"string",gender:"string",address:e=>e?"string"==typeof e?e:"object"==typeof e?JSON.stringify(e):void 0:"",birthdate:e=>ve.Birthdate(e),phone_number:e=>ve.PhoneNumber(e),picture:e=>e?ve.Url(e):void 0,profile:e=>e?ve.Url(e):void 0,website:e=>e?ve.Url(e):void 0,nickname:"string",misc:"string",email_public:["boolean",()=>!1],gender_public:["boolean",()=>!1],address_public:["boolean",()=>!1],birthdate_public:["boolean",()=>!1],phone_number_public:["boolean",()=>!1],openid_id:"string",access_group:e=>{try{"string"==typeof e&&(e="admin"===e?99:parseInt(e))}catch(e){throw new te('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if("number"!=typeof e||e<1||e>100)throw new te('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"});return e}},r=ve.Params(e,n,["email"]);if(t=ve.Params(t,{confirmation_url:e=>{let t=e;if("string"!=typeof e)throw new te('"options.confirmation_url" should be type: <string>.',{code:"INVALID_PARAMETER"});if(t=ve.Url(e),t&&!r.email)throw new te('"email" is required for signup confirmation.',{code:"INVALID_PARAMETER"});return t},email_subscription:e=>{if("boolean"!=typeof e)throw new te('"options.email_subscription" should be type: <boolean>.',{code:"INVALID_PARAMETER"});if(!t?.confirmation_url)throw new te('"options.confirmation_url" is required for email subscription.',{code:"INVALID_PARAMETER"});return e},template:e=>{if("object"!=typeof e||!e.url||!e.subject)throw new te('"options.template" should be type: <object> with "url" and "subject".',{code:"INVALID_PARAMETER"});return{url:ve.Url(e.url),subject:e.subject}}}),r.signup_confirmation=t?.confirmation_url||!0,r.email_subscription=t?.email_subscription||!1,r.template=t?.template||{},!await Ve.bind(this)()){if(!this.__user)throw new te("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new te("Invalid access.",{code:"INVALID_REQUEST"})}return await ft.bind(this)("admin-signup",r,{auth:!0})}async function zn(e){let t={email:e=>ve.Email(e),password:e=>ve.Password(e),openid_id:"string",name:"string",username:"string",gender:"string",address:e=>e?"string"==typeof e?e:"object"==typeof e?JSON.stringify(e):void 0:"",birthdate:e=>ve.Birthdate(e),phone_number:e=>ve.PhoneNumber(e),picture:e=>e?ve.Url(e):"",profile:e=>e?ve.Url(e):"",website:e=>e?ve.Url(e):"",nickname:"string",misc:"string",email_public:["boolean",()=>!1],gender_public:["boolean",()=>!1],address_public:["boolean",()=>!1],birthdate_public:["boolean",()=>!1],phone_number_public:["boolean",()=>!1],access_group:e=>{try{"string"==typeof e&&(e=parseInt(e))}catch(e){throw new te('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if("number"!=typeof e||e<1||e>100)throw new te('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"});return e}},n=ve.Params(e,t,["email","password"]);if(!await Ve.bind(this)()){if(!this.__user)throw new te("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new te("Invalid access.",{code:"INVALID_REQUEST"})}return await ft.bind(this)("admin-signup",n,{auth:!0})}async function Gn(e){if(e=ve.Params(e,{user_id:e=>ve.UserId(e,'"user_id"'),access_group:e=>{try{"string"==typeof e&&(e=parseInt(e))}catch(e){throw new te('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if("number"==typeof e&&e>0&&e<100)return e;throw new te('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"})}},["user_id","access_group"]),!await Ve.bind(this)()){if(!this.__user)throw new te("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new te("Invalid access.",{code:"INVALID_REQUEST"})}return await ft.bind(this)("grant-access",e,{auth:!0})}async function Yn(e,t){if(e=ve.Params(e,{email:"string"}),!await Ve.bind(this)()){if(!this.__user)throw new te("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new te("Invalid access.",{code:"INVALID_REQUEST"})}let n=await ft.bind(this)("invitation-list",Object.assign({mode:"search"},e),{fetchOptions:t,auth:!0});return n.list=n.list.map(e=>pe(e.user)),n}async function Zn(e){if(e=ve.Params(e,{email:e=>ve.Email(e)},["email"]),!await Ve.bind(this)()){if(!this.__user)throw new te("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new te("Invalid access.",{code:"INVALID_REQUEST"})}return await ft.bind(this)("invitation-list",Object.assign({mode:"cancel"},e),{auth:!0})}async function Xn(e){if(e=ve.Params(e,{email:e=>ve.Email(e)},["email"]),!await Ve.bind(this)()){if(!this.__user)throw new te("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new te("Invalid access.",{code:"INVALID_REQUEST"})}return await ft.bind(this)("invitation-list",Object.assign({mode:"resend"},e),{auth:!0})}async function er(e){if("undefined"==typeof window||window._runningInNodeJS)throw new te("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.__connection,!e.endpoint)throw new te("Missing parameter: endpoint",{code:"INVALID_PARAMETER"});if(!e.keys||!e.keys.p256dh||!e.keys.auth)throw new te("Missing parameter: keys.p256dh or keys.auth",{code:"INVALID_PARAMETER"});return await ft.bind(this)("store-subscription",{endpoint:e.endpoint,keys:e.keys},{auth:!0}),"SUCCESS: Subscribed to receive notifications."}async function tr(e){if("undefined"==typeof window||window._runningInNodeJS)throw new te("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.__connection,!e.endpoint)throw new te("Missing parameter: endpoint",{code:"INVALID_PARAMETER"});if(!e.keys||!e.keys.p256dh||!e.keys.auth)throw new te("Missing parameter: keys.p256dh or keys.auth",{code:"INVALID_PARAMETER"});return await ft.bind(this)("delete-subscription",{endpoint:e.endpoint,keys:e.keys},{auth:!0}),"SUCCESS: Unsubscribed from notifications."}async function nr(){if("undefined"==typeof window||window._runningInNodeJS)throw new te("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});return await this.__connection,{VAPIDPublicKey:await ft.bind(this)("get-vapid-public-key",null,{auth:!0})}}async function rr(e,t){if("undefined"==typeof window||window._runningInNodeJS)throw new te("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});await this.__connection;let{title:n,body:r}=fe(e||{},{nullIfEmpty:!0}).data;if(!n)throw new te("Missing parameter: message title",{code:"INVALID_PARAMETER"});if(!r)throw new te("Missing parameter: message body",{code:"INVALID_PARAMETER"});const i={title:n,body:r};return t?("string"==typeof t&&(t=[t]),i.user_ids=t):i.user_ids="all_users",await ft.bind(this)("push-notification",i,{auth:!0}),"SUCCESS: Notification sent."}async function ir(e){return await this.__connection,e=ve.Params(e,{spell:"string",name:"string",magic:e=>e},["spell","name"]),await ft.bind(this)("castspell",e),`The spell "${e.spell}" has been cast.`}async function sr(e){return await this.__connection,e=ve.Params(e||{},{search:["spell","name",()=>"spell"],value:"string"}),await ft.bind(this)("getspell",e)}async function or(e){await this.__connection,e=ve.Params(e,{message:"string",name:"string"},["message","name"]);let t=await ft.bind(this)("dopamine",e,{auth:!0}),n=t?.previous_message?.message,r=t?.previous_message?.name;if(!ue())return n&&r?`${r} said: ${n}\nWatch the video here: ${t.video}`:`Your message has been uploaded for future generations to receive.\nWatch the video here: ${t.video}`;n&&r&&window.alert(`${r} said: ${n}`),window.location.href=t.video}const ar=JSON.parse('{"rE":"1.2.14-beta.6"}');var cr=function(e,t,n,r){var i,s=arguments.length,o=s<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,n,o):i(t,n))||o);return s>3&&o&&Object.defineProperty(t,n,o),o};class ur{get user(){return this.__user&&Object.keys(this.__user).length?JSON.parse(JSON.stringify(this.__user)):null}set user(e){}get onLogin(){return this._onLoginListeners}set onLogin(e){"function"==typeof e&&this._onLoginListeners.push(e)}get onUserUpdate(){return this._userProfileListeners}set onUserUpdate(e){"function"==typeof e&&this._userProfileListeners.push(e)}_runOnUserUpdateListeners(e){for(let t of this._userProfileListeners)"function"==typeof t&&t(e)}_runOnLoginListeners(e){for(let t of this._onLoginListeners)"function"==typeof t&&t(e)}get onBatchProcess(){return this._onBatchProcessListeners}set onBatchProcess(e){"function"==typeof e&&this._onBatchProcessListeners.push(e)}_alert(e){ue()&&"function"==typeof window.alert&&window.alert(e)}constructor(e,t,n,r){if(this.__version=ar.rE,this.session=null,this.connection=null,this.__my_unique_ids={},this.userPool=null,this.__socket=null,this.__mediaStream=null,this.host="skapi",this.hostDomain="skapi.com",this.target_cdn="d3e9syvbtso631",this.customApiDomain="skapi.dev",this.requestBatchSize=30,this.__disabledAccount=null,this.__cached_requests={},this.__startKeyHistory={},this.__request_signup_confirmation=null,this.__private_access_key={},this.__class_properties_has_been_cached=!1,this.__user=null,this._userProfileListeners=[],this._onLoginListeners=[],this._onBatchProcessListeners=[],this.validate={userId(e){try{return ve.UserId(e),!0}catch(e){return!1}},url(e){try{return ve.Url(e),!0}catch(e){return!1}},phoneNumber(e){try{return ve.PhoneNumber(e),!0}catch(e){return!1}},birthdate(e){try{return ve.Birthdate(e),!0}catch(e){return!1}},email(e){try{return ve.Email(e),!0}catch(e){return!1}},params:(e,t,n)=>ve.Params(e,t,n)},this.util={MD5:ie,generateRandom:ae,toBase62:se,fromBase62:oe,decodeServiceId:ge,formatServiceId:_e,extractFormData:fe,terminatePendingRequests:dt,request:(e,t,n)=>ft.bind(this)(e,t,n,{ignoreService:!0})},this.__network_logs=!1,this.__endpoint_version="v1",this.__public_identifier="",this.bearerToken="",this.registerTicket=De.bind(this),this.unregisterTicket=Ue.bind(this),!e||"string"!=typeof e)throw this._alert("Service ID is required."),new te("Service ID is required.",{code:"INVALID_PARAMETER"});if(e.startsWith("s1_")||7===e.split("-").length)try{let i=ge(e);n&&"object"==typeof n&&(r=n),t&&"object"==typeof t&&(n=t),t=i.owner,e=i.service}catch(e){throw this._alert("Service ID is invalid."),new te("Service ID is invalid.",{code:"INVALID_PARAMETER"})}if(!t||"string"!=typeof t)throw this._alert("Owner ID is invalid."),new te("Owner ID is invalid.",{code:"INVALID_PARAMETER"});if("service_id"===e.toLowerCase())throw this._alert('Replace "service_id" with your actual Service ID.'),new te("Service ID is required.",{code:"INVALID_PARAMETER"});if(t!==this.host)try{ve.UserId(t,'"owner"')}catch(e){throw this._alert("Owner ID is invalid."),new te("Owner ID is invalid.",{code:"INVALID_PARAMETER"})}this.service=e,this.owner=t;let i=!0;if(n&&("boolean"==typeof n.autoLogin&&(i=n.autoLogin),"number"==typeof n.requestBatchSize)){if(n.requestBatchSize<1)throw new te('"requestBatchSize" must be greater than 0.',{code:"INVALID_PARAMETER"});this.requestBatchSize=n.requestBatchSize}n?.eventListener&&"object"==typeof n.eventListener&&(n.eventListener?.onLogin&&"function"==typeof n.eventListener.onLogin&&(this.onLogin=n.eventListener.onLogin),n.eventListener?.onUserUpdate&&"function"==typeof n.eventListener.onUserUpdate&&(this.onUserUpdate=n.eventListener.onUserUpdate),n.eventListener?.onBatchProcess&&"function"==typeof n.eventListener.onBatchProcess&&(this.onBatchProcess=n.eventListener.onBatchProcess)),this.target_cdn=r?.target_cdn||this.target_cdn,this.hostDomain=r?.hostDomain||this.hostDomain,this.customApiDomain=r?.customApiDomain||this.customApiDomain,this.__network_logs=!!r?.network_logs;const s=`https://${this.target_cdn}.cloudfront.net`;let o=e.substring(0,4);this.admin_endpoint=fetch(`${s}/${o}/admin-${this.__endpoint_version}.json`).then(e=>e.blob()).then(e=>new Promise((t,n)=>{const r=new FileReader;r.onloadend=()=>t(r.result),r.onerror=n,r.readAsDataURL(e)})).then(e=>{try{return"string"==typeof e?JSON.parse(atob(e.split(",")[1])):null}catch(e){throw new te("Service does not exist. Create your service from skapi.com",{code:"NOT_EXISTS"})}}),this.record_endpoint=fetch(`${s}/${o}/record-${this.__endpoint_version}.json`).then(e=>e.blob()).then(e=>new Promise((t,n)=>{const r=new FileReader;r.onloadend=()=>t(r.result),r.onerror=n,r.readAsDataURL(e)})).then(e=>{try{return"string"==typeof e?JSON.parse(atob(e.split(",")[1])):null}catch(e){throw new te("Service does not exist. Create your service from skapi.com",{code:"NOT_EXISTS"})}});const a=ue();if(a&&!window.sessionStorage)throw this._alert("This browser is not supported."),new Error("This browser is not supported.");const c=a?JSON.parse(window.sessionStorage.getItem(`${e}#${t}`)||"null"):null;if(this.log("constructor:restore",c),c?.connection){for(let e in c)this[e]=c[e];c.__public_identifier||(this.__public_identifier=`${this.service}:${this.owner}:${ae(16)}`)}this.__authConnection=(async()=>{const e=await this.admin_endpoint,t={UserPoolId:e.userpool_id,ClientId:e.userpool_client};ce()&&(t.Storage=window.localStorage),this.userPool=new ee(t);try{this.user||await ke.bind(this)().getSession({skipUserUpdateEventTrigger:!0}),this.user&&(c?.connection||i?(this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user)):xe.bind(this)())}catch(e){}})();let u=a?window.sessionStorage.getItem(`${this.service}:uniqueids`):null;if(u)try{this.__my_unique_ids=JSON.parse(u)}catch(e){this.__my_unique_ids={}}this.__connection=(async()=>{let n=null;await this.record_endpoint,c?.connection||(n=this._updateConnection());const r=()=>{if(this.__class_properties_has_been_cached)return;let r=()=>{let n={};const r=["__startKeyHistory","__disabledAccount","__cached_requests","__request_signup_confirmation","__public_identifier","connection"];if(this.connection){for(let e of r)n[e]=this[e];a&&window.sessionStorage.setItem(`${e}#${t}`,JSON.stringify(n)),this.__class_properties_has_been_cached=!0}};return n instanceof Promise?n.then(()=>r()):r()};return a&&(window.addEventListener("beforeunload",()=>{this.closeRealtime(),r()}),window.addEventListener("visibilitychange",()=>{r()})),await n,await this.__authConnection,this.connection})(),this.__connection.then(e=>{((e?.group||0)<3||this.__network_logs)&&this.version()})}async getConnectionInfo(){let e=await this.__connection,t=e?.user_agent||(ue()&&"string"==typeof window.navigator?.userAgent?window.navigator.userAgent:`skapi-node/${globalThis?.process?.versions?.node||"unknown"}`);return{user_ip:e.ip,user_agent:t,user_location:e.locale,service_name:e.service_name,version:this.__version}}async _updateConnection(){try{this.connection=await ft.bind(this)("service",{service:this.service,owner:this.owner},{bypassAwaitConnection:!0,method:"get"})}catch(e){throw this.log("connection fail",e),this._alert("Service is not available: "+(e.message||e.toString())),this.connection=null,e}return this.connection}async version(){if(await this.__connection,ue()){let e=`Built with:\n%c\r\n $$\\ $$\\ \r\n $$ | \\__|\r\n $$$$$$$\\ $$ | $$\\ $$$$$$\\ $$$$$$\\ $$\\ \r\n$$ _____|$$ | $$ |\\____$$\\ $$ __$$\\ $$ |\r\n\\$$$$$$\\ $$$$$$ / $$$$$$$ |$$ / $$ |$$ |\r\n \\____$$\\ $$ _$$< $$ __$$ |$$ | $$ |$$ |\r\n$$$$$$$ |$$ | \\$$\\\\$$$$$$$ |$$$$$$$ |$$ |\r\n\\_______/ \\__| \\__|\\_______|$$ ____/ \\__|\r\n $$ | \r\n $$ | \r\n \\__| \r\nVersion: ${this.__version}\n\nFull Documentation: https://docs.skapi.com/skapi.md`;console.log(e,"font-family: monospace; color:blue;"),1===this.connection.group&&console.log("%cSKAPI: THE SERVICE IS IN TRIAL MODE.","font-family: monospace; color:red;")}return this.__version}log(e,t){if(this.__network_logs){if("object"==typeof t)try{t=JSON.parse(JSON.stringify(t))}catch(e){t=String(t)}else"string"==typeof t&&t.length>100&&(t=t.substring(0,100)+"...");console.log(`%c${e}:`,"color: blue;",t)}}getFeed(e,t){return Ln.bind(this)(e,t)}closeRTC(e){return cn.bind(this)(e)}connectRTC(e,t){return ln.bind(this)(e,t)}connectRealtime(e){return vn.bind(this)(e)}spellcast(e){return ir.bind(this)(e)}getspell(e){return sr.bind(this)(e)}dopamine(e){return or.bind(this)(e)}getUniqueId(e,t){return jt.bind(this)(e,t)}resendInvitation(e){return Xn.bind(this)(e)}cancelInvitation(e){return Zn.bind(this)(e)}getInvitations(e,t){return Yn.bind(this)(e,t)}openIdLogin(e){return Oe.bind(this)(e)}loginWithToken(e){return Me.bind(this)(e)}clientSecretRequest(e){return Pn.bind(this)(e)}consumeTicket(e){return Ie.bind(this)(e)}getConsumedTickets(e,t){return Re.bind(this)(e,t)}getTickets(e,t){return Te.bind(this)(e,t)}closeRealtime(){return An.bind(this)()}getRealtimeUsers(e,t){return In.bind(this)(e,t)}sendInquiry(e){return Cn.bind(this)(e)}blockAccount(e){return Jn.bind(this)(e)}unblockAccount(e){return Hn.bind(this)(e)}deleteAccount(e){return Wn.bind(this)(e)}inviteUser(e,t){return Qn.bind(this)(e,t)}createAccount(e){return zn.bind(this)(e)}grantAccess(e){return Gn.bind(this)(e)}getRealtimeGroups(e,t){return Tn.bind(this)(e,t)}postRealtime(e,t,n){return En.bind(this)(e,t,n)}joinRealtime(e){return Sn.bind(this)(e)}getProfile(e){return Le.bind(this)(e)}getFile(e,t){return Lt.bind(this)(e,t)}secureRequest(e,t){return kn.bind(this)(e,t)}getFormResponse(){return bt.bind(this)()}getRecords(e,t){return Mt.bind(this)(e,t)}getTables(e,t){return Ft.bind(this)(e,t)}getIndexes(e,t){return qt.bind(this)(e,t)}getTags(e,t){return $t.bind(this)(e,t)}deleteRecords(e,t){return Bt.bind(this)(e,t)}resendSignupConfirmation(){return qe.bind(this)()}recoverAccount(e=!1){return $e.bind(this)(e)}getUsers(e,t){return Ze.bind(this)(e,t)}disableAccount(){return Ke.bind(this)()}lastVerifiedEmail(e){return Xe.bind(this)(e)}unsubscribeNewsletter(e){return Bn.bind(this)(e)}subscribeNotification(e,t){return er.bind(this)({endpoint:e,keys:t})}unsubscribeNotification(e,t){return tr.bind(this)({endpoint:e,keys:t})}vapidPublicKey(){return nr.bind(this)()}pushNotification(e,t){return rr.bind(this)(e,t)}getNewsletters(e,t){return Kn.bind(this)(e,t)}getNewsletterSubscription(e,t){return $n.bind(this)(e,t)}requestUsernameChange(e){return et.bind(this)(e)}grantPrivateRecordAccess(e){return Kt.bind(this)(e)}removePrivateRecordAccess(e){return Jt.bind(this)(e)}listPrivateRecordAccess(e){return Ht.bind(this)(e)}requestPrivateRecordAccessKey(e){return Wt.bind(this)(e)}deleteFiles(e){return Nt.bind(this)(e)}uploadFiles(e,t){return mt.bind(this)(e,t)}mock(e,t){return Nn.bind(this)(e,t)}login(e){return je.bind(this)(e)}logout(e){return Fe.bind(this)(e)}signup(e,t){return Be.bind(this)(e,t)}resetPassword(e){return Je.bind(this)(e)}verifyEmail(e){return Qe.bind(this)(e)}verifyPhoneNumber(e){return We.bind(this)(e)}forgotPassword(e){return ze.bind(this)(e)}changePassword(e){return Ge.bind(this)(e)}updateProfile(e){return Ye.bind(this)(e)}postRecord(e,t,n){return Vt.bind(this)(e,t,n)}async bulkPostRecords(e){return xt.bind(this)(e)}getSubscriptions(e,t){return Mn.bind(this)(e,t)}subscribe(e){return Vn.bind(this)(e)}unsubscribe(e){return xn.bind(this)(e)}blockSubscriber(e){return Fn.bind(this)(e)}unblockSubscriber(e){return qn.bind(this)(e)}subscribeNewsletter(e){return jn.bind(this)(e)}}cr([wt()],ur.prototype,"getFeed",null),cr([wt()],ur.prototype,"closeRTC",null),cr([wt()],ur.prototype,"connectRTC",null),cr([wt()],ur.prototype,"spellcast",null),cr([wt()],ur.prototype,"getspell",null),cr([wt()],ur.prototype,"dopamine",null),cr([wt()],ur.prototype,"getUniqueId",null),cr([wt()],ur.prototype,"resendInvitation",null),cr([wt()],ur.prototype,"cancelInvitation",null),cr([wt()],ur.prototype,"getInvitations",null),cr([wt()],ur.prototype,"openIdLogin",null),cr([wt()],ur.prototype,"loginWithToken",null),cr([wt()],ur.prototype,"clientSecretRequest",null),cr([wt()],ur.prototype,"consumeTicket",null),cr([wt()],ur.prototype,"getConsumedTickets",null),cr([wt()],ur.prototype,"getTickets",null),cr([wt()],ur.prototype,"getRealtimeUsers",null),cr([wt()],ur.prototype,"sendInquiry",null),cr([wt()],ur.prototype,"blockAccount",null),cr([wt()],ur.prototype,"unblockAccount",null),cr([wt()],ur.prototype,"deleteAccount",null),cr([wt()],ur.prototype,"inviteUser",null),cr([wt()],ur.prototype,"createAccount",null),cr([wt()],ur.prototype,"grantAccess",null),cr([wt()],ur.prototype,"getRealtimeGroups",null),cr([wt()],ur.prototype,"postRealtime",null),cr([wt()],ur.prototype,"joinRealtime",null),cr([wt()],ur.prototype,"getProfile",null),cr([wt()],ur.prototype,"getFile",null),cr([wt()],ur.prototype,"secureRequest",null),cr([wt()],ur.prototype,"getFormResponse",null),cr([wt()],ur.prototype,"getRecords",null),cr([wt()],ur.prototype,"getTables",null),cr([wt()],ur.prototype,"getIndexes",null),cr([wt()],ur.prototype,"getTags",null),cr([wt()],ur.prototype,"deleteRecords",null),cr([wt()],ur.prototype,"resendSignupConfirmation",null),cr([wt()],ur.prototype,"recoverAccount",null),cr([wt()],ur.prototype,"getUsers",null),cr([wt()],ur.prototype,"disableAccount",null),cr([wt()],ur.prototype,"lastVerifiedEmail",null),cr([wt()],ur.prototype,"unsubscribeNewsletter",null),cr([wt()],ur.prototype,"subscribeNotification",null),cr([wt()],ur.prototype,"unsubscribeNotification",null),cr([wt()],ur.prototype,"vapidPublicKey",null),cr([wt()],ur.prototype,"pushNotification",null),cr([wt()],ur.prototype,"getNewsletters",null),cr([wt()],ur.prototype,"getNewsletterSubscription",null),cr([wt()],ur.prototype,"requestUsernameChange",null),cr([wt()],ur.prototype,"grantPrivateRecordAccess",null),cr([wt()],ur.prototype,"removePrivateRecordAccess",null),cr([wt()],ur.prototype,"listPrivateRecordAccess",null),cr([wt()],ur.prototype,"requestPrivateRecordAccessKey",null),cr([wt()],ur.prototype,"deleteFiles",null),cr([wt()],ur.prototype,"uploadFiles",null),cr([wt()],ur.prototype,"mock",null),cr([wt({preventMultipleCalls:!0})],ur.prototype,"login",null),cr([wt()],ur.prototype,"logout",null),cr([wt({preventMultipleCalls:!0})],ur.prototype,"signup",null),cr([wt({preventMultipleCalls:!0})],ur.prototype,"resetPassword",null),cr([wt({preventMultipleCalls:!0})],ur.prototype,"verifyEmail",null),cr([wt({preventMultipleCalls:!0})],ur.prototype,"verifyPhoneNumber",null),cr([wt({preventMultipleCalls:!0})],ur.prototype,"forgotPassword",null),cr([wt({preventMultipleCalls:!0})],ur.prototype,"changePassword",null),cr([wt({preventMultipleCalls:!0})],ur.prototype,"updateProfile",null),cr([wt()],ur.prototype,"postRecord",null),cr([wt({preventMultipleCalls:!0})],ur.prototype,"bulkPostRecords",null),cr([wt()],ur.prototype,"getSubscriptions",null),cr([wt()],ur.prototype,"subscribe",null),cr([wt()],ur.prototype,"unsubscribe",null),cr([wt()],ur.prototype,"blockSubscriber",null),cr([wt()],ur.prototype,"unblockSubscriber",null),cr([wt()],ur.prototype,"subscribeNewsletter",null)})(),r})());
3
3
  //# sourceMappingURL=skapi.js.map