skapi-js 1.5.6-beta.0 → 1.5.7-beta.1

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.
@@ -203,8 +203,8 @@
203
203
  limitations under the License.
204
204
 
205
205
  */
206
- var Ds=Object.create;var De=Object.defineProperty;var Or=Object.getOwnPropertyDescriptor;var ks=Object.getOwnPropertyNames;var Ns=Object.getPrototypeOf,Fs=Object.prototype.hasOwnProperty;var Ls=(r,e,t)=>e in r?De(r,e,{enumerable:true,configurable:true,writable:true,value:t}):r[e]=t;var Mr=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')});var ke=(r,e)=>()=>(r&&(e=r(r=0)),e);var j=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),st=(r,e)=>{for(var t in e)De(r,t,{get:e[t],enumerable:true});},Vr=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of ks(e))!Fs.call(r,i)&&i!==t&&De(r,i,{get:()=>e[i],enumerable:!(n=Or(e,i))||n.enumerable});return r};var Te=(r,e,t)=>(t=r!=null?Ds(Ns(r)):{},Vr(!r||!r.__esModule?De(t,"default",{value:r,enumerable:true}):t,r)),re=r=>Vr(De({},"__esModule",{value:true}),r),E=(r,e,t,n)=>{for(var i=Or(e,t),s=r.length-1,o;s>=0;s--)(o=r[s])&&(i=(o(e,t,i))||i);return i&&De(e,t,i),i};var fe=(r,e,t)=>Ls(r,typeof e!="symbol"?e+"":e,t);var Re={};st(Re,{default:()=>Ms});var Os,Ms,Ie=ke(()=>{Os={},Ms=Os;});var $r=j(at=>{at.byteLength=Bs;at.toByteArray=js;at.fromByteArray=Ws;var ae=[],Y=[],qs=typeof Uint8Array<"u"?Uint8Array:Array,$t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(Pe=0,qr=$t.length;Pe<qr;++Pe)ae[Pe]=$t[Pe],Y[$t.charCodeAt(Pe)]=Pe;var Pe,qr;Y[45]=62;Y[95]=63;function Br(r){var e=r.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var t=r.indexOf("=");t===-1&&(t=e);var n=t===e?0:4-t%4;return [t,n]}function Bs(r){var e=Br(r),t=e[0],n=e[1];return (t+n)*3/4-n}function $s(r,e,t){return (e+t)*3/4-t}function js(r){var e,t=Br(r),n=t[0],i=t[1],s=new qs($s(r,n,i)),o=0,a=i>0?n-4:n,u;for(u=0;u<a;u+=4)e=Y[r.charCodeAt(u)]<<18|Y[r.charCodeAt(u+1)]<<12|Y[r.charCodeAt(u+2)]<<6|Y[r.charCodeAt(u+3)],s[o++]=e>>16&255,s[o++]=e>>8&255,s[o++]=e&255;return i===2&&(e=Y[r.charCodeAt(u)]<<2|Y[r.charCodeAt(u+1)]>>4,s[o++]=e&255),i===1&&(e=Y[r.charCodeAt(u)]<<10|Y[r.charCodeAt(u+1)]<<4|Y[r.charCodeAt(u+2)]>>2,s[o++]=e>>8&255,s[o++]=e&255),s}function Ks(r){return ae[r>>18&63]+ae[r>>12&63]+ae[r>>6&63]+ae[r&63]}function Hs(r,e,t){for(var n,i=[],s=e;s<t;s+=3)n=(r[s]<<16&16711680)+(r[s+1]<<8&65280)+(r[s+2]&255),i.push(Ks(n));return i.join("")}function Ws(r){for(var e,t=r.length,n=t%3,i=[],s=16383,o=0,a=t-n;o<a;o+=s)i.push(Hs(r,o,o+s>a?a:o+s));return n===1?(e=r[t-1],i.push(ae[e>>2]+ae[e<<4&63]+"==")):n===2&&(e=(r[t-2]<<8)+r[t-1],i.push(ae[e>>10]+ae[e>>4&63]+ae[e<<2&63]+"=")),i.join("")}});var jr=j(jt=>{jt.read=function(r,e,t,n,i){var s,o,a=i*8-n-1,u=(1<<a)-1,c=u>>1,d=-7,l=t?i-1:0,g=t?-1:1,p=r[e+l];for(l+=g,s=p&(1<<-d)-1,p>>=-d,d+=a;d>0;s=s*256+r[e+l],l+=g,d-=8);for(o=s&(1<<-d)-1,s>>=-d,d+=n;d>0;o=o*256+r[e+l],l+=g,d-=8);if(s===0)s=1-c;else {if(s===u)return o?NaN:(p?-1:1)*(1/0);o=o+Math.pow(2,n),s=s-c;}return (p?-1:1)*o*Math.pow(2,s-n)};jt.write=function(r,e,t,n,i,s){var o,a,u,c=s*8-i-1,d=(1<<c)-1,l=d>>1,g=i===23?Math.pow(2,-24)-Math.pow(2,-77):0,p=n?0:s-1,h=n?1:-1,b=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,o=d):(o=Math.floor(Math.log(e)/Math.LN2),e*(u=Math.pow(2,-o))<1&&(o--,u*=2),o+l>=1?e+=g/u:e+=g*Math.pow(2,1-l),e*u>=2&&(o++,u/=2),o+l>=d?(a=0,o=d):o+l>=1?(a=(e*u-1)*Math.pow(2,i),o=o+l):(a=e*Math.pow(2,l-1)*Math.pow(2,i),o=0));i>=8;r[t+p]=a&255,p+=h,a/=256,i-=8);for(o=o<<i|a,c+=i;c>0;r[t+p]=o&255,p+=h,o/=256,c-=8);r[t+p-h]|=b*128;};});var Hr=j((rc,Kr)=>{var Js={}.toString;Kr.exports=Array.isArray||function(r){return Js.call(r)=="[object Array]"};});var ht=j(Fe=>{var Kt=$r(),Ne=jr(),Gr=Hr();Fe.Buffer=y;Fe.SlowBuffer=Zs;Fe.INSPECT_MAX_BYTES=50;y.TYPED_ARRAY_SUPPORT=globalThis.TYPED_ARRAY_SUPPORT!==void 0?globalThis.TYPED_ARRAY_SUPPORT:Gs();Fe.kMaxLength=ut();function Gs(){try{var r=new Uint8Array(1);return r.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},r.foo()===42&&typeof r.subarray=="function"&&r.subarray(1,1).byteLength===0}catch{return false}}function ut(){return y.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function ge(r,e){if(ut()<e)throw new RangeError("Invalid typed array length");return y.TYPED_ARRAY_SUPPORT?(r=new Uint8Array(e),r.__proto__=y.prototype):(r===null&&(r=new y(e)),r.length=e),r}function y(r,e,t){if(!y.TYPED_ARRAY_SUPPORT&&!(this instanceof y))return new y(r,e,t);if(typeof r=="number"){if(typeof e=="string")throw new Error("If encoding is specified then the first argument must be a string");return Wt(this,r)}return Qr(this,r,e,t)}y.poolSize=8192;y._augment=function(r){return r.__proto__=y.prototype,r};function Qr(r,e,t,n){if(typeof e=="number")throw new TypeError('"value" argument must not be a number');return typeof ArrayBuffer<"u"&&e instanceof ArrayBuffer?Ys(r,e,t,n):typeof e=="string"?zs(r,e,t):Xs(r,e)}y.from=function(r,e,t){return Qr(null,r,e,t)};y.TYPED_ARRAY_SUPPORT&&(y.prototype.__proto__=Uint8Array.prototype,y.__proto__=Uint8Array,typeof Symbol<"u"&&Symbol.species&&y[Symbol.species]===y&&Object.defineProperty(y,Symbol.species,{value:null,configurable:true}));function zr(r){if(typeof r!="number")throw new TypeError('"size" argument must be a number');if(r<0)throw new RangeError('"size" argument must not be negative')}function Qs(r,e,t,n){return zr(e),e<=0?ge(r,e):t!==void 0?typeof n=="string"?ge(r,e).fill(t,n):ge(r,e).fill(t):ge(r,e)}y.alloc=function(r,e,t){return Qs(null,r,e,t)};function Wt(r,e){if(zr(e),r=ge(r,e<0?0:Jt(e)|0),!y.TYPED_ARRAY_SUPPORT)for(var t=0;t<e;++t)r[t]=0;return r}y.allocUnsafe=function(r){return Wt(null,r)};y.allocUnsafeSlow=function(r){return Wt(null,r)};function zs(r,e,t){if((typeof t!="string"||t==="")&&(t="utf8"),!y.isEncoding(t))throw new TypeError('"encoding" must be a valid string encoding');var n=Yr(e,t)|0;r=ge(r,n);var i=r.write(e,t);return i!==n&&(r=r.slice(0,i)),r}function Ht(r,e){var t=e.length<0?0:Jt(e.length)|0;r=ge(r,t);for(var n=0;n<t;n+=1)r[n]=e[n]&255;return r}function Ys(r,e,t,n){if(e.byteLength,t<0||e.byteLength<t)throw new RangeError("'offset' is out of bounds");if(e.byteLength<t+(n||0))throw new RangeError("'length' is out of bounds");return t===void 0&&n===void 0?e=new Uint8Array(e):n===void 0?e=new Uint8Array(e,t):e=new Uint8Array(e,t,n),y.TYPED_ARRAY_SUPPORT?(r=e,r.__proto__=y.prototype):r=Ht(r,e),r}function Xs(r,e){if(y.isBuffer(e)){var t=Jt(e.length)|0;return r=ge(r,t),r.length===0||e.copy(r,0,0,t),r}if(e){if(typeof ArrayBuffer<"u"&&e.buffer instanceof ArrayBuffer||"length"in e)return typeof e.length!="number"||yo(e.length)?ge(r,0):Ht(r,e);if(e.type==="Buffer"&&Gr(e.data))return Ht(r,e.data)}throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")}function Jt(r){if(r>=ut())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+ut().toString(16)+" bytes");return r|0}function Zs(r){return +r!=r&&(r=0),y.alloc(+r)}y.isBuffer=function(e){return !!(e!=null&&e._isBuffer)};y.compare=function(e,t){if(!y.isBuffer(e)||!y.isBuffer(t))throw new TypeError("Arguments must be Buffers");if(e===t)return 0;for(var n=e.length,i=t.length,s=0,o=Math.min(n,i);s<o;++s)if(e[s]!==t[s]){n=e[s],i=t[s];break}return n<i?-1:i<n?1:0};y.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 true;default:return false}};y.concat=function(e,t){if(!Gr(e))throw new TypeError('"list" argument must be an Array of Buffers');if(e.length===0)return y.alloc(0);var n;if(t===void 0)for(t=0,n=0;n<e.length;++n)t+=e[n].length;var i=y.allocUnsafe(t),s=0;for(n=0;n<e.length;++n){var o=e[n];if(!y.isBuffer(o))throw new TypeError('"list" argument must be an Array of Buffers');o.copy(i,s),s+=o.length;}return i};function Yr(r,e){if(y.isBuffer(r))return r.length;if(typeof ArrayBuffer<"u"&&typeof ArrayBuffer.isView=="function"&&(ArrayBuffer.isView(r)||r instanceof ArrayBuffer))return r.byteLength;typeof r!="string"&&(r=""+r);var t=r.length;if(t===0)return 0;for(var n=false;;)switch(e){case "ascii":case "latin1":case "binary":return t;case "utf8":case "utf-8":case void 0:return ct(r).length;case "ucs2":case "ucs-2":case "utf16le":case "utf-16le":return t*2;case "hex":return t>>>1;case "base64":return sn(r).length;default:if(n)return ct(r).length;e=(""+e).toLowerCase(),n=true;}}y.byteLength=Yr;function eo(r,e,t){var n=false;if((e===void 0||e<0)&&(e=0),e>this.length||((t===void 0||t>this.length)&&(t=this.length),t<=0)||(t>>>=0,e>>>=0,t<=e))return "";for(r||(r="utf8");;)switch(r){case "hex":return lo(this,e,t);case "utf8":case "utf-8":return en(this,e,t);case "ascii":return uo(this,e,t);case "latin1":case "binary":return co(this,e,t);case "base64":return oo(this,e,t);case "ucs2":case "ucs-2":case "utf16le":case "utf-16le":return fo(this,e,t);default:if(n)throw new TypeError("Unknown encoding: "+r);r=(r+"").toLowerCase(),n=true;}}y.prototype._isBuffer=true;function xe(r,e,t){var n=r[e];r[e]=r[t],r[t]=n;}y.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)xe(this,t,t+1);return this};y.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)xe(this,t,t+3),xe(this,t+1,t+2);return this};y.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)xe(this,t,t+7),xe(this,t+1,t+6),xe(this,t+2,t+5),xe(this,t+3,t+4);return this};y.prototype.toString=function(){var e=this.length|0;return e===0?"":arguments.length===0?en(this,0,e):eo.apply(this,arguments)};y.prototype.equals=function(e){if(!y.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e?true:y.compare(this,e)===0};y.prototype.inspect=function(){var e="",t=Fe.INSPECT_MAX_BYTES;return this.length>0&&(e=this.toString("hex",0,t).match(/.{2}/g).join(" "),this.length>t&&(e+=" ... ")),"<Buffer "+e+">"};y.prototype.compare=function(e,t,n,i,s){if(!y.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(t===void 0&&(t=0),n===void 0&&(n=e?e.length:0),i===void 0&&(i=0),s===void 0&&(s=this.length),t<0||n>e.length||i<0||s>this.length)throw new RangeError("out of range index");if(i>=s&&t>=n)return 0;if(i>=s)return -1;if(t>=n)return 1;if(t>>>=0,n>>>=0,i>>>=0,s>>>=0,this===e)return 0;for(var o=s-i,a=n-t,u=Math.min(o,a),c=this.slice(i,s),d=e.slice(t,n),l=0;l<u;++l)if(c[l]!==d[l]){o=c[l],a=d[l];break}return o<a?-1:a<o?1:0};function Xr(r,e,t,n,i){if(r.length===0)return -1;if(typeof t=="string"?(n=t,t=0):t>2147483647?t=2147483647:t<-2147483648&&(t=-2147483648),t=+t,isNaN(t)&&(t=i?0:r.length-1),t<0&&(t=r.length+t),t>=r.length){if(i)return -1;t=r.length-1;}else if(t<0)if(i)t=0;else return -1;if(typeof e=="string"&&(e=y.from(e,n)),y.isBuffer(e))return e.length===0?-1:Wr(r,e,t,n,i);if(typeof e=="number")return e=e&255,y.TYPED_ARRAY_SUPPORT&&typeof Uint8Array.prototype.indexOf=="function"?i?Uint8Array.prototype.indexOf.call(r,e,t):Uint8Array.prototype.lastIndexOf.call(r,e,t):Wr(r,[e],t,n,i);throw new TypeError("val must be string, number or Buffer")}function Wr(r,e,t,n,i){var s=1,o=r.length,a=e.length;if(n!==void 0&&(n=String(n).toLowerCase(),n==="ucs2"||n==="ucs-2"||n==="utf16le"||n==="utf-16le")){if(r.length<2||e.length<2)return -1;s=2,o/=2,a/=2,t/=2;}function u(p,h){return s===1?p[h]:p.readUInt16BE(h*s)}var c;if(i){var d=-1;for(c=t;c<o;c++)if(u(r,c)===u(e,d===-1?0:c-d)){if(d===-1&&(d=c),c-d+1===a)return d*s}else d!==-1&&(c-=c-d),d=-1;}else for(t+a>o&&(t=o-a),c=t;c>=0;c--){for(var l=true,g=0;g<a;g++)if(u(r,c+g)!==u(e,g)){l=false;break}if(l)return c}return -1}y.prototype.includes=function(e,t,n){return this.indexOf(e,t,n)!==-1};y.prototype.indexOf=function(e,t,n){return Xr(this,e,t,n,true)};y.prototype.lastIndexOf=function(e,t,n){return Xr(this,e,t,n,false)};function to(r,e,t,n){t=Number(t)||0;var i=r.length-t;n?(n=Number(n),n>i&&(n=i)):n=i;var s=e.length;if(s%2!==0)throw new TypeError("Invalid hex string");n>s/2&&(n=s/2);for(var o=0;o<n;++o){var a=parseInt(e.substr(o*2,2),16);if(isNaN(a))return o;r[t+o]=a;}return o}function ro(r,e,t,n){return ft(ct(e,r.length-t),r,t,n)}function Zr(r,e,t,n){return ft(_o(e),r,t,n)}function no(r,e,t,n){return Zr(r,e,t,n)}function io(r,e,t,n){return ft(sn(e),r,t,n)}function so(r,e,t,n){return ft(bo(e,r.length-t),r,t,n)}y.prototype.write=function(e,t,n,i){if(t===void 0)i="utf8",n=this.length,t=0;else if(n===void 0&&typeof t=="string")i=t,n=this.length,t=0;else if(isFinite(t))t=t|0,isFinite(n)?(n=n|0,i===void 0&&(i="utf8")):(i=n,n=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");var s=this.length-t;if((n===void 0||n>s)&&(n=s),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");i||(i="utf8");for(var o=false;;)switch(i){case "hex":return to(this,e,t,n);case "utf8":case "utf-8":return ro(this,e,t,n);case "ascii":return Zr(this,e,t,n);case "latin1":case "binary":return no(this,e,t,n);case "base64":return io(this,e,t,n);case "ucs2":case "ucs-2":case "utf16le":case "utf-16le":return so(this,e,t,n);default:if(o)throw new TypeError("Unknown encoding: "+i);i=(""+i).toLowerCase(),o=true;}};y.prototype.toJSON=function(){return {type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function oo(r,e,t){return e===0&&t===r.length?Kt.fromByteArray(r):Kt.fromByteArray(r.slice(e,t))}function en(r,e,t){t=Math.min(r.length,t);for(var n=[],i=e;i<t;){var s=r[i],o=null,a=s>239?4:s>223?3:s>191?2:1;if(i+a<=t){var u,c,d,l;switch(a){case 1:s<128&&(o=s);break;case 2:u=r[i+1],(u&192)===128&&(l=(s&31)<<6|u&63,l>127&&(o=l));break;case 3:u=r[i+1],c=r[i+2],(u&192)===128&&(c&192)===128&&(l=(s&15)<<12|(u&63)<<6|c&63,l>2047&&(l<55296||l>57343)&&(o=l));break;case 4:u=r[i+1],c=r[i+2],d=r[i+3],(u&192)===128&&(c&192)===128&&(d&192)===128&&(l=(s&15)<<18|(u&63)<<12|(c&63)<<6|d&63,l>65535&&l<1114112&&(o=l));}}o===null?(o=65533,a=1):o>65535&&(o-=65536,n.push(o>>>10&1023|55296),o=56320|o&1023),n.push(o),i+=a;}return ao(n)}var Jr=4096;function ao(r){var e=r.length;if(e<=Jr)return String.fromCharCode.apply(String,r);for(var t="",n=0;n<e;)t+=String.fromCharCode.apply(String,r.slice(n,n+=Jr));return t}function uo(r,e,t){var n="";t=Math.min(r.length,t);for(var i=e;i<t;++i)n+=String.fromCharCode(r[i]&127);return n}function co(r,e,t){var n="";t=Math.min(r.length,t);for(var i=e;i<t;++i)n+=String.fromCharCode(r[i]);return n}function lo(r,e,t){var n=r.length;(!e||e<0)&&(e=0),(!t||t<0||t>n)&&(t=n);for(var i="",s=e;s<t;++s)i+=mo(r[s]);return i}function fo(r,e,t){for(var n=r.slice(e,t),i="",s=0;s<n.length;s+=2)i+=String.fromCharCode(n[s]+n[s+1]*256);return i}y.prototype.slice=function(e,t){var n=this.length;e=~~e,t=t===void 0?n:~~t,e<0?(e+=n,e<0&&(e=0)):e>n&&(e=n),t<0?(t+=n,t<0&&(t=0)):t>n&&(t=n),t<e&&(t=e);var i;if(y.TYPED_ARRAY_SUPPORT)i=this.subarray(e,t),i.__proto__=y.prototype;else {var s=t-e;i=new y(s,void 0);for(var o=0;o<s;++o)i[o]=this[o+e];}return i};function q(r,e,t){if(r%1!==0||r<0)throw new RangeError("offset is not uint");if(r+e>t)throw new RangeError("Trying to access beyond buffer length")}y.prototype.readUIntLE=function(e,t,n){e=e|0,t=t|0,n||q(e,t,this.length);for(var i=this[e],s=1,o=0;++o<t&&(s*=256);)i+=this[e+o]*s;return i};y.prototype.readUIntBE=function(e,t,n){e=e|0,t=t|0,n||q(e,t,this.length);for(var i=this[e+--t],s=1;t>0&&(s*=256);)i+=this[e+--t]*s;return i};y.prototype.readUInt8=function(e,t){return t||q(e,1,this.length),this[e]};y.prototype.readUInt16LE=function(e,t){return t||q(e,2,this.length),this[e]|this[e+1]<<8};y.prototype.readUInt16BE=function(e,t){return t||q(e,2,this.length),this[e]<<8|this[e+1]};y.prototype.readUInt32LE=function(e,t){return t||q(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+this[e+3]*16777216};y.prototype.readUInt32BE=function(e,t){return t||q(e,4,this.length),this[e]*16777216+(this[e+1]<<16|this[e+2]<<8|this[e+3])};y.prototype.readIntLE=function(e,t,n){e=e|0,t=t|0,n||q(e,t,this.length);for(var i=this[e],s=1,o=0;++o<t&&(s*=256);)i+=this[e+o]*s;return s*=128,i>=s&&(i-=Math.pow(2,8*t)),i};y.prototype.readIntBE=function(e,t,n){e=e|0,t=t|0,n||q(e,t,this.length);for(var i=t,s=1,o=this[e+--i];i>0&&(s*=256);)o+=this[e+--i]*s;return s*=128,o>=s&&(o-=Math.pow(2,8*t)),o};y.prototype.readInt8=function(e,t){return t||q(e,1,this.length),this[e]&128?(255-this[e]+1)*-1:this[e]};y.prototype.readInt16LE=function(e,t){t||q(e,2,this.length);var n=this[e]|this[e+1]<<8;return n&32768?n|4294901760:n};y.prototype.readInt16BE=function(e,t){t||q(e,2,this.length);var n=this[e+1]|this[e]<<8;return n&32768?n|4294901760:n};y.prototype.readInt32LE=function(e,t){return t||q(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24};y.prototype.readInt32BE=function(e,t){return t||q(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]};y.prototype.readFloatLE=function(e,t){return t||q(e,4,this.length),Ne.read(this,e,true,23,4)};y.prototype.readFloatBE=function(e,t){return t||q(e,4,this.length),Ne.read(this,e,false,23,4)};y.prototype.readDoubleLE=function(e,t){return t||q(e,8,this.length),Ne.read(this,e,true,52,8)};y.prototype.readDoubleBE=function(e,t){return t||q(e,8,this.length),Ne.read(this,e,false,52,8)};function G(r,e,t,n,i,s){if(!y.isBuffer(r))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>i||e<s)throw new RangeError('"value" argument is out of bounds');if(t+n>r.length)throw new RangeError("Index out of range")}y.prototype.writeUIntLE=function(e,t,n,i){if(e=+e,t=t|0,n=n|0,!i){var s=Math.pow(2,8*n)-1;G(this,e,t,n,s,0);}var o=1,a=0;for(this[t]=e&255;++a<n&&(o*=256);)this[t+a]=e/o&255;return t+n};y.prototype.writeUIntBE=function(e,t,n,i){if(e=+e,t=t|0,n=n|0,!i){var s=Math.pow(2,8*n)-1;G(this,e,t,n,s,0);}var o=n-1,a=1;for(this[t+o]=e&255;--o>=0&&(a*=256);)this[t+o]=e/a&255;return t+n};y.prototype.writeUInt8=function(e,t,n){return e=+e,t=t|0,n||G(this,e,t,1,255,0),y.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=e&255,t+1};function lt(r,e,t,n){e<0&&(e=65535+e+1);for(var i=0,s=Math.min(r.length-t,2);i<s;++i)r[t+i]=(e&255<<8*(n?i:1-i))>>>(n?i:1-i)*8;}y.prototype.writeUInt16LE=function(e,t,n){return e=+e,t=t|0,n||G(this,e,t,2,65535,0),y.TYPED_ARRAY_SUPPORT?(this[t]=e&255,this[t+1]=e>>>8):lt(this,e,t,true),t+2};y.prototype.writeUInt16BE=function(e,t,n){return e=+e,t=t|0,n||G(this,e,t,2,65535,0),y.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=e&255):lt(this,e,t,false),t+2};function dt(r,e,t,n){e<0&&(e=4294967295+e+1);for(var i=0,s=Math.min(r.length-t,4);i<s;++i)r[t+i]=e>>>(n?i:3-i)*8&255;}y.prototype.writeUInt32LE=function(e,t,n){return e=+e,t=t|0,n||G(this,e,t,4,4294967295,0),y.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=e&255):dt(this,e,t,true),t+4};y.prototype.writeUInt32BE=function(e,t,n){return e=+e,t=t|0,n||G(this,e,t,4,4294967295,0),y.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=e&255):dt(this,e,t,false),t+4};y.prototype.writeIntLE=function(e,t,n,i){if(e=+e,t=t|0,!i){var s=Math.pow(2,8*n-1);G(this,e,t,n,s-1,-s);}var o=0,a=1,u=0;for(this[t]=e&255;++o<n&&(a*=256);)e<0&&u===0&&this[t+o-1]!==0&&(u=1),this[t+o]=(e/a>>0)-u&255;return t+n};y.prototype.writeIntBE=function(e,t,n,i){if(e=+e,t=t|0,!i){var s=Math.pow(2,8*n-1);G(this,e,t,n,s-1,-s);}var o=n-1,a=1,u=0;for(this[t+o]=e&255;--o>=0&&(a*=256);)e<0&&u===0&&this[t+o+1]!==0&&(u=1),this[t+o]=(e/a>>0)-u&255;return t+n};y.prototype.writeInt8=function(e,t,n){return e=+e,t=t|0,n||G(this,e,t,1,127,-128),y.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=e&255,t+1};y.prototype.writeInt16LE=function(e,t,n){return e=+e,t=t|0,n||G(this,e,t,2,32767,-32768),y.TYPED_ARRAY_SUPPORT?(this[t]=e&255,this[t+1]=e>>>8):lt(this,e,t,true),t+2};y.prototype.writeInt16BE=function(e,t,n){return e=+e,t=t|0,n||G(this,e,t,2,32767,-32768),y.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=e&255):lt(this,e,t,false),t+2};y.prototype.writeInt32LE=function(e,t,n){return e=+e,t=t|0,n||G(this,e,t,4,2147483647,-2147483648),y.TYPED_ARRAY_SUPPORT?(this[t]=e&255,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):dt(this,e,t,true),t+4};y.prototype.writeInt32BE=function(e,t,n){return e=+e,t=t|0,n||G(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),y.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=e&255):dt(this,e,t,false),t+4};function tn(r,e,t,n,i,s){if(t+n>r.length)throw new RangeError("Index out of range");if(t<0)throw new RangeError("Index out of range")}function rn(r,e,t,n,i){return i||tn(r,e,t,4),Ne.write(r,e,t,n,23,4),t+4}y.prototype.writeFloatLE=function(e,t,n){return rn(this,e,t,true,n)};y.prototype.writeFloatBE=function(e,t,n){return rn(this,e,t,false,n)};function nn(r,e,t,n,i){return i||tn(r,e,t,8),Ne.write(r,e,t,n,52,8),t+8}y.prototype.writeDoubleLE=function(e,t,n){return nn(this,e,t,true,n)};y.prototype.writeDoubleBE=function(e,t,n){return nn(this,e,t,false,n)};y.prototype.copy=function(e,t,n,i){if(n||(n=0),!i&&i!==0&&(i=this.length),t>=e.length&&(t=e.length),t||(t=0),i>0&&i<n&&(i=n),i===n||e.length===0||this.length===0)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(i<0)throw new RangeError("sourceEnd out of bounds");i>this.length&&(i=this.length),e.length-t<i-n&&(i=e.length-t+n);var s=i-n,o;if(this===e&&n<t&&t<i)for(o=s-1;o>=0;--o)e[o+t]=this[o+n];else if(s<1e3||!y.TYPED_ARRAY_SUPPORT)for(o=0;o<s;++o)e[o+t]=this[o+n];else Uint8Array.prototype.set.call(e,this.subarray(n,n+s),t);return s};y.prototype.fill=function(e,t,n,i){if(typeof e=="string"){if(typeof t=="string"?(i=t,t=0,n=this.length):typeof n=="string"&&(i=n,n=this.length),e.length===1){var s=e.charCodeAt(0);s<256&&(e=s);}if(i!==void 0&&typeof i!="string")throw new TypeError("encoding must be a string");if(typeof i=="string"&&!y.isEncoding(i))throw new TypeError("Unknown encoding: "+i)}else typeof e=="number"&&(e=e&255);if(t<0||this.length<t||this.length<n)throw new RangeError("Out of range index");if(n<=t)return this;t=t>>>0,n=n===void 0?this.length:n>>>0,e||(e=0);var o;if(typeof e=="number")for(o=t;o<n;++o)this[o]=e;else {var a=y.isBuffer(e)?e:ct(new y(e,i).toString()),u=a.length;for(o=0;o<n-t;++o)this[o+t]=a[o%u];}return this};var ho=/[^+\/0-9A-Za-z-_]/g;function go(r){if(r=po(r).replace(ho,""),r.length<2)return "";for(;r.length%4!==0;)r=r+"=";return r}function po(r){return r.trim?r.trim():r.replace(/^\s+|\s+$/g,"")}function mo(r){return r<16?"0"+r.toString(16):r.toString(16)}function ct(r,e){e=e||1/0;for(var t,n=r.length,i=null,s=[],o=0;o<n;++o){if(t=r.charCodeAt(o),t>55295&&t<57344){if(!i){if(t>56319){(e-=3)>-1&&s.push(239,191,189);continue}else if(o+1===n){(e-=3)>-1&&s.push(239,191,189);continue}i=t;continue}if(t<56320){(e-=3)>-1&&s.push(239,191,189),i=t;continue}t=(i-55296<<10|t-56320)+65536;}else i&&(e-=3)>-1&&s.push(239,191,189);if(i=null,t<128){if((e-=1)<0)break;s.push(t);}else if(t<2048){if((e-=2)<0)break;s.push(t>>6|192,t&63|128);}else if(t<65536){if((e-=3)<0)break;s.push(t>>12|224,t>>6&63|128,t&63|128);}else if(t<1114112){if((e-=4)<0)break;s.push(t>>18|240,t>>12&63|128,t>>6&63|128,t&63|128);}else throw new Error("Invalid code point")}return s}function _o(r){for(var e=[],t=0;t<r.length;++t)e.push(r.charCodeAt(t)&255);return e}function bo(r,e){for(var t,n,i,s=[],o=0;o<r.length&&!((e-=2)<0);++o)t=r.charCodeAt(o),n=t>>8,i=t%256,s.push(i),s.push(n);return s}function sn(r){return Kt.toByteArray(go(r))}function ft(r,e,t,n){for(var i=0;i<n&&!(i+t>=e.length||i>=r.length);++i)e[i+t]=r[i];return i}function yo(r){return r!==r}});var on=j(()=>{});var Zt={};st(Zt,{__assign:()=>Yt,__asyncDelegator:()=>ko,__asyncGenerator:()=>Do,__asyncValues:()=>No,__await:()=>Je,__awaiter:()=>Ro,__classPrivateFieldGet:()=>Mo,__classPrivateFieldSet:()=>Vo,__createBinding:()=>Po,__decorate:()=>Eo,__exportStar:()=>xo,__extends:()=>Ao,__generator:()=>Io,__importDefault:()=>Oo,__importStar:()=>Lo,__makeTemplateObject:()=>Fo,__metadata:()=>To,__param:()=>vo,__read:()=>an,__rest:()=>So,__spread:()=>Uo,__spreadArrays:()=>Co,__values:()=>Xt});function Ao(r,e){zt(r,e);function t(){this.constructor=r;}r.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t);}function So(r,e){var t={};for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&e.indexOf(n)<0&&(t[n]=r[n]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(r);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(r,n[i])&&(t[n[i]]=r[n[i]]);return t}function Eo(r,e,t,n){var i=arguments.length,s=i<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(o=r[a])&&(s=(i<3?o(s):i>3?o(e,t,s):o(e,t))||s);return i>3&&s&&Object.defineProperty(e,t,s),s}function vo(r,e){return function(t,n){e(t,n,r);}}function To(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)}function Ro(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s);})}return new(t||(t=Promise))(function(s,o){function a(d){try{c(n.next(d));}catch(l){o(l);}}function u(d){try{c(n.throw(d));}catch(l){o(l);}}function c(d){d.done?s(d.value):i(d.value).then(a,u);}c((n=n.apply(r,e||[])).next());})}function Io(r,e){var t={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},n,i,s,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(c){return function(d){return u([c,d])}}function u(c){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,i&&(s=c[0]&2?i.return:c[0]?i.throw||((s=i.return)&&s.call(i),0):i.next)&&!(s=s.call(i,c[1])).done)return s;switch(i=0,s&&(c=[c[0]&2,s.value]),c[0]){case 0:case 1:s=c;break;case 4:return t.label++,{value:c[1],done:!1};case 5:t.label++,i=c[1],c=[0];continue;case 7:c=t.ops.pop(),t.trys.pop();continue;default:if(s=t.trys,!(s=s.length>0&&s[s.length-1])&&(c[0]===6||c[0]===2)){t=0;continue}if(c[0]===3&&(!s||c[1]>s[0]&&c[1]<s[3])){t.label=c[1];break}if(c[0]===6&&t.label<s[1]){t.label=s[1],s=c;break}if(s&&t.label<s[2]){t.label=s[2],t.ops.push(c);break}s[2]&&t.ops.pop(),t.trys.pop();continue}c=e.call(r,t);}catch(d){c=[6,d],i=0;}finally{n=s=0;}if(c[0]&5)throw c[1];return {value:c[0]?c[1]:void 0,done:true}}}function Po(r,e,t,n){n===void 0&&(n=t),r[n]=e[t];}function xo(r,e){for(var t in r)t!=="default"&&!e.hasOwnProperty(t)&&(e[t]=r[t]);}function Xt(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],n=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return {next:function(){return r&&n>=r.length&&(r=void 0),{value:r&&r[n++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function an(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),i,s=[],o;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)s.push(i.value);}catch(a){o={error:a};}finally{try{i&&!i.done&&(t=n.return)&&t.call(n);}finally{if(o)throw o.error}}return s}function Uo(){for(var r=[],e=0;e<arguments.length;e++)r=r.concat(an(arguments[e]));return r}function Co(){for(var r=0,e=0,t=arguments.length;e<t;e++)r+=arguments[e].length;for(var n=Array(r),i=0,e=0;e<t;e++)for(var s=arguments[e],o=0,a=s.length;o<a;o++,i++)n[i]=s[o];return n}function Je(r){return this instanceof Je?(this.v=r,this):new Je(r)}function Do(r,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=t.apply(r,e||[]),i,s=[];return i={},o("next"),o("throw"),o("return"),i[Symbol.asyncIterator]=function(){return this},i;function o(g){n[g]&&(i[g]=function(p){return new Promise(function(h,b){s.push([g,p,h,b])>1||a(g,p);})});}function a(g,p){try{u(n[g](p));}catch(h){l(s[0][3],h);}}function u(g){g.value instanceof Je?Promise.resolve(g.value.v).then(c,d):l(s[0][2],g);}function c(g){a("next",g);}function d(g){a("throw",g);}function l(g,p){g(p),s.shift(),s.length&&a(s[0][0],s[0][1]);}}function ko(r){var e,t;return e={},n("next"),n("throw",function(i){throw i}),n("return"),e[Symbol.iterator]=function(){return this},e;function n(i,s){e[i]=r[i]?function(o){return (t=!t)?{value:Je(r[i](o)),done:i==="return"}:s?s(o):o}:s;}}function No(r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=r[Symbol.asyncIterator],t;return e?e.call(r):(r=typeof Xt=="function"?Xt(r):r[Symbol.iterator](),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(s){t[s]=r[s]&&function(o){return new Promise(function(a,u){o=r[s](o),i(a,u,o.done,o.value);})};}function i(s,o,a,u){Promise.resolve(u).then(function(c){s({value:c,done:a});},o);}}function Fo(r,e){return Object.defineProperty?Object.defineProperty(r,"raw",{value:e}):r.raw=e,r}function Lo(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)Object.hasOwnProperty.call(r,t)&&(e[t]=r[t]);return e.default=r,e}function Oo(r){return r&&r.__esModule?r:{default:r}}function Mo(r,e){if(!e.has(r))throw new TypeError("attempted to get private field on non-instance");return e.get(r)}function Vo(r,e,t){if(!e.has(r))throw new TypeError("attempted to set private field on non-instance");return e.set(r,t),t}var zt,Yt,er=ke(()=>{zt=function(r,e){return zt=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,n){t.__proto__=n;}||function(t,n){for(var i in n)n.hasOwnProperty(i)&&(t[i]=n[i]);},zt(r,e)};Yt=function(){return Yt=Object.assign||function(e){for(var t,n=1,i=arguments.length;n<i;n++){t=arguments[n];for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&(e[s]=t[s]);}return e},Yt.apply(this,arguments)};});var tr=j(Z=>{Object.defineProperty(Z,"__esModule",{value:true});Z.MAX_HASHABLE_LENGTH=Z.INIT=Z.KEY=Z.DIGEST_LENGTH=Z.BLOCK_SIZE=void 0;Z.BLOCK_SIZE=64;Z.DIGEST_LENGTH=32;Z.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]);Z.INIT=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225];Z.MAX_HASHABLE_LENGTH=Math.pow(2,53)-1;});var un=j(gt=>{Object.defineProperty(gt,"__esModule",{value:true});gt.RawSha256=void 0;var ee=tr(),qo=(function(){function r(){this.state=Int32Array.from(ee.INIT),this.temp=new Int32Array(64),this.buffer=new Uint8Array(64),this.bufferLength=0,this.bytesHashed=0,this.finished=false;}return r.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,this.bytesHashed*8>ee.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===ee.BLOCK_SIZE&&(this.hashBuffer(),this.bufferLength=0);},r.prototype.digest=function(){if(!this.finished){var e=this.bytesHashed*8,t=new DataView(this.buffer.buffer,this.buffer.byteOffset,this.buffer.byteLength),n=this.bufferLength;if(t.setUint8(this.bufferLength++,128),n%ee.BLOCK_SIZE>=ee.BLOCK_SIZE-8){for(var i=this.bufferLength;i<ee.BLOCK_SIZE;i++)t.setUint8(i,0);this.hashBuffer(),this.bufferLength=0;}for(var i=this.bufferLength;i<ee.BLOCK_SIZE-8;i++)t.setUint8(i,0);t.setUint32(ee.BLOCK_SIZE-8,Math.floor(e/4294967296),true),t.setUint32(ee.BLOCK_SIZE-4,e),this.hashBuffer(),this.finished=true;}for(var s=new Uint8Array(ee.DIGEST_LENGTH),i=0;i<8;i++)s[i*4]=this.state[i]>>>24&255,s[i*4+1]=this.state[i]>>>16&255,s[i*4+2]=this.state[i]>>>8&255,s[i*4+3]=this.state[i]>>>0&255;return s},r.prototype.hashBuffer=function(){for(var e=this,t=e.buffer,n=e.state,i=n[0],s=n[1],o=n[2],a=n[3],u=n[4],c=n[5],d=n[6],l=n[7],g=0;g<ee.BLOCK_SIZE;g++){if(g<16)this.temp[g]=(t[g*4]&255)<<24|(t[g*4+1]&255)<<16|(t[g*4+2]&255)<<8|t[g*4+3]&255;else {var p=this.temp[g-2],h=(p>>>17|p<<15)^(p>>>19|p<<13)^p>>>10;p=this.temp[g-15];var b=(p>>>7|p<<25)^(p>>>18|p<<14)^p>>>3;this.temp[g]=(h+this.temp[g-7]|0)+(b+this.temp[g-16]|0);}var w=(((u>>>6|u<<26)^(u>>>11|u<<21)^(u>>>25|u<<7))+(u&c^~u&d)|0)+(l+(ee.KEY[g]+this.temp[g]|0)|0)|0,_=((i>>>2|i<<30)^(i>>>13|i<<19)^(i>>>22|i<<10))+(i&s^i&o^s&o)|0;l=d,d=c,c=u,u=a+w|0,a=o,o=s,s=i,i=w+_|0;}n[0]+=i,n[1]+=s,n[2]+=o,n[3]+=a,n[4]+=u,n[5]+=c,n[6]+=d,n[7]+=l;},r})();gt.RawSha256=qo;});var cn,ln,dn=ke(()=>{cn=r=>{let e=[];for(let t=0,n=r.length;t<n;t++){let i=r.charCodeAt(t);if(i<128)e.push(i);else if(i<2048)e.push(i>>6|192,i&63|128);else if(t+1<r.length&&(i&64512)===55296&&(r.charCodeAt(t+1)&64512)===56320){let s=65536+((i&1023)<<10)+(r.charCodeAt(++t)&1023);e.push(s>>18|240,s>>12&63|128,s>>6&63|128,s&63|128);}else e.push(i>>12|224,i>>6&63|128,i&63|128);}return Uint8Array.from(e)},ln=r=>{let e="";for(let t=0,n=r.length;t<n;t++){let i=r[t];if(i<128)e+=String.fromCharCode(i);else if(192<=i&&i<224){let s=r[++t];e+=String.fromCharCode((i&31)<<6|s&63);}else if(240<=i&&i<365){let o="%"+[i,r[++t],r[++t],r[++t]].map(a=>a.toString(16)).join("%");e+=decodeURIComponent(o);}else e+=String.fromCharCode((i&15)<<12|(r[++t]&63)<<6|r[++t]&63);}return e};});function fn(r){return new TextEncoder().encode(r)}function hn(r){return new TextDecoder("utf-8").decode(r)}var gn=ke(()=>{});var pn={};st(pn,{fromUtf8:()=>Bo,toUtf8:()=>$o});var Bo,$o,mn=ke(()=>{dn();gn();Bo=r=>typeof TextEncoder=="function"?fn(r):cn(r),$o=r=>typeof TextDecoder=="function"?hn(r):ln(r);});var _n=j(pt=>{Object.defineProperty(pt,"__esModule",{value:true});pt.convertToBuffer=void 0;var jo=(mn(),re(pn)),Ko=typeof Buffer<"u"&&Buffer.from?function(r){return Buffer.from(r,"utf8")}:jo.fromUtf8;function Ho(r){return r instanceof Uint8Array?r:typeof r=="string"?Ko(r):ArrayBuffer.isView(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(r)}pt.convertToBuffer=Ho;});var bn=j(mt=>{Object.defineProperty(mt,"__esModule",{value:true});mt.isEmptyData=void 0;function Wo(r){return typeof r=="string"?r.length===0:r.byteLength===0}mt.isEmptyData=Wo;});var yn=j(_t=>{Object.defineProperty(_t,"__esModule",{value:true});_t.numToUint8=void 0;function Jo(r){return new Uint8Array([(r&4278190080)>>24,(r&16711680)>>16,(r&65280)>>8,r&255])}_t.numToUint8=Jo;});var wn=j(bt=>{Object.defineProperty(bt,"__esModule",{value:true});bt.uint32ArrayFrom=void 0;function Go(r){if(!Array.from){for(var e=new Uint32Array(r.length),t=0;t<r.length;)e[t]=r[t];return e}return Uint32Array.from(r)}bt.uint32ArrayFrom=Go;});var An=j(ue=>{Object.defineProperty(ue,"__esModule",{value:true});ue.uint32ArrayFrom=ue.numToUint8=ue.isEmptyData=ue.convertToBuffer=void 0;var Qo=_n();Object.defineProperty(ue,"convertToBuffer",{enumerable:true,get:function(){return Qo.convertToBuffer}});var zo=bn();Object.defineProperty(ue,"isEmptyData",{enumerable:true,get:function(){return zo.isEmptyData}});var Yo=yn();Object.defineProperty(ue,"numToUint8",{enumerable:true,get:function(){return Yo.numToUint8}});var Xo=wn();Object.defineProperty(ue,"uint32ArrayFrom",{enumerable:true,get:function(){return Xo.uint32ArrayFrom}});});var En=j(wt=>{Object.defineProperty(wt,"__esModule",{value:true});wt.Sha256=void 0;var Sn=(er(),re(Zt)),yt=tr(),rr=un(),nr=An(),Zo=(function(){function r(e){if(this.hash=new rr.RawSha256,e){this.outer=new rr.RawSha256;var t=ea(e),n=new Uint8Array(yt.BLOCK_SIZE);n.set(t);for(var i=0;i<yt.BLOCK_SIZE;i++)t[i]^=54,n[i]^=92;this.hash.update(t),this.outer.update(n);for(var i=0;i<t.byteLength;i++)t[i]=0;}}return r.prototype.update=function(e){if(!((0, nr.isEmptyData)(e)||this.error))try{this.hash.update((0,nr.convertToBuffer)(e));}catch(t){this.error=t;}},r.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()},r.prototype.digest=function(){return (0, Sn.__awaiter)(this,void 0,void 0,function(){return (0, Sn.__generator)(this,function(e){return [2,this.digestSync()]})})},r})();wt.Sha256=Zo;function ea(r){var e=(0, nr.convertToBuffer)(r);if(e.byteLength>yt.BLOCK_SIZE){var t=new rr.RawSha256;t.update(e),e=t.digest();}var n=new Uint8Array(yt.BLOCK_SIZE);return n.set(e),n}});var sr=j(ir=>{Object.defineProperty(ir,"__esModule",{value:true});var ta=(er(),re(Zt));(0, ta.__exportStar)(En(),ir);});var gr={};st(gr,{default:()=>Qa});function Qa(r,e){return e=e||{},new Promise(function(t,n){var i=new XMLHttpRequest,s=[],o=[],a={},u=function(){return {ok:(i.status/100|0)==2,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:u,headers:{keys:function(){return s},entries:function(){return o},get:function(d){return a[d.toLowerCase()]},has:function(d){return d.toLowerCase()in a}}}};for(var c in i.open(e.method||"get",r,true),i.onload=function(){i.getAllResponseHeaders().replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm,function(d,l,g){s.push(l=l.toLowerCase()),o.push([l,g]),a[l]=a[l]?a[l]+","+g:g;}),t(u());},i.onerror=n,i.withCredentials=e.credentials=="include",e.headers)i.setRequestHeader(c,e.headers[c]);i.send(e.body||null);})}var pr=ke(()=>{});var Dn=j((Yc,Cn)=>{Cn.exports=self.fetch||(self.fetch=(pr(),re(gr)).default||(pr(),re(gr)));});var Vn=j((On,Mn)=>{(function(r){var e;if(typeof define=="function"&&define.amd&&(define(r),e=true),typeof On=="object"&&(Mn.exports=r(),e=true),!e){var t=window.Cookies,n=window.Cookies=r();n.noConflict=function(){return window.Cookies=t,n};}})(function(){function r(){for(var n=0,i={};n<arguments.length;n++){var s=arguments[n];for(var o in s)i[o]=s[o];}return i}function e(n){return n.replace(/(%[0-9A-Z]{2})+/g,decodeURIComponent)}function t(n){function i(){}function s(a,u,c){if(!(typeof document>"u")){c=r({path:"/"},i.defaults,c),typeof c.expires=="number"&&(c.expires=new Date(new Date*1+c.expires*864e5)),c.expires=c.expires?c.expires.toUTCString():"";try{var d=JSON.stringify(u);/^[\{\[]/.test(d)&&(u=d);}catch{}u=n.write?n.write(u,a):encodeURIComponent(String(u)).replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g,decodeURIComponent),a=encodeURIComponent(String(a)).replace(/%(23|24|26|2B|5E|60|7C)/g,decodeURIComponent).replace(/[\(\)]/g,escape);var l="";for(var g in c)c[g]&&(l+="; "+g,c[g]!==true&&(l+="="+c[g].split(";")[0]));return document.cookie=a+"="+u+l}}function o(a,u){if(!(typeof document>"u")){for(var c={},d=document.cookie?document.cookie.split("; "):[],l=0;l<d.length;l++){var g=d[l].split("="),p=g.slice(1).join("=");!u&&p.charAt(0)==='"'&&(p=p.slice(1,-1));try{var h=e(g[0]);if(p=(n.read||n)(p,h)||e(p),u)try{p=JSON.parse(p);}catch{}if(c[h]=p,a===h)break}catch{}}return a?c[a]:c}}return i.set=s,i.get=function(a){return o(a,false)},i.getJSON=function(a){return o(a,true)},i.remove=function(a,u){s(a,"",r(u,{expires:-1}));},i.defaults={},i.withConverter=t,i}return t(function(){})});});var he=typeof globalThis<"u"?globalThis:void 0,ot=he?.window;function Vs(r){if(Buffer)return Buffer.from(r).toString("base64");let e="",t=new Uint8Array(r),n=32768;for(let i=0;i<t.length;i+=n){let s=t.subarray(i,i+n);e+=String.fromCharCode.apply(null,Array.from(s));}if(typeof btoa=="function")return btoa(e);throw new Error("No base64 encoder available in this environment.")}if(ot)ot.global=ot,ot.global._runningInNodeJS=false;else if(he&&(he.global=he,typeof he.window>"u")){class r{constructor(){this.result=null;this.error=null;this.onload=null;this.onloadend=null;this.onerror=null;}readAsDataURL(n){n.arrayBuffer().then(i=>{let s=Vs(i),o=n.type||"application/octet-stream";this.result=`data:${o};base64,${s}`,this.onload&&this.onload({target:this}),this.onloadend&&this.onloadend({target:this});}).catch(i=>{this.error=i,this.onerror&&this.onerror({target:this});});}readAsArrayBuffer(n){n.arrayBuffer().then(i=>{this.result=i,this.onload&&this.onload({target:this}),this.onloadend&&this.onloadend({target:this});}).catch(i=>{this.error=i,this.onerror&&this.onerror({target:this});});}readAsText(n,i="utf-8"){n.text().then(s=>{this.result=s,this.onload&&this.onload({target:this}),this.onloadend&&this.onloadend({target:this});}).catch(s=>{this.error=s,this.onerror&&this.onerror({target:this});});}}he.FileReader=r;class e{constructor(){this.status=0;this.statusText="";this.readyState=0;this.responseText="";this.response=null;this.responseType="";this.responseURL="";this.timeout=0;this.withCredentials=false;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=false;}open(n,i){this._method=n,this._url=i,this.readyState=1;}setRequestHeader(n,i){this._headers[n]=i;}getResponseHeader(n){return null}abort(){this._aborted=true,this.onabort&&this.onabort({});}send(n){if(this._aborted)return;let i={method:this._method,headers:this._headers};n&&this._method!=="GET"&&this._method!=="HEAD"&&(i.body=n),fetch(this._url,i).then(async s=>{if(!this._aborted){if(this.status=s.status,this.statusText=s.statusText,this.responseURL=s.url,this.readyState=4,this.responseType==="blob")this.response=await s.blob();else if(this.responseType==="json")try{this.response=await s.json();}catch{this.response=null;}else this.responseType==="arraybuffer"?this.response=await s.arrayBuffer():(this.responseText=await s.text(),this.response=this.responseText);this.onload&&this.onload({});}}).catch(s=>{this._aborted||this.onerror&&this.onerror(s);});}}he.XMLHttpRequest=e,he.window={_runningInNodeJS:true,alert:t=>console.error("[Alert]",t),sessionStorage:{getItem:t=>null,setItem:(t,n)=>{},removeItem:t=>{}},localStorage:{getItem:t=>{let n=(Ie(),re(Re)),i=(Ie(),re(Re));try{let s=i.resolve(process.cwd(),"states","localStorage",`${t}.skapi`);return n.existsSync(s)?n.readFileSync(s,"utf8"):null}catch{return null}},setItem:(t,n)=>{let i=(Ie(),re(Re)),s=(Ie(),re(Re));try{let o=s.resolve(process.cwd(),"states","localStorage");i.existsSync(o)||i.mkdirSync(o,{recursive:!0});let a=s.resolve(o,`${t}.skapi`);i.writeFileSync(a,n,"utf8");}catch{}},removeItem:t=>{let n=(Ie(),re(Re)),i=(Ie(),re(Re));try{let s=i.resolve(process.cwd(),"states","localStorage",`${t}.skapi`);n.existsSync(s)&&n.unlinkSync(s);}catch{}}},location:{href:"",origin:"",hostname:"",protocol:"",replace:t=>{}},navigator:{userAgent:`nodejs/${he?.process?.versions?.node||"unknown"}`,mediaDevices:{getUserMedia:async t=>{throw new Error("getUserMedia is not supported in Node.js environment.")}}},addEventListener:()=>{},removeEventListener:()=>{}};}var Bt=(function(){function r(t){var n=t||{},i=n.ValidationData,s=n.Username,o=n.Password,a=n.AuthParameters,u=n.ClientMetadata;this.validationData=i||{},this.authParameters=a||{},this.clientMetadata=u||{},this.username=s,this.password=o;}var e=r.prototype;return e.getUsername=function(){return this.username},e.getPassword=function(){return this.password},e.getValidationData=function(){return this.validationData},e.getAuthParameters=function(){return this.authParameters},e.getClientMetadata=function(){return this.clientMetadata},r})();var pe=Te(ht());var X;typeof window<"u"&&window.crypto&&(X=window.crypto);!X&&typeof window<"u"&&window.msCrypto&&(X=window.msCrypto);!X&&typeof globalThis<"u"&&globalThis.crypto&&(X=globalThis.crypto);if(!X&&typeof Mr=="function")try{X=on();}catch{}function Gt(){if(X){if(typeof X.getRandomValues=="function")try{return X.getRandomValues(new Uint32Array(1))[0]}catch{}if(typeof X.randomBytes=="function")try{return X.randomBytes(4).readInt32LE()}catch{}}throw new Error("Native crypto module could not be used to get secure random number.")}function wo(r){for(var e=r.words,t=r.sigBytes,n=[],i=0;i<t;i++){var s=e[i>>>2]>>>24-i%4*8&255;n.push((s>>>4).toString(16)),n.push((s&15).toString(16));}return n.join("")}var Qt=(function(){function r(t,n){t=this.words=t||[],n!=null?this.sigBytes=n:this.sigBytes=t.length*4;}var e=r.prototype;return e.random=function(n){for(var i=[],s=0;s<n;s+=4)i.push(Gt());return new r(i,n)},e.toString=function(){return wo(this)},r})();var St=Te(sr());var M=U;function U(r,e){r!=null&&this.fromString(r,e);}function H(){return new U(null)}var ye,ra=0xdeadbeefcafe,vn=(ra&16777215)==15715070;function na(r,e,t,n,i,s){for(;--s>=0;){var o=e*this[r++]+t[n]+i;i=Math.floor(o/67108864),t[n++]=o&67108863;}return i}function ia(r,e,t,n,i,s){for(var o=e&32767,a=e>>15;--s>=0;){var u=this[r]&32767,c=this[r++]>>15,d=a*u+c*o;u=o*u+((d&32767)<<15)+t[n]+(i&1073741823),i=(u>>>30)+(d>>>15)+a*c+(i>>>30),t[n++]=u&1073741823;}return i}function sa(r,e,t,n,i,s){for(var o=e&16383,a=e>>14;--s>=0;){var u=this[r]&16383,c=this[r++]>>14,d=a*u+c*o;u=o*u+((d&16383)<<14)+t[n]+i,i=(u>>28)+(d>>14)+a*c,t[n++]=u&268435455;}return i}var Tn=typeof navigator<"u";Tn&&vn&&navigator.appName=="Microsoft Internet Explorer"?(U.prototype.am=ia,ye=30):Tn&&vn&&navigator.appName!="Netscape"?(U.prototype.am=na,ye=26):(U.prototype.am=sa,ye=28);U.prototype.DB=ye;U.prototype.DM=(1<<ye)-1;U.prototype.DV=1<<ye;var or=52;U.prototype.FV=Math.pow(2,or);U.prototype.F1=or-ye;U.prototype.F2=2*ye-or;var oa="0123456789abcdefghijklmnopqrstuvwxyz",At=new Array,Le,te;Le=48;for(te=0;te<=9;++te)At[Le++]=te;Le=97;for(te=10;te<36;++te)At[Le++]=te;Le=65;for(te=10;te<36;++te)At[Le++]=te;function Rn(r){return oa.charAt(r)}function aa(r,e){var t=At[r.charCodeAt(e)];return t??-1}function ua(r){for(var e=this.t-1;e>=0;--e)r[e]=this[e];r.t=this.t,r.s=this.s;}function ca(r){this.t=1,this.s=r<0?-1:0,r>0?this[0]=r:r<-1?this[0]=r+this.DV:this.t=0;}function ar(r){var e=H();return e.fromInt(r),e}function la(r,e){var t;if(e==16)t=4;else if(e==8)t=3;else if(e==2)t=1;else if(e==32)t=5;else if(e==4)t=2;else throw new Error("Only radix 2, 4, 8, 16, 32 are supported");this.t=0,this.s=0;for(var n=r.length,i=false,s=0;--n>=0;){var o=aa(r,n);if(o<0){r.charAt(n)=="-"&&(i=true);continue}i=false,s==0?this[this.t++]=o:s+t>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+=t,s>=this.DB&&(s-=this.DB);}this.clamp(),i&&U.ZERO.subTo(this,this);}function da(){for(var r=this.s&this.DM;this.t>0&&this[this.t-1]==r;)--this.t;}function fa(r){if(this.s<0)return "-"+this.negate().toString(r);var e;if(r==16)e=4;else if(r==8)e=3;else if(r==2)e=1;else if(r==32)e=5;else if(r==4)e=2;else throw new Error("Only radix 2, 4, 8, 16, 32 are supported");var t=(1<<e)-1,n,i=false,s="",o=this.t,a=this.DB-o*this.DB%e;if(o-- >0)for(a<this.DB&&(n=this[o]>>a)>0&&(i=true,s=Rn(n));o>=0;)a<e?(n=(this[o]&(1<<a)-1)<<e-a,n|=this[--o]>>(a+=this.DB-e)):(n=this[o]>>(a-=e)&t,a<=0&&(a+=this.DB,--o)),n>0&&(i=true),i&&(s+=Rn(n));return i?s:"0"}function ha(){var r=H();return U.ZERO.subTo(this,r),r}function ga(){return this.s<0?this.negate():this}function pa(r){var e=this.s-r.s;if(e!=0)return e;var t=this.t;if(e=t-r.t,e!=0)return this.s<0?-e:e;for(;--t>=0;)if((e=this[t]-r[t])!=0)return e;return 0}function ur(r){var e=1,t;return (t=r>>>16)!=0&&(r=t,e+=16),(t=r>>8)!=0&&(r=t,e+=8),(t=r>>4)!=0&&(r=t,e+=4),(t=r>>2)!=0&&(r=t,e+=2),(t=r>>1)!=0&&(r=t,e+=1),e}function ma(){return this.t<=0?0:this.DB*(this.t-1)+ur(this[this.t-1]^this.s&this.DM)}function _a(r,e){var t;for(t=this.t-1;t>=0;--t)e[t+r]=this[t];for(t=r-1;t>=0;--t)e[t]=0;e.t=this.t+r,e.s=this.s;}function ba(r,e){for(var t=r;t<this.t;++t)e[t-r]=this[t];e.t=Math.max(this.t-r,0),e.s=this.s;}function ya(r,e){var t=r%this.DB,n=this.DB-t,i=(1<<n)-1,s=Math.floor(r/this.DB),o=this.s<<t&this.DM,a;for(a=this.t-1;a>=0;--a)e[a+s+1]=this[a]>>n|o,o=(this[a]&i)<<t;for(a=s-1;a>=0;--a)e[a]=0;e[s]=o,e.t=this.t+s+1,e.s=this.s,e.clamp();}function wa(r,e){e.s=this.s;var t=Math.floor(r/this.DB);if(t>=this.t){e.t=0;return}var n=r%this.DB,i=this.DB-n,s=(1<<n)-1;e[0]=this[t]>>n;for(var o=t+1;o<this.t;++o)e[o-t-1]|=(this[o]&s)<<i,e[o-t]=this[o]>>n;n>0&&(e[this.t-t-1]|=(this.s&s)<<i),e.t=this.t-t,e.clamp();}function Aa(r,e){for(var t=0,n=0,i=Math.min(r.t,this.t);t<i;)n+=this[t]-r[t],e[t++]=n&this.DM,n>>=this.DB;if(r.t<this.t){for(n-=r.s;t<this.t;)n+=this[t],e[t++]=n&this.DM,n>>=this.DB;n+=this.s;}else {for(n+=this.s;t<r.t;)n-=r[t],e[t++]=n&this.DM,n>>=this.DB;n-=r.s;}e.s=n<0?-1:0,n<-1?e[t++]=this.DV+n:n>0&&(e[t++]=n),e.t=t,e.clamp();}function Sa(r,e){var t=this.abs(),n=r.abs(),i=t.t;for(e.t=i+n.t;--i>=0;)e[i]=0;for(i=0;i<n.t;++i)e[i+t.t]=t.am(0,n[i],e,i,0,t.t);e.s=0,e.clamp(),this.s!=r.s&&U.ZERO.subTo(e,e);}function Ea(r){for(var e=this.abs(),t=r.t=2*e.t;--t>=0;)r[t]=0;for(t=0;t<e.t-1;++t){var n=e.am(t,e[t],r,2*t,0,1);(r[t+e.t]+=e.am(t+1,2*e[t],r,2*t+1,n,e.t-t-1))>=e.DV&&(r[t+e.t]-=e.DV,r[t+e.t+1]=1);}r.t>0&&(r[r.t-1]+=e.am(t,e[t],r,2*t,0,1)),r.s=0,r.clamp();}function va(r,e,t){var n=r.abs();if(!(n.t<=0)){var i=this.abs();if(i.t<n.t){e?.fromInt(0),t!=null&&this.copyTo(t);return}t==null&&(t=H());var s=H(),o=this.s,a=r.s,u=this.DB-ur(n[n.t-1]);u>0?(n.lShiftTo(u,s),i.lShiftTo(u,t)):(n.copyTo(s),i.copyTo(t));var c=s.t,d=s[c-1];if(d!=0){var l=d*(1<<this.F1)+(c>1?s[c-2]>>this.F2:0),g=this.FV/l,p=(1<<this.F1)/l,h=1<<this.F2,b=t.t,w=b-c,_=e??H();for(s.dlShiftTo(w,_),t.compareTo(_)>=0&&(t[t.t++]=1,t.subTo(_,t)),U.ONE.dlShiftTo(c,_),_.subTo(s,s);s.t<c;)s[s.t++]=0;for(;--w>=0;){var R=t[--b]==d?this.DM:Math.floor(t[b]*g+(t[b-1]+h)*p);if((t[b]+=s.am(0,R,t,w,0,c))<R)for(s.dlShiftTo(w,_),t.subTo(_,t);t[b]<--R;)t.subTo(_,t);}e!=null&&(t.drShiftTo(c,e),o!=a&&U.ZERO.subTo(e,e)),t.t=c,t.clamp(),u>0&&t.rShiftTo(u,t),o<0&&U.ZERO.subTo(t,t);}}}function Ta(r){var e=H();return this.abs().divRemTo(r,null,e),this.s<0&&e.compareTo(U.ZERO)>0&&r.subTo(e,e),e}function Ra(){if(this.t<1)return 0;var r=this[0];if((r&1)==0)return 0;var e=r&3;return e=e*(2-(r&15)*e)&15,e=e*(2-(r&255)*e)&255,e=e*(2-((r&65535)*e&65535))&65535,e=e*(2-r*e%this.DV)%this.DV,e>0?this.DV-e:-e}function Ia(r){return this.compareTo(r)==0}function Pa(r,e){for(var t=0,n=0,i=Math.min(r.t,this.t);t<i;)n+=this[t]+r[t],e[t++]=n&this.DM,n>>=this.DB;if(r.t<this.t){for(n+=r.s;t<this.t;)n+=this[t],e[t++]=n&this.DM,n>>=this.DB;n+=this.s;}else {for(n+=this.s;t<r.t;)n+=r[t],e[t++]=n&this.DM,n>>=this.DB;n+=r.s;}e.s=n<0?-1:0,n>0?e[t++]=n:n<-1&&(e[t++]=this.DV+n),e.t=t,e.clamp();}function xa(r){var e=H();return this.addTo(r,e),e}function Ua(r){var e=H();return this.subTo(r,e),e}function Ca(r){var e=H();return this.multiplyTo(r,e),e}function Da(r){var e=H();return this.divRemTo(r,e,null),e}function Oe(r){this.m=r,this.mp=r.invDigit(),this.mpl=this.mp&32767,this.mph=this.mp>>15,this.um=(1<<r.DB-15)-1,this.mt2=2*r.t;}function ka(r){var e=H();return r.abs().dlShiftTo(this.m.t,e),e.divRemTo(this.m,null,e),r.s<0&&e.compareTo(U.ZERO)>0&&this.m.subTo(e,e),e}function Na(r){var e=H();return r.copyTo(e),this.reduce(e),e}function Fa(r){for(;r.t<=this.mt2;)r[r.t++]=0;for(var e=0;e<this.m.t;++e){var t=r[e]&32767,n=t*this.mpl+((t*this.mph+(r[e]>>15)*this.mpl&this.um)<<15)&r.DM;for(t=e+this.m.t,r[t]+=this.m.am(0,n,r,e,0,this.m.t);r[t]>=r.DV;)r[t]-=r.DV,r[++t]++;}r.clamp(),r.drShiftTo(this.m.t,r),r.compareTo(this.m)>=0&&r.subTo(this.m,r);}function La(r,e){r.squareTo(e),this.reduce(e);}function Oa(r,e,t){r.multiplyTo(e,t),this.reduce(t);}Oe.prototype.convert=ka;Oe.prototype.revert=Na;Oe.prototype.reduce=Fa;Oe.prototype.mulTo=Oa;Oe.prototype.sqrTo=La;function Ma(r,e,t){var n=r.bitLength(),i,s=ar(1),o=new Oe(e);if(n<=0)return s;n<18?i=1:n<48?i=3:n<144?i=4:n<768?i=5:i=6;var a=new Array,u=3,c=i-1,d=(1<<i)-1;if(a[1]=o.convert(this),i>1){var l=H();for(o.sqrTo(a[1],l);u<=d;)a[u]=H(),o.mulTo(l,a[u-2],a[u]),u+=2;}var g=r.t-1,p,h=true,b=H(),w;for(n=ur(r[g])-1;g>=0;){for(n>=c?p=r[g]>>n-c&d:(p=(r[g]&(1<<n+1)-1)<<c-n,g>0&&(p|=r[g-1]>>this.DB+n-c)),u=i;(p&1)==0;)p>>=1,--u;if((n-=u)<0&&(n+=this.DB,--g),h)a[p].copyTo(s),h=false;else {for(;u>1;)o.sqrTo(s,b),o.sqrTo(b,s),u-=2;u>0?o.sqrTo(s,b):(w=s,s=b,b=w),o.mulTo(b,a[p],s);}for(;g>=0&&(r[g]&1<<n)==0;)o.sqrTo(s,b),w=s,s=b,b=w,--n<0&&(n=this.DB-1,--g);}var _=o.revert(s);return t(null,_),_}U.prototype.copyTo=ua;U.prototype.fromInt=ca;U.prototype.fromString=la;U.prototype.clamp=da;U.prototype.dlShiftTo=_a;U.prototype.drShiftTo=ba;U.prototype.lShiftTo=ya;U.prototype.rShiftTo=wa;U.prototype.subTo=Aa;U.prototype.multiplyTo=Sa;U.prototype.squareTo=Ea;U.prototype.divRemTo=va;U.prototype.invDigit=Ra;U.prototype.addTo=Pa;U.prototype.toString=fa;U.prototype.negate=ha;U.prototype.abs=ga;U.prototype.compareTo=pa;U.prototype.bitLength=ma;U.prototype.mod=Ta;U.prototype.equals=Ia;U.prototype.add=xa;U.prototype.subtract=Ua;U.prototype.multiply=Ca;U.prototype.divide=Da;U.prototype.modPow=Ma;U.ZERO=ar(0);U.ONE=ar(1);function cr(r){return pe.Buffer.from(new Qt().random(r).toString(),"hex")}var Va=/^[89a-f]/i,qa="FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200CBBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF",Ba="userAttributes.",we=(function(){function r(t){this.N=new M(qa,16),this.g=new M("2",16),this.k=new M(this.hexHash(""+this.padHex(this.N)+this.padHex(this.g)),16),this.smallAValue=this.generateRandomSmallA(),this.getLargeAValue(function(){}),this.infoBits=pe.Buffer.from("Caldera Derived Key","utf8"),this.poolName=t;}var e=r.prototype;return e.getSmallAValue=function(){return this.smallAValue},e.getLargeAValue=function(n){var i=this;this.largeAValue?n(null,this.largeAValue):this.calculateA(this.smallAValue,function(s,o){s&&n(s,null),i.largeAValue=o,n(null,i.largeAValue);});},e.generateRandomSmallA=function(){var n=cr(128).toString("hex"),i=new M(n,16);return i},e.generateRandomString=function(){return cr(40).toString("base64")},e.getRandomPassword=function(){return this.randomPassword},e.getSaltDevices=function(){return this.SaltToHashDevices},e.getVerifierDevices=function(){return this.verifierDevices},e.generateHashDevice=function(n,i,s){var o=this;this.randomPassword=this.generateRandomString();var a=""+n+i+":"+this.randomPassword,u=this.hash(a),c=cr(16).toString("hex");this.SaltToHashDevices=this.padHex(new M(c,16)),this.g.modPow(new M(this.hexHash(this.SaltToHashDevices+u),16),this.N,function(d,l){d&&s(d,null),o.verifierDevices=o.padHex(l),s(null,null);});},e.calculateA=function(n,i){var s=this;this.g.modPow(n,this.N,function(o,a){o&&i(o,null),a.mod(s.N).equals(M.ZERO)&&i(new Error("Illegal paramater. A mod N cannot be 0."),null),i(null,a);});},e.calculateU=function(n,i){this.UHexHash=this.hexHash(this.padHex(n)+this.padHex(i));var s=new M(this.UHexHash,16);return s},e.hash=function(n){var i=new St.Sha256;i.update(n);var s=i.digestSync(),o=pe.Buffer.from(s).toString("hex");return new Array(64-o.length).join("0")+o},e.hexHash=function(n){return this.hash(pe.Buffer.from(n,"hex"))},e.computehkdf=function(n,i){var s=pe.Buffer.concat([this.infoBits,pe.Buffer.from("","utf8")]),o=new St.Sha256(i);o.update(n);var a=o.digestSync(),u=new St.Sha256(a);u.update(s);var c=u.digestSync(),d=c,l=d.slice(0,16);return l},e.getPasswordAuthenticationKey=function(n,i,s,o,a){var u=this;if(s.mod(this.N).equals(M.ZERO))throw new Error("B cannot be zero.");if(this.UValue=this.calculateU(this.largeAValue,s),this.UValue.equals(M.ZERO))throw new Error("U cannot be zero.");var c=""+this.poolName+n+":"+i,d=this.hash(c),l=new M(this.hexHash(this.padHex(o)+d),16);this.calculateS(l,s,function(g,p){g&&a(g,null);var h=u.computehkdf(pe.Buffer.from(u.padHex(p),"hex"),pe.Buffer.from(u.padHex(u.UValue),"hex"));a(null,h);});},e.calculateS=function(n,i,s){var o=this;this.g.modPow(n,this.N,function(a,u){a&&s(a,null);var c=i.subtract(o.k.multiply(u));c.modPow(o.smallAValue.add(o.UValue.multiply(n)),o.N,function(d,l){d&&s(d,null),s(null,l.mod(o.N));});});},e.getNewPasswordRequiredChallengeUserAttributePrefix=function(){return Ba},e.padHex=function(n){if(!(n instanceof M))throw new Error("Not a BigInteger");var i=n.compareTo(M.ZERO)<0,s=n.abs().toString(16);if(s=s.length%2!==0?"0"+s:s,s=Va.test(s)?"00"+s:s,i){var o=s.split("").map(function(u){var c=~parseInt(u,16)&15;return "0123456789ABCDEF".charAt(c)}).join(""),a=new M(o,16).add(M.ONE);s=a.toString(16),s.toUpperCase().startsWith("FF8")&&(s=s.substring(2));}return s},r})();var In=Te(ht());var Et=(function(){function r(t){this.jwtToken=t||"",this.payload=this.decodePayload();}var e=r.prototype;return e.getJwtToken=function(){return this.jwtToken},e.getExpiration=function(){return this.payload.exp},e.getIssuedAt=function(){return this.payload.iat},e.decodePayload=function(){var n=this.jwtToken.split(".")[1];try{return JSON.parse(In.Buffer.from(n,"base64").toString("utf8"))}catch{return {}}},r})();function $a(r,e){r.prototype=Object.create(e.prototype),r.prototype.constructor=r,lr(r,e);}function lr(r,e){return lr=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,n){return t.__proto__=n,t},lr(r,e)}var Me=(function(r){function e(t){var n=t===void 0?{}:t,i=n.AccessToken;return r.call(this,i||"")||this}return $a(e,r),e})(Et);function ja(r,e){r.prototype=Object.create(e.prototype),r.prototype.constructor=r,dr(r,e);}function dr(r,e){return dr=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,n){return t.__proto__=n,t},dr(r,e)}var Ve=(function(r){function e(t){var n=t===void 0?{}:t,i=n.IdToken;return r.call(this,i||"")||this}return ja(e,r),e})(Et);var qe=(function(){function r(t){var n=t===void 0?{}:t,i=n.RefreshToken;this.token=i||"";}var e=r.prototype;return e.getToken=function(){return this.token},r})();var B=Te(ht()),hr=Te(sr());var Pn="5.0.4";var Ka="aws-amplify/"+Pn,fr={userAgent:Ka,isReactNative:typeof navigator<"u"&&navigator.product==="ReactNative"},xn=function(){return fr.userAgent};var Be=(function(){function r(t){var n=t===void 0?{}:t,i=n.IdToken,s=n.RefreshToken,o=n.AccessToken,a=n.ClockDrift;if(o==null||i==null)throw new Error("Id token and Access Token must be present.");this.idToken=i,this.refreshToken=s,this.accessToken=o,this.clockDrift=a===void 0?this.calculateClockDrift():a;}var e=r.prototype;return e.getIdToken=function(){return this.idToken},e.getRefreshToken=function(){return this.refreshToken},e.getAccessToken=function(){return this.accessToken},e.getClockDrift=function(){return this.clockDrift},e.calculateClockDrift=function(){var n=Math.floor(new Date/1e3),i=Math.min(this.accessToken.getIssuedAt(),this.idToken.getIssuedAt());return n-i},e.isValid=function(){var n=Math.floor(new Date/1e3),i=n-this.clockDrift;return i<this.accessToken.getExpiration()&&i<this.idToken.getExpiration()},r})();var Ha=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],Wa=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],vt=(function(){function r(){}var e=r.prototype;return e.getNowString=function(){var n=new Date,i=Wa[n.getUTCDay()],s=Ha[n.getUTCMonth()],o=n.getUTCDate(),a=n.getUTCHours();a<10&&(a="0"+a);var u=n.getUTCMinutes();u<10&&(u="0"+u);var c=n.getUTCSeconds();c<10&&(c="0"+c);var d=n.getUTCFullYear(),l=i+" "+s+" "+o+" "+a+":"+u+":"+c+" UTC "+d;return l},r})();var ce=(function(){function r(t){var n=t===void 0?{}:t,i=n.Name,s=n.Value;this.Name=i||"",this.Value=s||"";}var e=r.prototype;return e.getValue=function(){return this.Value},e.setValue=function(n){return this.Value=n,this},e.getName=function(){return this.Name},e.setName=function(n){return this.Name=n,this},e.toString=function(){return JSON.stringify(this)},e.toJSON=function(){return {Name:this.Name,Value:this.Value}},r})();var Ue={},Ja=(function(){function r(){}return r.setItem=function(t,n){return Ue[t]=n,Ue[t]},r.getItem=function(t){return Object.prototype.hasOwnProperty.call(Ue,t)?Ue[t]:void 0},r.removeItem=function(t){return delete Ue[t]},r.clear=function(){return Ue={},Ue},r})(),Tt=(function(){function r(){try{this.storageWindow=window.localStorage,this.storageWindow.setItem("aws.cognito.test-ls",1),this.storageWindow.removeItem("aws.cognito.test-ls");}catch{this.storageWindow=Ja;}}var e=r.prototype;return e.getStorage=function(){return this.storageWindow},r})();var Ga=typeof navigator<"u",Un=Ga?fr.isReactNative?"react-native":navigator.userAgent:"nodejs",me=(function(){function r(t){if(t==null||t.Username==null||t.Pool==null)throw new Error("Username and Pool information are required.");this.username=t.Username||"",this.pool=t.Pool,this.Session=null,this.client=t.Pool.client,this.signInUserSession=null,this.authenticationFlowType="USER_SRP_AUTH",this.storage=t.Storage||new Tt().getStorage(),this.keyPrefix="CognitoIdentityServiceProvider."+this.pool.getClientId(),this.userDataKey=this.keyPrefix+"."+this.username+".userData";}var e=r.prototype;return e.setSignInUserSession=function(n){this.clearCachedUserData(),this.signInUserSession=n,this.cacheTokens();},e.getSignInUserSession=function(){return this.signInUserSession},e.getUsername=function(){return this.username},e.getAuthenticationFlowType=function(){return this.authenticationFlowType},e.setAuthenticationFlowType=function(n){this.authenticationFlowType=n;},e.initiateAuth=function(n,i){var s=this,o=n.getAuthParameters();o.USERNAME=this.username;var a=Object.keys(n.getValidationData()).length!==0?n.getValidationData():n.getClientMetadata(),u={AuthFlow:"CUSTOM_AUTH",ClientId:this.pool.getClientId(),AuthParameters:o,ClientMetadata:a};this.getUserContextData()&&(u.UserContextData=this.getUserContextData()),this.client.request("InitiateAuth",u,function(c,d){if(c)return i.onFailure(c);var l=d.ChallengeName,g=d.ChallengeParameters;return l==="CUSTOM_CHALLENGE"?(s.Session=d.Session,i.customChallenge(g)):(s.signInUserSession=s.getCognitoUserSession(d.AuthenticationResult),s.cacheTokens(),i.onSuccess(s.signInUserSession))});},e.authenticateUser=function(n,i){return this.authenticationFlowType==="USER_PASSWORD_AUTH"?this.authenticateUserPlainUsernamePassword(n,i):this.authenticationFlowType==="USER_SRP_AUTH"||this.authenticationFlowType==="CUSTOM_AUTH"?this.authenticateUserDefaultAuth(n,i):i.onFailure(new Error("Authentication flow type is invalid."))},e.authenticateUserDefaultAuth=function(n,i){var s=this,o=new we(this.pool.getUserPoolName()),a=new vt,u,c,d={};this.deviceKey!=null&&(d.DEVICE_KEY=this.deviceKey),d.USERNAME=this.username,o.getLargeAValue(function(l,g){l&&i.onFailure(l),d.SRP_A=g.toString(16),s.authenticationFlowType==="CUSTOM_AUTH"&&(d.CHALLENGE_NAME="SRP_A");var p=Object.keys(n.getValidationData()).length!==0?n.getValidationData():n.getClientMetadata(),h={AuthFlow:s.authenticationFlowType,ClientId:s.pool.getClientId(),AuthParameters:d,ClientMetadata:p};s.getUserContextData(s.username)&&(h.UserContextData=s.getUserContextData(s.username)),s.client.request("InitiateAuth",h,function(b,w){if(b)return i.onFailure(b);var _=w.ChallengeParameters;s.username=_.USER_ID_FOR_SRP,s.userDataKey=s.keyPrefix+"."+s.username+".userData",u=new M(_.SRP_B,16),c=new M(_.SALT,16),s.getCachedDeviceKeyAndPassword(),o.getPasswordAuthenticationKey(s.username,n.getPassword(),u,c,function(R,C){R&&i.onFailure(R);var I=a.getNowString(),k=B.Buffer.concat([B.Buffer.from(s.pool.getUserPoolName(),"utf8"),B.Buffer.from(s.username,"utf8"),B.Buffer.from(_.SECRET_BLOCK,"base64"),B.Buffer.from(I,"utf8")]),K=new hr.Sha256(C);K.update(k);var ve=K.digestSync(),V=B.Buffer.from(ve).toString("base64"),P={};P.USERNAME=s.username,P.PASSWORD_CLAIM_SECRET_BLOCK=_.SECRET_BLOCK,P.TIMESTAMP=I,P.PASSWORD_CLAIM_SIGNATURE=V,s.deviceKey!=null&&(P.DEVICE_KEY=s.deviceKey);var D=function(Ce,Lr){return s.client.request("RespondToAuthChallenge",Ce,function(it,Cs){return it&&it.code==="ResourceNotFoundException"&&it.message.toLowerCase().indexOf("device")!==-1?(P.DEVICE_KEY=null,s.deviceKey=null,s.randomPassword=null,s.deviceGroupKey=null,s.clearCachedDeviceKeyAndPassword(),D(Ce,Lr)):Lr(it,Cs)})},N={ChallengeName:"PASSWORD_VERIFIER",ClientId:s.pool.getClientId(),ChallengeResponses:P,Session:w.Session,ClientMetadata:p};s.getUserContextData()&&(N.UserContextData=s.getUserContextData()),D(N,function(F,Ce){return F?i.onFailure(F):s.authenticateUserInternal(Ce,o,i)});});});});},e.authenticateUserPlainUsernamePassword=function(n,i){var s=this,o={};if(o.USERNAME=this.username,o.PASSWORD=n.getPassword(),!o.PASSWORD){i.onFailure(new Error("PASSWORD parameter is required"));return}var a=new we(this.pool.getUserPoolName());this.getCachedDeviceKeyAndPassword(),this.deviceKey!=null&&(o.DEVICE_KEY=this.deviceKey);var u=Object.keys(n.getValidationData()).length!==0?n.getValidationData():n.getClientMetadata(),c={AuthFlow:"USER_PASSWORD_AUTH",ClientId:this.pool.getClientId(),AuthParameters:o,ClientMetadata:u};this.getUserContextData(this.username)&&(c.UserContextData=this.getUserContextData(this.username)),this.client.request("InitiateAuth",c,function(d,l){return d?i.onFailure(d):s.authenticateUserInternal(l,a,i)});},e.authenticateUserInternal=function(n,i,s){var o=this,a=n.ChallengeName,u=n.ChallengeParameters;if(a==="SMS_MFA")return this.Session=n.Session,s.mfaRequired(a,u);if(a==="SELECT_MFA_TYPE")return this.Session=n.Session,s.selectMFAType(a,u);if(a==="MFA_SETUP")return this.Session=n.Session,s.mfaSetup(a,u);if(a==="SOFTWARE_TOKEN_MFA")return this.Session=n.Session,s.totpRequired(a,u);if(a==="CUSTOM_CHALLENGE")return this.Session=n.Session,s.customChallenge(u);if(a==="NEW_PASSWORD_REQUIRED"){this.Session=n.Session;var c=null,d=null,l=[],g=i.getNewPasswordRequiredChallengeUserAttributePrefix();if(u&&(c=JSON.parse(n.ChallengeParameters.userAttributes),d=JSON.parse(n.ChallengeParameters.requiredAttributes)),d)for(var p=0;p<d.length;p++)l[p]=d[p].substr(g.length);return s.newPasswordRequired(c,l)}if(a==="DEVICE_SRP_AUTH"){this.Session=n.Session,this.getDeviceResponse(s);return}this.signInUserSession=this.getCognitoUserSession(n.AuthenticationResult),this.challengeName=a,this.cacheTokens();var h=n.AuthenticationResult.NewDeviceMetadata;if(h==null)return s.onSuccess(this.signInUserSession);i.generateHashDevice(n.AuthenticationResult.NewDeviceMetadata.DeviceGroupKey,n.AuthenticationResult.NewDeviceMetadata.DeviceKey,function(b){if(b)return s.onFailure(b);var w={Salt:B.Buffer.from(i.getSaltDevices(),"hex").toString("base64"),PasswordVerifier:B.Buffer.from(i.getVerifierDevices(),"hex").toString("base64")};o.verifierDevices=w.PasswordVerifier,o.deviceGroupKey=h.DeviceGroupKey,o.randomPassword=i.getRandomPassword(),o.client.request("ConfirmDevice",{DeviceKey:h.DeviceKey,AccessToken:o.signInUserSession.getAccessToken().getJwtToken(),DeviceSecretVerifierConfig:w,DeviceName:Un},function(_,R){return _?s.onFailure(_):(o.deviceKey=n.AuthenticationResult.NewDeviceMetadata.DeviceKey,o.cacheDeviceKeyAndPassword(),R.UserConfirmationNecessary===true?s.onSuccess(o.signInUserSession,R.UserConfirmationNecessary):s.onSuccess(o.signInUserSession))});});},e.completeNewPasswordChallenge=function(n,i,s,o){var a=this;if(!n)return s.onFailure(new Error("New password is required."));var u=new we(this.pool.getUserPoolName()),c=u.getNewPasswordRequiredChallengeUserAttributePrefix(),d={};i&&Object.keys(i).forEach(function(g){d[c+g]=i[g];}),d.NEW_PASSWORD=n,d.USERNAME=this.username;var l={ChallengeName:"NEW_PASSWORD_REQUIRED",ClientId:this.pool.getClientId(),ChallengeResponses:d,Session:this.Session,ClientMetadata:o};this.getUserContextData()&&(l.UserContextData=this.getUserContextData()),this.client.request("RespondToAuthChallenge",l,function(g,p){return g?s.onFailure(g):a.authenticateUserInternal(p,u,s)});},e.getDeviceResponse=function(n,i){var s=this,o=new we(this.deviceGroupKey),a=new vt,u={};u.USERNAME=this.username,u.DEVICE_KEY=this.deviceKey,o.getLargeAValue(function(c,d){c&&n.onFailure(c),u.SRP_A=d.toString(16);var l={ChallengeName:"DEVICE_SRP_AUTH",ClientId:s.pool.getClientId(),ChallengeResponses:u,ClientMetadata:i,Session:s.Session};s.getUserContextData()&&(l.UserContextData=s.getUserContextData()),s.client.request("RespondToAuthChallenge",l,function(g,p){if(g)return n.onFailure(g);var h=p.ChallengeParameters,b=new M(h.SRP_B,16),w=new M(h.SALT,16);o.getPasswordAuthenticationKey(s.deviceKey,s.randomPassword,b,w,function(_,R){if(_)return n.onFailure(_);var C=a.getNowString(),I=B.Buffer.concat([B.Buffer.from(s.deviceGroupKey,"utf8"),B.Buffer.from(s.deviceKey,"utf8"),B.Buffer.from(h.SECRET_BLOCK,"base64"),B.Buffer.from(C,"utf8")]),k=new hr.Sha256(R);k.update(I);var K=k.digestSync(),ve=B.Buffer.from(K).toString("base64"),V={};V.USERNAME=s.username,V.PASSWORD_CLAIM_SECRET_BLOCK=h.SECRET_BLOCK,V.TIMESTAMP=C,V.PASSWORD_CLAIM_SIGNATURE=ve,V.DEVICE_KEY=s.deviceKey;var P={ChallengeName:"DEVICE_PASSWORD_VERIFIER",ClientId:s.pool.getClientId(),ChallengeResponses:V,Session:p.Session};s.getUserContextData()&&(P.UserContextData=s.getUserContextData()),s.client.request("RespondToAuthChallenge",P,function(D,N){return D?n.onFailure(D):(s.signInUserSession=s.getCognitoUserSession(N.AuthenticationResult),s.cacheTokens(),n.onSuccess(s.signInUserSession))});});});});},e.confirmRegistration=function(n,i,s,o){var a={ClientId:this.pool.getClientId(),ConfirmationCode:n,Username:this.username,ForceAliasCreation:i,ClientMetadata:o};this.getUserContextData()&&(a.UserContextData=this.getUserContextData()),this.client.request("ConfirmSignUp",a,function(u){return u?s(u,null):s(null,"SUCCESS")});},e.sendCustomChallengeAnswer=function(n,i,s){var o=this,a={};a.USERNAME=this.username,a.ANSWER=n;var u=new we(this.pool.getUserPoolName());this.getCachedDeviceKeyAndPassword(),this.deviceKey!=null&&(a.DEVICE_KEY=this.deviceKey);var c={ChallengeName:"CUSTOM_CHALLENGE",ChallengeResponses:a,ClientId:this.pool.getClientId(),Session:this.Session,ClientMetadata:s};this.getUserContextData()&&(c.UserContextData=this.getUserContextData()),this.client.request("RespondToAuthChallenge",c,function(d,l){return d?i.onFailure(d):o.authenticateUserInternal(l,u,i)});},e.sendMFACode=function(n,i,s,o){var a=this,u={};u.USERNAME=this.username,u.SMS_MFA_CODE=n;var c=s||"SMS_MFA";c==="SOFTWARE_TOKEN_MFA"&&(u.SOFTWARE_TOKEN_MFA_CODE=n),this.deviceKey!=null&&(u.DEVICE_KEY=this.deviceKey);var d={ChallengeName:c,ChallengeResponses:u,ClientId:this.pool.getClientId(),Session:this.Session,ClientMetadata:o};this.getUserContextData()&&(d.UserContextData=this.getUserContextData()),this.client.request("RespondToAuthChallenge",d,function(l,g){if(l)return i.onFailure(l);var p=g.ChallengeName;if(p==="DEVICE_SRP_AUTH"){a.getDeviceResponse(i);return}if(a.signInUserSession=a.getCognitoUserSession(g.AuthenticationResult),a.cacheTokens(),g.AuthenticationResult.NewDeviceMetadata==null)return i.onSuccess(a.signInUserSession);var h=new we(a.pool.getUserPoolName());h.generateHashDevice(g.AuthenticationResult.NewDeviceMetadata.DeviceGroupKey,g.AuthenticationResult.NewDeviceMetadata.DeviceKey,function(b){if(b)return i.onFailure(b);var w={Salt:B.Buffer.from(h.getSaltDevices(),"hex").toString("base64"),PasswordVerifier:B.Buffer.from(h.getVerifierDevices(),"hex").toString("base64")};a.verifierDevices=w.PasswordVerifier,a.deviceGroupKey=g.AuthenticationResult.NewDeviceMetadata.DeviceGroupKey,a.randomPassword=h.getRandomPassword(),a.client.request("ConfirmDevice",{DeviceKey:g.AuthenticationResult.NewDeviceMetadata.DeviceKey,AccessToken:a.signInUserSession.getAccessToken().getJwtToken(),DeviceSecretVerifierConfig:w,DeviceName:Un},function(_,R){return _?i.onFailure(_):(a.deviceKey=g.AuthenticationResult.NewDeviceMetadata.DeviceKey,a.cacheDeviceKeyAndPassword(),R.UserConfirmationNecessary===true?i.onSuccess(a.signInUserSession,R.UserConfirmationNecessary):i.onSuccess(a.signInUserSession))});});});},e.changePassword=function(n,i,s,o){if(!(this.signInUserSession!=null&&this.signInUserSession.isValid()))return s(new Error("User is not authenticated"),null);this.client.request("ChangePassword",{PreviousPassword:n,ProposedPassword:i,AccessToken:this.signInUserSession.getAccessToken().getJwtToken(),ClientMetadata:o},function(a){return a?s(a,null):s(null,"SUCCESS")});},e.enableMFA=function(n){if(this.signInUserSession==null||!this.signInUserSession.isValid())return n(new Error("User is not authenticated"),null);var i=[],s={DeliveryMedium:"SMS",AttributeName:"phone_number"};i.push(s),this.client.request("SetUserSettings",{MFAOptions:i,AccessToken:this.signInUserSession.getAccessToken().getJwtToken()},function(o){return o?n(o,null):n(null,"SUCCESS")});},e.setUserMfaPreference=function(n,i,s){if(this.signInUserSession==null||!this.signInUserSession.isValid())return s(new Error("User is not authenticated"),null);this.client.request("SetUserMFAPreference",{SMSMfaSettings:n,SoftwareTokenMfaSettings:i,AccessToken:this.signInUserSession.getAccessToken().getJwtToken()},function(o){return o?s(o,null):s(null,"SUCCESS")});},e.disableMFA=function(n){if(this.signInUserSession==null||!this.signInUserSession.isValid())return n(new Error("User is not authenticated"),null);var i=[];this.client.request("SetUserSettings",{MFAOptions:i,AccessToken:this.signInUserSession.getAccessToken().getJwtToken()},function(s){return s?n(s,null):n(null,"SUCCESS")});},e.deleteUser=function(n,i){var s=this;if(this.signInUserSession==null||!this.signInUserSession.isValid())return n(new Error("User is not authenticated"),null);this.client.request("DeleteUser",{AccessToken:this.signInUserSession.getAccessToken().getJwtToken(),ClientMetadata:i},function(o){return o?n(o,null):(s.clearCachedUser(),n(null,"SUCCESS"))});},e.updateAttributes=function(n,i,s){var o=this;if(this.signInUserSession==null||!this.signInUserSession.isValid())return i(new Error("User is not authenticated"),null);this.client.request("UpdateUserAttributes",{AccessToken:this.signInUserSession.getAccessToken().getJwtToken(),UserAttributes:n,ClientMetadata:s},function(a,u){return a?i(a,null):o.getUserData(function(){return i(null,"SUCCESS",u)},{bypassCache:true})});},e.getUserAttributes=function(n){if(!(this.signInUserSession!=null&&this.signInUserSession.isValid()))return n(new Error("User is not authenticated"),null);this.client.request("GetUser",{AccessToken:this.signInUserSession.getAccessToken().getJwtToken()},function(i,s){if(i)return n(i,null);for(var o=[],a=0;a<s.UserAttributes.length;a++){var u={Name:s.UserAttributes[a].Name,Value:s.UserAttributes[a].Value},c=new ce(u);o.push(c);}return n(null,o)});},e.getMFAOptions=function(n){if(!(this.signInUserSession!=null&&this.signInUserSession.isValid()))return n(new Error("User is not authenticated"),null);this.client.request("GetUser",{AccessToken:this.signInUserSession.getAccessToken().getJwtToken()},function(i,s){return i?n(i,null):n(null,s.MFAOptions)});},e.createGetUserRequest=function(){return this.client.promisifyRequest("GetUser",{AccessToken:this.signInUserSession.getAccessToken().getJwtToken()})},e.refreshSessionIfPossible=function(n){var i=this;return n===void 0&&(n={}),new Promise(function(s){var o=i.signInUserSession.getRefreshToken();o&&o.getToken()?i.refreshSession(o,s,n.clientMetadata):s();})},e.getUserData=function(n,i){var s=this;if(!(this.signInUserSession!=null&&this.signInUserSession.isValid()))return this.clearCachedUserData(),n(new Error("User is not authenticated"),null);var o=this.getUserDataFromCache();if(!o){this.fetchUserData().then(function(a){n(null,a);}).catch(n);return}if(this.isFetchUserDataAndTokenRequired(i)){this.fetchUserData().then(function(a){return s.refreshSessionIfPossible(i).then(function(){return a})}).then(function(a){return n(null,a)}).catch(n);return}try{n(null,JSON.parse(o));return}catch(a){this.clearCachedUserData(),n(a,null);return}},e.getUserDataFromCache=function(){var n=this.storage.getItem(this.userDataKey);return n},e.isFetchUserDataAndTokenRequired=function(n){var i=n||{},s=i.bypassCache,o=s===void 0?false:s;return o},e.fetchUserData=function(){var n=this;return this.createGetUserRequest().then(function(i){return n.cacheUserData(i),i})},e.deleteAttributes=function(n,i){var s=this;if(!(this.signInUserSession!=null&&this.signInUserSession.isValid()))return i(new Error("User is not authenticated"),null);this.client.request("DeleteUserAttributes",{UserAttributeNames:n,AccessToken:this.signInUserSession.getAccessToken().getJwtToken()},function(o){return o?i(o,null):s.getUserData(function(){return i(null,"SUCCESS")},{bypassCache:true})});},e.resendConfirmationCode=function(n,i){var s={ClientId:this.pool.getClientId(),Username:this.username,ClientMetadata:i};this.client.request("ResendConfirmationCode",s,function(o,a){return o?n(o,null):n(null,a)});},e.getSession=function(n,i){if(i===void 0&&(i={}),this.username==null)return n(new Error("Username is null. Cannot retrieve a new session"),null);if(this.signInUserSession!=null&&this.signInUserSession.isValid())return n(null,this.signInUserSession);var s="CognitoIdentityServiceProvider."+this.pool.getClientId()+"."+this.username,o=s+".idToken",a=s+".accessToken",u=s+".refreshToken",c=s+".clockDrift";if(this.storage.getItem(o)){var d=new Ve({IdToken:this.storage.getItem(o)}),l=new Me({AccessToken:this.storage.getItem(a)}),g=new qe({RefreshToken:this.storage.getItem(u)}),p=parseInt(this.storage.getItem(c),0)||0,h={IdToken:d,AccessToken:l,RefreshToken:g,ClockDrift:p},b=new Be(h);if(b.isValid())return this.signInUserSession=b,n(null,this.signInUserSession);if(!g.getToken())return n(new Error("Cannot retrieve a new session. Please authenticate."),null);this.refreshSession(g,n,i.clientMetadata);}else n(new Error("Local storage is missing an ID Token, Please authenticate"),null);},e.refreshSession=function(n,i,s){var o=this,a=this.pool.wrapRefreshSessionCallback?this.pool.wrapRefreshSessionCallback(i):i,u={};u.REFRESH_TOKEN=n.getToken();var c="CognitoIdentityServiceProvider."+this.pool.getClientId(),d=c+".LastAuthUser";if(this.storage.getItem(d)){this.username=this.storage.getItem(d);var l=c+"."+this.username+".deviceKey";this.deviceKey=this.storage.getItem(l),u.DEVICE_KEY=this.deviceKey;}var g={ClientId:this.pool.getClientId(),AuthFlow:"REFRESH_TOKEN_AUTH",AuthParameters:u,ClientMetadata:s};this.getUserContextData()&&(g.UserContextData=this.getUserContextData()),this.client.requestWithRetry("InitiateAuth",g,function(p,h){if(p)return p.code==="NotAuthorizedException"&&o.clearCachedUser(),a(p,null);if(h){var b=h.AuthenticationResult;return Object.prototype.hasOwnProperty.call(b,"RefreshToken")||(b.RefreshToken=n.getToken()),o.signInUserSession=o.getCognitoUserSession(b),o.cacheTokens(),a(null,o.signInUserSession)}});},e.cacheTokens=function(){var n="CognitoIdentityServiceProvider."+this.pool.getClientId(),i=n+"."+this.username+".idToken",s=n+"."+this.username+".accessToken",o=n+"."+this.username+".refreshToken",a=n+"."+this.username+".clockDrift",u=n+".LastAuthUser";this.storage.setItem(i,this.signInUserSession.getIdToken().getJwtToken()),this.storage.setItem(s,this.signInUserSession.getAccessToken().getJwtToken()),this.storage.setItem(o,this.signInUserSession.getRefreshToken().getToken()),this.storage.setItem(a,""+this.signInUserSession.getClockDrift()),this.storage.setItem(u,this.username);},e.cacheUserData=function(n){this.storage.setItem(this.userDataKey,JSON.stringify(n));},e.clearCachedUserData=function(){this.storage.removeItem(this.userDataKey);},e.clearCachedUser=function(){this.clearCachedTokens(),this.clearCachedUserData();},e.cacheDeviceKeyAndPassword=function(){var n="CognitoIdentityServiceProvider."+this.pool.getClientId()+"."+this.username,i=n+".deviceKey",s=n+".randomPasswordKey",o=n+".deviceGroupKey";this.storage.setItem(i,this.deviceKey),this.storage.setItem(s,this.randomPassword),this.storage.setItem(o,this.deviceGroupKey);},e.getCachedDeviceKeyAndPassword=function(){var n="CognitoIdentityServiceProvider."+this.pool.getClientId()+"."+this.username,i=n+".deviceKey",s=n+".randomPasswordKey",o=n+".deviceGroupKey";this.storage.getItem(i)&&(this.deviceKey=this.storage.getItem(i),this.randomPassword=this.storage.getItem(s),this.deviceGroupKey=this.storage.getItem(o));},e.clearCachedDeviceKeyAndPassword=function(){var n="CognitoIdentityServiceProvider."+this.pool.getClientId()+"."+this.username,i=n+".deviceKey",s=n+".randomPasswordKey",o=n+".deviceGroupKey";this.storage.removeItem(i),this.storage.removeItem(s),this.storage.removeItem(o);},e.clearCachedTokens=function(){var n="CognitoIdentityServiceProvider."+this.pool.getClientId(),i=n+"."+this.username+".idToken",s=n+"."+this.username+".accessToken",o=n+"."+this.username+".refreshToken",a=n+".LastAuthUser",u=n+"."+this.username+".clockDrift";this.storage.removeItem(i),this.storage.removeItem(s),this.storage.removeItem(o),this.storage.removeItem(a),this.storage.removeItem(u);},e.getCognitoUserSession=function(n){var i=new Ve(n),s=new Me(n),o=new qe(n),a={IdToken:i,AccessToken:s,RefreshToken:o};return new Be(a)},e.forgotPassword=function(n,i){var s={ClientId:this.pool.getClientId(),Username:this.username,ClientMetadata:i};this.getUserContextData()&&(s.UserContextData=this.getUserContextData()),this.client.request("ForgotPassword",s,function(o,a){return o?n.onFailure(o):typeof n.inputVerificationCode=="function"?n.inputVerificationCode(a):n.onSuccess(a)});},e.confirmPassword=function(n,i,s,o){var a={ClientId:this.pool.getClientId(),Username:this.username,ConfirmationCode:n,Password:i,ClientMetadata:o};this.getUserContextData()&&(a.UserContextData=this.getUserContextData()),this.client.request("ConfirmForgotPassword",a,function(u){return u?s.onFailure(u):s.onSuccess("SUCCESS")});},e.getAttributeVerificationCode=function(n,i,s){if(this.signInUserSession==null||!this.signInUserSession.isValid())return i.onFailure(new Error("User is not authenticated"));this.client.request("GetUserAttributeVerificationCode",{AttributeName:n,AccessToken:this.signInUserSession.getAccessToken().getJwtToken(),ClientMetadata:s},function(o,a){return o?i.onFailure(o):typeof i.inputVerificationCode=="function"?i.inputVerificationCode(a):i.onSuccess("SUCCESS")});},e.verifyAttribute=function(n,i,s){if(this.signInUserSession==null||!this.signInUserSession.isValid())return s.onFailure(new Error("User is not authenticated"));this.client.request("VerifyUserAttribute",{AttributeName:n,Code:i,AccessToken:this.signInUserSession.getAccessToken().getJwtToken()},function(o){return o?s.onFailure(o):s.onSuccess("SUCCESS")});},e.getDevice=function(n){if(this.signInUserSession==null||!this.signInUserSession.isValid())return n.onFailure(new Error("User is not authenticated"));this.client.request("GetDevice",{AccessToken:this.signInUserSession.getAccessToken().getJwtToken(),DeviceKey:this.deviceKey},function(i,s){return i?n.onFailure(i):n.onSuccess(s)});},e.forgetSpecificDevice=function(n,i){if(this.signInUserSession==null||!this.signInUserSession.isValid())return i.onFailure(new Error("User is not authenticated"));this.client.request("ForgetDevice",{AccessToken:this.signInUserSession.getAccessToken().getJwtToken(),DeviceKey:n},function(s){return s?i.onFailure(s):i.onSuccess("SUCCESS")});},e.forgetDevice=function(n){var i=this;this.forgetSpecificDevice(this.deviceKey,{onFailure:n.onFailure,onSuccess:function(o){return i.deviceKey=null,i.deviceGroupKey=null,i.randomPassword=null,i.clearCachedDeviceKeyAndPassword(),n.onSuccess(o)}});},e.setDeviceStatusRemembered=function(n){if(this.signInUserSession==null||!this.signInUserSession.isValid())return n.onFailure(new Error("User is not authenticated"));this.client.request("UpdateDeviceStatus",{AccessToken:this.signInUserSession.getAccessToken().getJwtToken(),DeviceKey:this.deviceKey,DeviceRememberedStatus:"remembered"},function(i){return i?n.onFailure(i):n.onSuccess("SUCCESS")});},e.setDeviceStatusNotRemembered=function(n){if(this.signInUserSession==null||!this.signInUserSession.isValid())return n.onFailure(new Error("User is not authenticated"));this.client.request("UpdateDeviceStatus",{AccessToken:this.signInUserSession.getAccessToken().getJwtToken(),DeviceKey:this.deviceKey,DeviceRememberedStatus:"not_remembered"},function(i){return i?n.onFailure(i):n.onSuccess("SUCCESS")});},e.listDevices=function(n,i,s){if(this.signInUserSession==null||!this.signInUserSession.isValid())return s.onFailure(new Error("User is not authenticated"));var o={AccessToken:this.signInUserSession.getAccessToken().getJwtToken(),Limit:n};i&&(o.PaginationToken=i),this.client.request("ListDevices",o,function(a,u){return a?s.onFailure(a):s.onSuccess(u)});},e.globalSignOut=function(n){var i=this;if(this.signInUserSession==null||!this.signInUserSession.isValid())return n.onFailure(new Error("User is not authenticated"));this.client.request("GlobalSignOut",{AccessToken:this.signInUserSession.getAccessToken().getJwtToken()},function(s){return s?n.onFailure(s):(i.clearCachedUser(),n.onSuccess("SUCCESS"))});},e.signOut=function(n){var i=this;if(!n||typeof n!="function"){this.cleanClientData();return}this.getSession(function(s,o){if(s)return n(s);i.revokeTokens(function(a){i.cleanClientData(),n(a);});});},e.revokeTokens=function(n){if(n===void 0&&(n=function(){}),typeof n!="function")throw new Error("Invalid revokeTokenCallback. It should be a function.");if(!this.signInUserSession){var s=new Error("User is not authenticated");return n(s)}if(!this.signInUserSession.getAccessToken()){var o=new Error("No Access token available");return n(o)}var a=this.signInUserSession.getRefreshToken().getToken(),u=this.signInUserSession.getAccessToken();if(this.isSessionRevocable(u)&&a)return this.revokeToken({token:a,callback:n});n();},e.isSessionRevocable=function(n){if(n&&typeof n.decodePayload=="function")try{var i=n.decodePayload(),s=i.origin_jti;return !!s}catch{}return false},e.cleanClientData=function(){this.signInUserSession=null,this.clearCachedUser();},e.revokeToken=function(n){var i=n.token,s=n.callback;this.client.requestWithRetry("RevokeToken",{Token:i,ClientId:this.pool.getClientId()},function(o){if(o)return s(o);s();});},e.sendMFASelectionAnswer=function(n,i){var s=this,o={};o.USERNAME=this.username,o.ANSWER=n;var a={ChallengeName:"SELECT_MFA_TYPE",ChallengeResponses:o,ClientId:this.pool.getClientId(),Session:this.Session};this.getUserContextData()&&(a.UserContextData=this.getUserContextData()),this.client.request("RespondToAuthChallenge",a,function(u,c){if(u)return i.onFailure(u);if(s.Session=c.Session,n==="SMS_MFA")return i.mfaRequired(c.ChallengeName,c.ChallengeParameters);if(n==="SOFTWARE_TOKEN_MFA")return i.totpRequired(c.ChallengeName,c.ChallengeParameters)});},e.getUserContextData=function(){var n=this.pool;return n.getUserContextData(this.username)},e.associateSoftwareToken=function(n){var i=this;this.signInUserSession!=null&&this.signInUserSession.isValid()?this.client.request("AssociateSoftwareToken",{AccessToken:this.signInUserSession.getAccessToken().getJwtToken()},function(s,o){return s?n.onFailure(s):n.associateSecretCode(o.SecretCode)}):this.client.request("AssociateSoftwareToken",{Session:this.Session},function(s,o){return s?n.onFailure(s):(i.Session=o.Session,n.associateSecretCode(o.SecretCode))});},e.verifySoftwareToken=function(n,i,s){var o=this;this.signInUserSession!=null&&this.signInUserSession.isValid()?this.client.request("VerifySoftwareToken",{AccessToken:this.signInUserSession.getAccessToken().getJwtToken(),UserCode:n,FriendlyDeviceName:i},function(a,u){return a?s.onFailure(a):s.onSuccess(u)}):this.client.request("VerifySoftwareToken",{Session:this.Session,UserCode:n,FriendlyDeviceName:i},function(a,u){if(a)return s.onFailure(a);o.Session=u.Session;var c={};c.USERNAME=o.username;var d={ChallengeName:"MFA_SETUP",ClientId:o.pool.getClientId(),ChallengeResponses:c,Session:o.Session};o.getUserContextData()&&(d.UserContextData=o.getUserContextData()),o.client.request("RespondToAuthChallenge",d,function(l,g){return l?s.onFailure(l):(o.signInUserSession=o.getCognitoUserSession(g.AuthenticationResult),o.cacheTokens(),s.onSuccess(o.signInUserSession))});});},r})();Te(Dn());function $e(){}$e.prototype.userAgent=xn();var kn=function(e){var t=$e.category?" "+$e.category:"",n=$e.framework?" framework/"+$e.framework:"",i=""+$e.prototype.userAgent+t+n;return i};function za(r,e){r.prototype=Object.create(e.prototype),r.prototype.constructor=r,Ge(r,e);}function mr(r){var e=typeof Map=="function"?new Map:void 0;return mr=function(n){if(n===null||!Xa(n))return n;if(typeof n!="function")throw new TypeError("Super expression must either be null or a function");if(e!==void 0){if(e.has(n))return e.get(n);e.set(n,i);}function i(){return Ya(n,arguments,_r(this).constructor)}return i.prototype=Object.create(n.prototype,{constructor:{value:i,enumerable:false,writable:true,configurable:true}}),Ge(i,n)},mr(r)}function Ya(r,e,t){if(Nn())return Reflect.construct.apply(null,arguments);var n=[null];n.push.apply(n,e);var i=new(r.bind.apply(r,n));return t&&Ge(i,t.prototype),i}function Nn(){try{var r=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}));}catch{}return (Nn=function(){return !!r})()}function Xa(r){try{return Function.toString.call(r).indexOf("[native code]")!==-1}catch{return typeof r=="function"}}function Ge(r,e){return Ge=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,n){return t.__proto__=n,t},Ge(r,e)}function _r(r){return _r=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},_r(r)}var Za=(function(r){function e(t,n,i,s){var o;return o=r.call(this,t)||this,o.code=n,o.name=i,o.statusCode=s,o}return za(e,r),e})(mr(Error)),Fn=(function(){function r(t,n,i){this.endpoint=n||"https://cognito-idp."+t+".amazonaws.com/";var s=i||{},o=s.credentials;this.fetchOptions=o?{credentials:o}:{};}var e=r.prototype;return e.promisifyRequest=function(n,i){var s=this;return new Promise(function(o,a){s.request(n,i,function(u,c){u?a(new Za(u.message,u.code,u.name,u.statusCode)):o(c);});})},e.requestWithRetry=function(n,i,s){var o=this,a=5*1e3;nu(function(u){return new Promise(function(c,d){o.request(n,u,function(l,g){l?d(l):c(g);});})},[i],a).then(function(u){return s(null,u)}).catch(function(u){return s(u)});},e.request=function(n,i,s){var o={"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":"AWSCognitoIdentityProviderService."+n,"X-Amz-User-Agent":kn(),"Cache-Control":"no-store"},a=Object.assign({},this.fetchOptions,{headers:o,method:"POST",mode:"cors",body:JSON.stringify(i)}),u;fetch(this.endpoint,a).then(function(d){return u=d,d},function(d){throw d instanceof TypeError?new Error("Network error"):d}).then(function(d){return d.json().catch(function(){return {}})}).then(function(d){if(u.ok)return s(null,d);var l=(d.__type||d.code).split("#").pop(),g=new Error(d.message||d.Message||null);return g.name=l,g.code=l,s(g)}).catch(function(d){if(u&&u.headers&&u.headers.get("x-amzn-errortype"))try{var l=u.headers.get("x-amzn-errortype").split(":")[0],g=new Error(u.status?u.status.toString():null);return g.code=l,g.name=l,g.statusCode=u.status,s(g)}catch{return s(d)}else d instanceof Error&&d.message==="Network error"&&(d.code="NetworkError");return s(d)});},r})();var Rt={debug:function(){}};var eu=function(e){var t="nonRetryable";return e&&e[t]};function Ln(r,e,t,n){if(n===void 0&&(n=1),typeof r!="function")throw Error("functionToRetry must be a function");return Rt.debug(r.name+" attempt #"+n+" with args: "+JSON.stringify(e)),r.apply(void 0,e).catch(function(i){if(Rt.debug("error on "+r.name,i),eu(i))throw Rt.debug(r.name+" non retryable error",i),i;var s=t(n,e,i);if(Rt.debug(r.name+" retrying in "+s+" ms"),s!==false)return new Promise(function(o){return setTimeout(o,s)}).then(function(){return Ln(r,e,t,n+1)});throw i})}function tu(r){var e=100,t=100;return function(n){var i=Math.pow(2,n)*e+t*Math.random();return i>r?false:i}}function nu(r,e,t){return Ln(r,e,tu(t))}var iu=55,br=(function(){function r(t,n){var i=t||{},s=i.UserPoolId,o=i.ClientId,a=i.endpoint,u=i.fetchOptions,c=i.AdvancedSecurityDataCollectionFlag;if(!s||!o)throw new Error("Both UserPoolId and ClientId are required.");if(s.length>iu||!/^[\w-]+_[0-9a-zA-Z]+$/.test(s))throw new Error("Invalid UserPoolId format.");var d=s.split("_")[0];this.userPoolId=s,this.clientId=o,this.client=new Fn(d,a,u),this.advancedSecurityDataCollectionFlag=c!==false,this.storage=t.Storage||new Tt().getStorage(),n&&(this.wrapRefreshSessionCallback=n);}var e=r.prototype;return e.getUserPoolId=function(){return this.userPoolId},e.getUserPoolName=function(){return this.getUserPoolId().split("_")[1]},e.getClientId=function(){return this.clientId},e.signUp=function(n,i,s,o,a,u){var c=this,d={ClientId:this.clientId,Username:n,Password:i,UserAttributes:s,ValidationData:o,ClientMetadata:u};this.getUserContextData(n)&&(d.UserContextData=this.getUserContextData(n)),this.client.request("SignUp",d,function(l,g){if(l)return a(l,null);var p={Username:n,Pool:c,Storage:c.storage},h={user:new me(p),userConfirmed:g.UserConfirmed,userSub:g.UserSub,codeDeliveryDetails:g.CodeDeliveryDetails};return a(null,h)});},e.getCurrentUser=function(){var n="CognitoIdentityServiceProvider."+this.clientId+".LastAuthUser",i=this.storage.getItem(n);if(i){var s={Username:i,Pool:this,Storage:this.storage};return new me(s)}return null},e.getUserContextData=function(n){if(!(typeof AmazonCognitoAdvancedSecurityData>"u")){var i=AmazonCognitoAdvancedSecurityData;if(this.advancedSecurityDataCollectionFlag){var s=i.getData(n,this.userPoolId,this.clientId);if(s){var o={EncodedData:s};return o}}return {}}},r})();Te(Vn());var f=class extends Error{constructor(e,t){if(Array.isArray(e)&&e.length<=2){let n=e[1];if(e.length>2)for(let i=2;i<e.length&&typeof e[i]=="string";i++)n+=e[i];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||(typeof e=="string"?e:"Something went wrong.")).trim()),typeof e=="string"?(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)):typeof e=="object"&&e?.code&&e?.message&&(this.name=t?.name||"SKAPI",this.code=t?.code||"ERROR",this.cause=e?.cause);}};var _e="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",wr=BigInt(_e.length),su=2*1024*1024,ou=["aud","cognito:username","event_id","exp","iat","iss","jti","origin_jti","secret_key","token_use"],qn={auth_time:"log",sub:"user_id"},au=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f","g","h","i","j","k","l"],Hn=["us31","us72","ap51","ap22","ap41","eu71","ap21","us32","us71","af51","ap31","ap43","ap23","ap42","ca01","eu01","eu72","eu51","eu73","eu11","me51","sa31"],Bn=typeof TextEncoder<"u"?new TextEncoder:null;function uu(){if(typeof globalThis<"u")return globalThis.Buffer}function cu(r){if(Bn)return Bn.encode(r);let e=unescape(encodeURIComponent(r)),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}function lu(r){if(r instanceof Uint8Array)return r;if(typeof r=="string")return cu(r);if(typeof ArrayBuffer<"u"&&r instanceof ArrayBuffer)return new Uint8Array(r);if(typeof ArrayBuffer<"u"&&ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);if(Array.isArray(r))return Uint8Array.from(r);let e=uu();if(e)return new Uint8Array(e.from(r));throw new Error("No byte conversion available in this environment.")}var A=class A{static hash(e){typeof e!="string"&&(console.warn("coercing non-string value to empty string"),e="");let t=A.sb(e),n=1732584193,i=-271733879,s=-1732584194,o=271733878,a,u,c,d;for(let l=0;l<t.length;l+=16)a=n,u=i,c=s,d=o,n=A.ff(n,i,s,o,t[l],7,-680876936),o=A.ff(o,n,i,s,t[l+1],12,-389564586),s=A.ff(s,o,n,i,t[l+2],17,606105819),i=A.ff(i,s,o,n,t[l+3],22,-1044525330),n=A.ff(n,i,s,o,t[l+4],7,-176418897),o=A.ff(o,n,i,s,t[l+5],12,1200080426),s=A.ff(s,o,n,i,t[l+6],17,-1473231341),i=A.ff(i,s,o,n,t[l+7],22,-45705983),n=A.ff(n,i,s,o,t[l+8],7,1770035416),o=A.ff(o,n,i,s,t[l+9],12,-1958414417),s=A.ff(s,o,n,i,t[l+10],17,-42063),i=A.ff(i,s,o,n,t[l+11],22,-1990404162),n=A.ff(n,i,s,o,t[l+12],7,1804603682),o=A.ff(o,n,i,s,t[l+13],12,-40341101),s=A.ff(s,o,n,i,t[l+14],17,-1502002290),i=A.ff(i,s,o,n,t[l+15],22,1236535329),n=A.gg(n,i,s,o,t[l+1],5,-165796510),o=A.gg(o,n,i,s,t[l+6],9,-1069501632),s=A.gg(s,o,n,i,t[l+11],14,643717713),i=A.gg(i,s,o,n,t[l],20,-373897302),n=A.gg(n,i,s,o,t[l+5],5,-701558691),o=A.gg(o,n,i,s,t[l+10],9,38016083),s=A.gg(s,o,n,i,t[l+15],14,-660478335),i=A.gg(i,s,o,n,t[l+4],20,-405537848),n=A.gg(n,i,s,o,t[l+9],5,568446438),o=A.gg(o,n,i,s,t[l+14],9,-1019803690),s=A.gg(s,o,n,i,t[l+3],14,-187363961),i=A.gg(i,s,o,n,t[l+8],20,1163531501),n=A.gg(n,i,s,o,t[l+13],5,-1444681467),o=A.gg(o,n,i,s,t[l+2],9,-51403784),s=A.gg(s,o,n,i,t[l+7],14,1735328473),i=A.gg(i,s,o,n,t[l+12],20,-1926607734),n=A.hh(n,i,s,o,t[l+5],4,-378558),o=A.hh(o,n,i,s,t[l+8],11,-2022574463),s=A.hh(s,o,n,i,t[l+11],16,1839030562),i=A.hh(i,s,o,n,t[l+14],23,-35309556),n=A.hh(n,i,s,o,t[l+1],4,-1530992060),o=A.hh(o,n,i,s,t[l+4],11,1272893353),s=A.hh(s,o,n,i,t[l+7],16,-155497632),i=A.hh(i,s,o,n,t[l+10],23,-1094730640),n=A.hh(n,i,s,o,t[l+13],4,681279174),o=A.hh(o,n,i,s,t[l],11,-358537222),s=A.hh(s,o,n,i,t[l+3],16,-722521979),i=A.hh(i,s,o,n,t[l+6],23,76029189),n=A.hh(n,i,s,o,t[l+9],4,-640364487),o=A.hh(o,n,i,s,t[l+12],11,-421815835),s=A.hh(s,o,n,i,t[l+15],16,530742520),i=A.hh(i,s,o,n,t[l+2],23,-995338651),n=A.ii(n,i,s,o,t[l],6,-198630844),o=A.ii(o,n,i,s,t[l+7],10,1126891415),s=A.ii(s,o,n,i,t[l+14],15,-1416354905),i=A.ii(i,s,o,n,t[l+5],21,-57434055),n=A.ii(n,i,s,o,t[l+12],6,1700485571),o=A.ii(o,n,i,s,t[l+3],10,-1894986606),s=A.ii(s,o,n,i,t[l+10],15,-1051523),i=A.ii(i,s,o,n,t[l+1],21,-2054922799),n=A.ii(n,i,s,o,t[l+8],6,1873313359),o=A.ii(o,n,i,s,t[l+15],10,-30611744),s=A.ii(s,o,n,i,t[l+6],15,-1560198380),i=A.ii(i,s,o,n,t[l+13],21,1309151649),n=A.ii(n,i,s,o,t[l+4],6,-145523070),o=A.ii(o,n,i,s,t[l+11],10,-1120210379),s=A.ii(s,o,n,i,t[l+2],15,718787259),i=A.ii(i,s,o,n,t[l+9],21,-343485551),n=A.ad(n,a),i=A.ad(i,u),s=A.ad(s,c),o=A.ad(o,d);return A.rh(n)+A.rh(i)+A.rh(s)+A.rh(o)}static rh(e){let t="";for(let n=0;n<=3;n++)t+=A.alphabet.charAt(e>>n*8+4&15)+A.alphabet.charAt(e>>n*8&15);return t}static ad(e,t){let n=(e&65535)+(t&65535);return (e>>16)+(t>>16)+(n>>16)<<16|n&65535}static rl(e,t){return e<<t|e>>>32-t}static cm(e,t,n,i,s,o){return A.ad(A.rl(A.ad(A.ad(t,e),A.ad(i,o)),s),n)}static ff(e,t,n,i,s,o,a){return A.cm(t&n|~t&i,e,t,s,o,a)}static gg(e,t,n,i,s,o,a){return A.cm(t&i|n&~i,e,t,s,o,a)}static hh(e,t,n,i,s,o,a){return A.cm(t^n^i,e,t,s,o,a)}static ii(e,t,n,i,s,o,a){return A.cm(n^(t|~i),e,t,s,o,a)}static sb(e){let t,n=(e.length+8>>6)+1,i=new Array(n*16);for(t=0;t<n*16;t++)i[t]=0;for(t=0;t<e.length;t++)i[t>>2]|=e.charCodeAt(t)<<t%4*8;return i[t>>2]|=128<<t%4*8,i[n*16-2]=e.length*8,i}};A.alphabet="0123456789abcdef";var Q=A;function Wn(r){if(r===0)return _e[0];let e="";for(;r>0;)e=_e[r%62]+e,r=Math.floor(r/62);return e}function ne(r){return r.split("").reverse().reduce((e,t,n)=>e+_e.indexOf(t)*62**n,0)}function Qe(r=6){let e="",t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n=t.length,i=0;for(;i<r;)e+=t.charAt(Math.floor(Math.random()*n)),i+=1;return e}function Ar(){return typeof window>"u"||!!window?._runningInNodeJS}function z(){return !Ar()&&typeof document<"u"&&typeof document.createElement=="function"}function It(r){let e;try{e=JSON.stringify(r);}catch{throw new f("Invalid data type.",{code:"INVALID_REQUEST"})}if(new Blob([e]).size>su)throw new f("Data should not exceed 2MB",{code:"INVALID_REQUEST"})}function $n(r){return r===""||r==="on"||r==="true"}function jn(r){return r==="false"}function Kn(r,e,t){e.name&&t(r,e.name,e.value);}var Pt=z(),du=typeof SubmitEvent<"u",fu=typeof HTMLFormElement<"u";function L(r,e,t){let n={},i=[];function s(u,c,d){if(e?.ignoreEmpty&&d==="")return;if(e?.nullIfEmpty&&d===""&&(d=null),typeof t=="function"){let p=t(c,d);p!==void 0&&(d=p);}let l=c.split("[").map(p=>{let h=p.replace("]",""),b=Number(h);return !isNaN(b)&&!h.includes(".")?h=b:(h[0]==='"'&&h[h.length-1]==='"'||h[0]==="'"&&h[h.length-1]==="'")&&(h=h.replace(/"/g,"").replace(/'/g,"")),h}),g=u;if(typeof l[0]=="number")throw new f("Form key cannot start with an array index.",{code:"INVALID_REQUEST"});for(let p=0;p<l.length;p++){let h=l[p];p<l.length-1?(g[h]===void 0&&(typeof l[p+1]=="number"?g[h]=[]:g[h]={}),g=g[h]):g[h]===void 0?g[h]=d:Array.isArray(g[h])?g[h].push(d):g[h]=[g[h],d];}}function o(u,c,d){if(d instanceof File)u.push({name:c,file:d});else if(d instanceof FileList&&d&&d.length>0)for(let l=0;l<=d.length-1;l++){let g=d.item(l);g&&u.push({name:c,file:g});}}let a=u=>{u.name&&(u.type==="number"?u.value&&s(n,u.name,Number(u.value)):u.type==="checkbox"||u.type==="radio"?u.checked?u.type==="checkbox"&&u.value===""||$n(u.value)?s(n,u.name,true):jn(u.value)?s(n,u.name,false):u.value&&s(n,u.name,u.value):u.type==="checkbox"&&($n(u.value)?s(n,u.name,false):jn(u.value)&&s(n,u.name,true)):u.type==="file"?u.files&&u.files.length>0&&o(i,u.name,u.files):s(n,u.name,u.value));};if(Pt&&(r instanceof HTMLInputElement||r instanceof HTMLSelectElement||r instanceof HTMLTextAreaElement))return a(r),It(n),{data:n,files:i};if(Pt&&r instanceof FormData){for(let u of r.entries()){let c=u[0],d=u[1];if(d instanceof File||d instanceof FileList)o(i,c,d);else if(d instanceof Blob){let l=d;if(l.type==="application/json")try{let g=JSON.parse(l.text());s(n,c,g);}catch{s(n,c,l);}}else s(n,c,d);}return It(n),{data:n,files:i}}if(Pt&&du&&r instanceof SubmitEvent&&(r=r.target),Pt&&fu&&r instanceof HTMLFormElement){let u=r.querySelectorAll("input"),c=r.querySelectorAll("select"),d=r.querySelectorAll("textarea");for(let l=0;l<c.length;l++)Kn(n,c[l],s);for(let l=0;l<d.length;l++)Kn(n,d[l],s);for(let l=0;l<u.length;l++)a(u[l]);return It(n),{data:n,files:i}}return It(r),{data:r,files:i}}function ze(r){let e={};for(let t in r){let n=r[t];if(!ou.includes(t))if(qn[t])e[qn[t]]=n;else if(t.includes("custom:"))e[t.replace("custom:","")]=n;else if(t==="address"){let i=n;if(i&&typeof i=="object"&&Object.keys(i).length){if(i?.formatted)try{e[t]=JSON.parse(i.formatted);}catch{e[t]=i.formatted;}}else e[t]=i;}else e[t]=n;}for(let t of ["address_public","birthdate_public","email_public","gender_public","phone_number_public","access_group"])t.includes("_public")?e.hasOwnProperty(t.split("_")[0])?e[t]=e.hasOwnProperty(t)?!!Number(e[t]):false:delete e[t]:e[t]=e.hasOwnProperty(t)?Number(e[t]):0;for(let t of ["email","phone_number"])e.hasOwnProperty(t)?e[t+"_verified"]=e[t+"_verified"]===true:delete e[t+"_verified"];return e}function Sr(r){if(r=wu(r),r.split("-").length===7){let e=r.split("-"),t,n;try{t=Hn[ne(e[1][0])],n=e.slice(2).join("-");}catch{throw new Error("INVALID_PARAMETER: Service ID is invalid.")}if(!t)throw new Error("INVALID_PARAMETER: Service ID is invalid.");return {service:t+e[0]+e[1].slice(1),owner:n}}return {service:r,owner:""}}function Jn(r,e){let t=Hn.indexOf(r.slice(0,4)),n=au[t],s=`${r.slice(4,-4)}-${n}${r.slice(-4)}-${e}`;return yu(s)}function hu(r){let e=0n;for(let t of r){let n=_e.indexOf(t);if(n<0)throw new Error(`INVALID_PARAMETER: Invalid base62 character: ${t}`);e=e*wr+BigInt(n);}return e}function gu(r,e=1){if(r<0n)throw new Error("INVALID_PARAMETER: Negative values are not supported.");if(r===0n)return "0".repeat(Math.max(1,e));let t="",n=r;for(;n>0n;){let i=Number(n%wr);t=_e[i]+t,n/=wr;}return t.length<e&&(t="0".repeat(e-t.length)+t),t}function pu(r){if(r===0n)return Uint8Array.from([0]);let e=[],t=r;for(;t>0n;)e.push(Number(t&0xffn)),t>>=8n;return e.reverse(),Uint8Array.from(e)}function mu(r){let e=0n;for(let t of r)e=(e<<8n)+BigInt(t);return e}function _u(r){let e=String(r).replace(/-/g,"");if(!/^[0-9a-fA-F]{32}$/.test(e))throw new Error("INVALID_PARAMETER: Invalid UUID format.");let t=new Uint8Array(16);for(let n=0;n<16;n++)t[n]=parseInt(e.slice(n*2,n*2+2),16);return t}function bu(r){let e=Array.from(lu(r),t=>t.toString(16).padStart(2,"0")).join("");return [e.slice(0,8),e.slice(8,12),e.slice(12,16),e.slice(16,20),e.slice(20)].join("-")}function yu(r){let e=String(r);if(e.split("-").length===2)return e;let t=e.match(/^([0-9A-Za-z]+)-([0-9A-Za-z]+)-([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/);if(!t)throw new Error("INVALID_PARAMETER: Input must match <base62>-<base62>-<uuid>.");let[,n,i,s]=t;if(n.length<2)throw new Error("INVALID_PARAMETER: The first part must contain at least 2 characters.");if(i.length>=_e.length)throw new Error("INVALID_PARAMETER: The middle section is too long to encode.");let o=n.slice(0,2),a=n.slice(2),u=i+o,c=_e[i.length]+a+u,d=_u(s),l=gu(mu(d));return `${c}-${l}`}function wu(r){let e=String(r);if(e.split("-").length!==2)return e;let t=e.split("-");if(t.length!==2||!t[0]||!t[1])throw new Error("INVALID_PARAMETER: Corrupt compressed token.");let[n,i]=t,s=_e.indexOf(n[0]);if(s<0)throw new Error("INVALID_PARAMETER: Corrupt compressed token.");let o=n.slice(1),a=s+2;if(o.length<a)throw new Error("INVALID_PARAMETER: Corrupt compressed token.");let u=o.slice(0,o.length-a),c=o.slice(o.length-a),d=c.slice(s),l=c.slice(0,s),g=d+u;if(!/^[0-9A-Za-z]+$/.test(g)||!/^[0-9A-Za-z]+$/.test(l))throw new Error("INVALID_PARAMETER: Corrupt compressed token.");let p=hu(i),h=pu(p);if(h.length>16)throw new Error("INVALID_PARAMETER: Corrupt compressed token.");let b=new Uint8Array(16);b.set(h,16-h.length);let w=bu(b);return `${g}-${l}-${w}`}function Ye(r,e,t=[],n=null){let i=["string","number","boolean","object","array","function","null","undefined"];function s(h){return h!==null&&typeof h=="object"&&!Array.isArray(h)}function o(h){return s(h)}function a(h){return Array.isArray(h)}function u(h){return typeof h=="string"&&i.indexOf(h)!==-1}function c(h){return Array.isArray(h)?"array":h===null?"null":typeof h}function d(h){try{return JSON.stringify(h)}catch{return String(h)}}function l(h){if(u(h))return `Type<${h}>`;if(typeof h=="function")return "custom validator";try{return JSON.stringify(h,(b,w)=>typeof w=="function"?"custom validator":w)}catch{return String(h)}}function g(h,b){return b==="array"?Array.isArray(h):b==="object"?s(h):b==="null"?h===null:b==="undefined"?typeof h>"u":typeof h===b}function p(h){return n===null?h:`${n}[${h}]`}if(typeof e>"u")throw new Error('Argument "struct" is required.');if(typeof e=="function")return e(r);if(o(e)){if(!s(r))throw new Error(`Data schema does not match:
207
- `+JSON.stringify(r,null,2));for(let h of Object.keys(e)){let b=p(h);if(Object.prototype.hasOwnProperty.call(r,h))r[h]=Ye(r[h],e[h],t,b);else {if(t.indexOf(b)!==-1)throw new Error(`Key "${b}" is required.`);let w=e[h];a(w)&&w.length>1&&typeof w[w.length-1]=="function"&&(r[h]=w[w.length-1]());}}return r}if(a(e)){let h=false;if(e.length===1&&!a(e[0])&&!o(e[0])){let b=e[0];if(!Array.isArray(r))throw new Error(`Type <${c(r)}> is invalid in "${n}". Expected a list.`);for(let w=0;w<r.length;w++){let _=r[w];if(u(b)){if(!g(_,b))throw new Error(`Type <${c(_)}> is invalid in "${n}". Expected a list of Type <${b}>.`)}else if(typeof b=="function")r[w]=b(_);else if(_!==b)throw new Error(`Value ${d(_)} is invalid in "${n}". Expected a list of ${d(b)}.`)}h=true;}else if(Array.isArray(r)&&e.every(w=>!a(w)&&w!=="array")){for(let w=0;w<r.length;w++){let _=false,R="";for(let C of e)try{r[w]=Ye(r[w],C,t,n),_=!0;break}catch(I){typeof C=="function"&&(R=I?.message||String(I));}if(!_&&R)throw new Error(R);if(!_){let C=e.map(l).join(", ");throw new Error(`${d(r[w])} is invalid in "${n}". allowed types or values are: ${C}.`)}}h=true;}else {let w="";for(let _ of e)try{r=Ye(r,_,t,n),h=!0;break}catch(R){typeof _=="function"&&(w=R?.message||String(R));}if(!h&&w)throw new Error(w)}if(!h){let b=e.map(l).join(", ");throw new Error(`${d(r)} is invalid in "${n}". allowed types or values are: ${b}.`)}return r}if(u(e)&&g(r,e)||r===e)return r;throw new Error(`${d(r)} is invalid in "${n}". allowed type or value is: ${l(e)}.`)}function Au(r,e="User ID"){let t=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;if(r){if(typeof r!="string")throw new f(`${e} should be type: string.`,{code:"INVALID_PARAMETER"});if(!r.match(t))throw new f(`${e} is invalid.`,{code:"INVALID_PARAMETER"})}else throw new f(`${e} is empty.`,{code:"INVALID_PARAMETER"});return r}function Su(r){if(r&&(typeof r!="string"||r.charAt(0)!=="+"||isNaN(Number(r.substring(1)))))throw new f('"phone_number" is invalid. The format should be "+00123456789". Type: string.',{code:"INVALID_PARAMETER"});return r||""}function Eu(r){if(r){if(typeof r!="string")throw new f('"birthdate" is invalid. The format should be "yyyy-mm-dd". Type: string.',{code:"INVALID_PARAMETER"});{let e=new RegExp(/([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))/);if(r.length!==10||r.split("-").length!==3||!e.test(r))throw new f('"birthdate" is invalid. The format should be "yyyy-mm-dd". Type: string.',{code:"INVALID_PARAMETER"})}}return r||""}function vu(r){if(r){if(typeof r!="string")throw new f('"password" should be type: string.',{code:"INVALID_PARAMETER"});if(r.length<6)throw new f('"password" should be at least 6 characters.',{code:"INVALID_PARAMETER"});if(r.length>60)throw new f('"password" can be up to 60 characters max.',{code:"INVALID_PARAMETER"})}else throw new f('"password" is required.',{code:"INVALID_PARAMETER"});return r}function Tu(r,e="email"){if(r){if(typeof r!="string")throw new f(`"${e}"should be type: string.`,{code:"INVALID_PARAMETER"});if(r.length<5)throw new f(`"${e}" should be at least 5 characters.`,{code:"INVALID_PARAMETER"});if(/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/.test(r)&&(r=r.trim(),r.split("@")[1].split(".").length>=2))return r.toLowerCase()}else throw new f(`"${e}" is required.`,{code:"INVALID_PARAMETER"});throw new f(`"${r}" is an invalid email.`,{code:"INVALID_PARAMETER"})}function Ru(r){let e=typeof window<"u",t=(()=>{let i=e&&window.location.origin||null;return i&&i.slice(-1)==="/"&&(i=i.slice(0,-1)),i})(),n=i=>{if(typeof i=="string"){if(i==="*")return "*";{let s=i.trim();if(s[0]==="/"&&t){if(t.slice(0,5)==="file:")throw new f(`"${i}" is an invalid url. Relative URL does not work on local file system. Use full URL string.`,{code:"INVALID_PARAMETER"});s=t+s;}else if(s[0]==="."&&t){if(t.slice(0,5)==="file:")throw new f(`"${i}" is an invalid url. Relative URL does not work on local file system. Use full URL string.`,{code:"INVALID_PARAMETER"});let a=e?window.location.href.split("?")[0]:"";a.slice(-1)!=="/"&&(a+="/"),s=a+s.slice(1);}let o;try{o=new URL(s);}catch{throw new f(`"${i}" is an invalid url.`,{code:"INVALID_PARAMETER"})}if(o.protocol)return o.href}}throw new f(`"${i}" is an invalid url.`,{code:"INVALID_PARAMETER"})};return Array.isArray(r)?r.map(i=>n(i)):n(r)}function Iu(r,e,t=[],n){let i=L(r,n),s=i.data;e.service="string",e.owner="string";let o={};for(let a in e)if(s&&typeof s=="object"&&!Array.isArray(s)&&s.hasOwnProperty(a))if(typeof s[a]=="function")o[a]=s[a];else try{o[a]=JSON.parse(JSON.stringify(s[a]));}catch{o[a]=s[a];}n?.precall&&n.precall({data:o,files:i?.files||[]});try{return Ye(o,e,t)}catch(a){throw new f(a.message,{code:"INVALID_PARAMETER"})}}var m={UserId:Au,PhoneNumber:Su,Birthdate:Eu,Password:vu,Email:Tu,Url:Ru,Params:Iu};var O=null;function Er(r){let e={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"},t={};for(let n in r)if(n==="tkid"){let i=r[n].split("#");if(i.length===1){t.ticket_id=i[0];continue}t.ticket_id=i[1],t.consume_id=i[2],t.user_id=i[3];let s=i[2].slice(-4);if(t.is_test=s===":CHK",!r.stmp){let o=i[2].slice(0,-4);/^[0-9]+$/.test(o)?t.timestamp=parseInt(o,10):t.timestamp=ne(i[2].slice(0,-4));}}else e[n]?t[e[n]]=r[n]:t[n]=r[n];return t}async function Qn(r){if(!r.ticket_id)throw new f("Ticket ID is required.",{code:"INVALID_PARAMETER"});if(!r.method)throw new f('Method is required. Should be either "GET" or "POST"',{code:"INVALID_PARAMETER"});let e=r.ticket_id;await this.__connection;let t=await v.bind(this)(`https://${this.service.slice(0,4)}.${this.customApiDomain}/auth/consume/${this.service}/${this.owner}/${e}`,r?.data||{},{method:r.method,auth:!!r?.auth});return Er(t)}async function zn(r,e){await this.__connection;let t=await v.bind(this)("ticket",Object.assign({exec:"list"},r||{}),{auth:true,fetchOptions:e});return t.list=t.list.map(Er),t}async function Yn(r,e){await this.__connection;let t=await v.bind(this)("ticket",Object.assign({exec:"consumed"},r||{}),{auth:true,fetchOptions:e});return t.list=t.list.map(Er),t}async function Xn(r){return v.bind(this)("register-ticket",Object.assign({exec:"reg"},r),{auth:true})}async function Zn(r){return v.bind(this)("register-ticket",Object.assign({exec:"unreg"},r),{auth:true})}async function je(){if(await this.__connection,this.session){let r=Math.floor(Date.now()/1e3),t=this.session.getIdToken().getExpiration();if(t<r){this.log("request:requesting new token",null);try{await W.bind(this)().getSession({refreshToken:!0}),this.log("request:received new tokens",{exp:this.session?.idToken?.payload?.exp,currentTime:r,expiresIn:t-r,token:this.session?.accessToken?.jwtToken,refreshToken:this.session?.refreshToken?.token});}catch(n){throw this.log("request:new token error",n),new f("User login is required.",{code:"INVALID_REQUEST"})}}else this.log("request:tokens",{exp:this.session.idToken.payload.exp,currentTime:r,expiresIn:t-r,token:this.session.accessToken.jwtToken,refreshToken:this.session.refreshToken.token});return this.session?.idToken?.jwtToken}else throw this.log("request:no session",null),be.bind(this)(),new f("User login is required.",{code:"INVALID_REQUEST"})}function Gn(r,e){return new Promise((t,n)=>{e.refreshSession(r.getRefreshToken(),(i,s)=>{this.log("getSession:refreshSessionCallback",{refreshErr:i,refreshedSession:s}),i?(be.bind(this)(),n(i)):s.isValid()?t(s):(be.bind(this)(),n(new f("Invalid session.",{code:"INVALID_REQUEST"})));});})}function W(){if(!this.userPool)throw new f("User pool is missing",{code:"INVALID_REQUEST"});let r=()=>{let s=O.getSignInUserSession().getIdToken().payload||null,o=ze(s);return this.log("normalized user attribute",o),this.__user=o,o},e=async s=>new Promise((o,a)=>{this.log("getSession:option",s);let{refreshToken:u=false,skipUserUpdateEventTrigger:c=false}=s||{};if(u&&c&&(c=false),O=this.userPool.getCurrentUser(),!O){this.log("getSession:cognitoUser",O),be.bind(this)(),a(null);return}let d=l=>{let g=l.getIdToken().payload;if(this.log("getSession:respond:sessionAttribute",g),g["custom:service"]!==this.service)throw this.log("getSession:respond","invalid service, signing out"),be.bind(this)(),new f("Invalid session.",{code:"INVALID_REQUEST"});return this.session=l,r(),c||this._runOnUserUpdateListeners(this.user),this.session};O.getSession((l,g)=>{if(this.log("getSession:getSessionCallback",{err:l,session:g}),!g){be.bind(this)(),a(new f("Current session does not exist.",{code:"INVALID_REQUEST"}));return}if(l){Gn.bind(this)(g,O).then(_=>o(d(_))).catch(a);return}let p=Math.floor(Date.now()/1e3),h=g.getIdToken(),b=h.getExpiration(),w=b<p;if(this.log("getSession:currentTime",p),this.log("getSession:idTokenExp",b),this.log("getSession:isExpired",w),this.log("getSession:existingBearerToken",this.bearerToken),this.bearerToken=h.getJwtToken(),w||u||!g.isValid())Gn.bind(this)(g,O).then(_=>o(d(_))).catch(a);else try{o(d(g));}catch(_){a(_);}});}),t=(s,o)=>{let a=o||s.includes(this.service+"-")?s:this.service+"-"+Q.hash(s);return {cognitoUser:new me({Username:a,Pool:this.userPool}),cognitoUsername:a}};return {getSession:e,authenticateUser:(s,o,a=false,u=false)=>new Promise((c,d)=>{this.__request_signup_confirmation=null,this.__disabledAccount=null;let l=t(s,a),g=l.cognitoUsername,p=new Bt({Username:g,Password:o});l.cognitoUser.authenticateUser(p,{newPasswordRequired:(h,b)=>{this.__disabledAccount=null,this.__request_signup_confirmation=g,h["custom:signup_ticket"]==="PASS"||h["custom:signup_ticket"]==="MEMBER"||h["custom:signup_ticket"]==="OIDPASS"?l.cognitoUser.completeNewPasswordChallenge(o,{},{onSuccess:w=>{O=l.cognitoUser,e().then(_=>c(this.user));},onFailure:w=>{d(new f(w.message||"Failed to authenticate user.",{code:w.code}));}}):d(new f("User's signup confirmation is required.",{code:"SIGNUP_CONFIRMATION_NEEDED"}));},onSuccess:h=>e({skipUserUpdateEventTrigger:true}).then(b=>{this.__disabledAccount=null,this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user),c(this.user);}),onFailure:h=>{let b=[],{parsed:w,code:_}=xt(h),R=typeof h?.message=="string"?h.message:"";if(_==="NotAuthorizedException"?R.includes("User is disabled.")?(this.__disabledAccount=g,b=["This account is disabled.","USER_IS_DISABLED"]):u?b=["The account already exists.","ACCOUNT_EXISTS"]:b=["Incorrect username or password.","INCORRECT_USERNAME_OR_PASSWORD"]:_==="UserNotFoundException"?b=["Incorrect username or password.","INCORRECT_USERNAME_OR_PASSWORD"]:_==="UserNotConfirmedException"?(this.__request_signup_confirmation=g,b=["User's signup confirmation is required.","SIGNUP_CONFIRMATION_NEEDED"]):(_==="TooManyRequestsException"||_==="LimitExceededException")&&(b=["Too many attempts. Please try again later.","REQUEST_EXCEED"]),w.code==="SIGNUP_CONFIRMATION_NEEDED"&&(this.__request_signup_confirmation=g),b.length){let C=b[1],I=b[0];d(new f(I,{code:C,cause:h}));}else d(w);}});}),createCognitoUser:t,signup:(s,o,a)=>new Promise((u,c)=>{this.userPool.signUp(s,o,a,null,(d,l)=>{if(d){let{parsed:g,code:p}=xt(d),h=[];p==="UsernameExistsException"?h=["The account already exists.","EXISTS"]:p==="InvalidPasswordException"?h=["Invalid password. Password must be at least 6 characters.","INVALID_PARAMETER"]:p==="InvalidParameterException"?h=[g.message||"Invalid parameter.","INVALID_PARAMETER"]:p==="TooManyRequestsException"||p==="LimitExceededException"?h=["Too many attempts. Please try again later.","REQUEST_EXCEED"]:p==="CodeDeliveryFailureException"?h=["Failed to deliver verification code.","CODE_DELIVERY_FAILURE"]:p==="UserLambdaValidationException"&&(h=[g.message||"Signup validation failed.","INVALID_REQUEST"]),h.length?c(new f(h[0],{code:h[1],cause:d})):c(g);return}u(l);});})}}function xt(r){let e=typeof r?.code=="string"&&r.code.trim()?r.code.trim():"ERROR",n=((typeof r?.message=="string"?r.message:typeof r=="string"?r:"An error occurred.")||"An error occurred.").trim();n||(n="An error occurred.");let i=n.match(/#([A-Za-z0-9_]+)\s*:\s*([\s\S]+)/),s=i?.[1]?.trim()||e,o=i?.[2]?.trim()||n;return {parsed:new f(o,{code:s,cause:r}),code:e}}async function ei(r){await this.__authConnection;let e=r?.refreshToken||false;if(!e)return this.user;try{return await W.bind(this)().getSession(Object.assign({skipUserUpdateEventTrigger:!e,refreshToken:e},r)),this.user}catch{return null}}async function ti(r){await this.__connection,r=m.Params(r,{token:"string",id:"string",merge:s=>{if(s===void 0)return false;if(typeof s=="string")return [s];if(Array.isArray(s)){for(let o of s)if(typeof o!="string")throw new f('"merge" array items should be type: <string>.',{code:"INVALID_PARAMETER"})}if(typeof s!="boolean"&&!Array.isArray(s))throw new f('"merge" should be type: <boolean | string[]>.',{code:"INVALID_PARAMETER"});return s}});let e=await v.bind(this)("openid-logger",r),t=e.logger.split("#"),n=this.service+"-"+t[0],i=t[1];return {userProfile:await W.bind(this)().authenticateUser(n,i,true,true),openid:e.openid}}function Pu(r){let e=typeof globalThis<"u"?globalThis:void 0;if(e?.Buffer)return e.Buffer.from(r,"base64").toString("utf8");if(typeof atob=="function"){let t=atob(r),n=new Uint8Array(t.length);for(let i=0;i<t.length;i++)n[i]=t.charCodeAt(i);return typeof TextDecoder<"u"?new TextDecoder().decode(n):t}throw new Error("No base64 decoder available in this environment")}function xu(r){let e=r.split(".");if(e.length!==3)throw new Error("Invalid JWT format");let n=e[1].replace(/-/g,"+").replace(/_/g,"/"),i=Pu(n);return JSON.parse(i)}async function ri(r){await this.__authConnection,this.log("loginWithToken:params",r),r=m.Params(r,{idToken:"string",accessToken:"string",refreshToken:"string"},["idToken"]);let e=xu(r.idToken);if(this.log("loginWithToken:idTokenPayload",e),e["custom:service"]!==this.service)throw new f("Token does not belong to this service.",{code:"INVALID_REQUEST"});let t=Math.floor(Date.now()/1e3);if(e.exp&&e.exp<t)throw new f("Token has expired.",{code:"INVALID_REQUEST"});if(this.__user=ze(e),this.session=null,r.accessToken&&r.refreshToken)try{if(this.session=new Be({IdToken:new Ve({IdToken:r.idToken}),AccessToken:new Me({AccessToken:r.accessToken}),RefreshToken:new qe({RefreshToken:r.refreshToken})}),this.log("loginWithToken:session",this.session),this.log("loginWithToken:CognitoUser",me),this.log("loginWithToken:userPool",this.userPool),me&&this.userPool){this.log("loginWithToken:cognito:username",e["cognito:username"]);let n={Username:e["cognito:username"],Pool:this.userPool};this.log("loginWithToken:cognitoUserParams",n),O=new me(n),O.setSignInUserSession(this.session),this.log("loginWithToken:cognitoUserRestored",{cognitoUserType:typeof O,cognitoUserKeys:Object.keys(O||{}),cognitoUser:O});}}catch(n){this.log("loginWithToken:err",n);try{this.log("loginWithToken:err:stringified",JSON.stringify(n));}catch{this.log("loginWithToken:err:stringifyFail",String(n));}try{let i=Object.keys(n||{}),s=Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(n||{}):[],o=Object.getOwnPropertyDescriptors?Object.getOwnPropertyDescriptors(n||{}):{};this.log("loginWithToken:createSessionError:allKeys",{keys:i,symbols:s,descriptors:o});}catch(i){this.log("loginWithToken:createSessionError:allKeysFail",String(i));}}return this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user),this.user}async function J(){return await this.__connection,this.__user?.service===this.service?this.__user?.owner===this.host:(await Xe.bind(this)(),false)}async function be(r=false){let e=null;O&&(r?e=new Promise((n,i)=>{O.globalSignOut({onSuccess:s=>{this.log("globalSignOut:success",s),n(s);},onFailure:s=>{this.log("globalSignOut:error",s),i(s);}});}):O.signOut());let t={session:null,__startKeyHistory:{},__cached_requests:{},__user:null};e&&(e=await e);for(let n in t)this[n]=t[n];return this._runOnUserUpdateListeners(null),this._runOnLoginListeners(null),e}async function Xe(r){await this.__connection;let{data:e}=L(r);return await be.bind(this)(e?.global),"SUCCESS: The user has been logged out."}async function ni(){if(!this.__request_signup_confirmation)throw new f("Least one login attempt is required.",{code:"INVALID_REQUEST"});return await v.bind(this)("confirm-signup",{username:this.__request_signup_confirmation})}async function ii(r=false){if(typeof r=="string")r=m.Url(r);else if(typeof r!="boolean")throw new f("Argument should be type: <boolean | string>.",{code:"INVALID_REQUEST"});if(!this.__disabledAccount)throw new f("Least one signin attempt of disabled account is required.",{code:"INVALID_REQUEST"});return await v.bind(this)("recover-account",{username:this.__disabledAccount,redirect:r}),"SUCCESS: Recovery e-mail has been sent."}async function vr(r){let e=m.Params(r,{username:"string",email:"string",password:"string"},["password"]);if(await this.__authConnection,e.email)try{m.Email(e.email);}catch{e.username=e.email,delete e.email;}if(!e.username&&!e.email)throw new f('Least one of "username" or "email" is required.',{code:"INVALID_PARAMETER"});return await W.bind(this)().authenticateUser(e.username||e.email,e.password)}async function si(r,e){await this.__authConnection;let t={username:"string",password:c=>m.Password(c),email:c=>m.Email(c),name:"string",address:c=>{if(!c)return "";if(typeof c=="string")return c;if(typeof c=="object")return JSON.stringify(c)},gender:"string",birthdate:c=>c?m.Birthdate(c):"",phone_number:c=>c?m.PhoneNumber(c):"",email_public:["boolean",()=>false],address_public:["boolean",()=>false],gender_public:["boolean",()=>false],birthdate_public:["boolean",()=>false],phone_number_public:["boolean",()=>false],access_group:"number",misc:"string",picture:c=>c?m.Url(c):"",profile:c=>c?m.Url(c):"",family_name:"string",given_name:"string",middle_name:"string",nickname:"string",website:c=>c?m.Url(c):""},n=m.Params(r||{},t,["email","password"]);await Xe.bind(this)(),e=m.Params(e||{},{email_subscription:c=>{if(typeof c!="boolean")throw new f('"option.email_subscription" should be type: <boolean>.',{code:"INVALID_PARAMETER"});if(!e?.signup_confirmation)throw new f('"option.signup_confirmation" is required for email subscription.',{code:"INVALID_PARAMETER"});return c},signup_confirmation:c=>{let d=c;if(typeof c=="string")d=m.Url(c);else if(typeof c=="boolean")d=c;else throw new f('"option.signup_confirmation" should be type: <string | boolean>.',{code:"INVALID_PARAMETER"});if(d&&!n.email)throw new f('"email" is required for signup confirmation.',{code:"INVALID_PARAMETER"});return d},login:c=>{if(typeof c=="boolean"){if(e.signup_confirmation&&c)throw new f('"login" is not allowed when "option.signup_confirmation" is true.',{code:"INVALID_PARAMETER"});return c}throw new f('"option.login" should be type: boolean.',{code:"INVALID_PARAMETER"})}});let i=e?.login||false;if(n.signup_confirmation=e?.signup_confirmation||false,n.email_subscription=e?.email_subscription||false,n.email_public&&!n.signup_confirmation)throw new f('"option.signup_confirmation" should be true if "email_public" is set to true.',{code:"INVALID_PARAMETER"});n.service=this.service,n.owner=this.owner;let s=W.bind(this)().createCognitoUser(n.username||n.email);for(let c of ["email_public","address_public","gender_public","birthdate_public","phone_number_public"])n[c]=n[c]?"1":"0";n.access_group&&(n.access_group=n.access_group.toString());let o=(await v.bind(this)("signupkey",{username:s.cognitoUsername,signup_confirmation:typeof n.signup_confirmation=="boolean"?JSON.stringify(n.signup_confirmation):n.signup_confirmation,email_subscription:n.email_subscription})).split(":"),a=o.slice(1).join(":"),u=[new ce({Name:"custom:signup",Value:o[0]}),new ce({Name:"locale",Value:a.split("#")[1]}),new ce({Name:"custom:signup_ticket",Value:a})];for(let c in t){let d=["email_public","address_public","gender_public","birthdate_public","phone_number_public","misc","service","owner"];n[c]!==""&&(c==="username"||c==="password"||c==="access_group"||(d.includes(c)?u.push(new ce({Name:"custom:"+c,Value:n[c]})):u.push(new ce({Name:c,Value:n[c]}))));}return await W.bind(this)().signup(s.cognitoUsername,n.password,u),n.signup_confirmation?(O=s.cognitoUser,this.__request_signup_confirmation=s.cognitoUsername,"SUCCESS: The account has been created. User's signup confirmation is required."):i?vr.bind(this)({email:n.username||n.email,password:n.password}):"SUCCESS: The account has been created."}async function oi(){await this.__connection;let r=await v.bind(this)("remove-account",{disable:this.__user.user_id},{auth:true});return await Xe.bind(this)(),r}async function ai(r){await this.__connection;let e=m.Params(r,{email:i=>m.Email(i),code:["number","string"],new_password:i=>m.Password(i)},["email","code","new_password"]),t=e.code,n=e.new_password;return typeof t=="number"&&(t=t.toString()),new Promise(async(i,s)=>{W.bind(this)().createCognitoUser(e.email).cognitoUser.confirmPassword(t,n,{onSuccess:a=>{i("SUCCESS: New password has been set.");},onFailure:a=>{s(new f(a?.message||"Failed to reset password.",{code:a?.code||"ERROR",cause:a}));}});})}async function ui(r,e){await this.__connection;let t;if(!O)throw new f("The user has to be logged in.",{code:"INVALID_REQUEST"});if(r==="email"||r==="phone_number"){if(!this.__user.hasOwnProperty(r))throw new f(`No ${r==="email"?"e-mail":"phone number"} to verify`,{code:"INVALID_REQUEST"});if(this.__user?.[`${r}_verified`])return `SUCCESS: "${r}" is verified.`;t=(e?m.Params(e,{code:"string"}):{}).code||"";}else return;return new Promise((n,i)=>{let s={onSuccess:o=>{t?W.bind(this)().getSession({refreshToken:true}).then(()=>{this.__user&&(this.__user[r+"_verified"]=true),n(`SUCCESS: "${r}" is verified.`);}).catch(a=>{i(a);}):n("SUCCESS: Verification code has been sent.");},onFailure:o=>{i(new f(o.message||"Failed to request verification code.",{code:o?.code}));}};t?O?.verifyAttribute(r,t,s):(s.inputVerificationCode=null,O?.getAttributeVerificationCode(r,s));})}function ci(r){return ui.bind(this)("phone_number",r)}function li(r){return ui.bind(this)("email",r)}async function di(r){await this.__connection;let e=m.Params(r,{email:t=>m.Email(t)},["email"]);return new Promise(async(t,n)=>{W.bind(this)().createCognitoUser(e.email).cognitoUser.forgotPassword({onSuccess:s=>{t("SUCCESS: Verification code has been sent.");},onFailure:s=>{let{parsed:o,code:a}=xt(s),u={UserNotFoundException:"NOT_EXISTS",InvalidParameterException:"INVALID_PARAMETER",NotAuthorizedException:"INVALID_REQUEST",LimitExceededException:"REQUEST_EXCEED",TooManyRequestsException:"REQUEST_EXCEED",CodeDeliveryFailureException:"CODE_DELIVERY_FAILURE"}[a]||o.code||a||"ERROR";n(new f(o.message,{code:u,cause:s}));}});})}async function fi(r){if(await this.__connection,!this.session)throw new f("User login is required.",{code:"INVALID_REQUEST"});let e=m.Params(r,{current_password:"string",new_password:"string"});if(!e?.current_password)throw new f('"current_password" is required to change password.',{code:"INVALID_PARAMETER"});if(!e?.new_password)throw new f('"new_password" is required to change password.',{code:"INVALID_PARAMETER"});return m.Password(e.current_password),m.Password(e.new_password),new Promise((t,n)=>{O.changePassword(e.current_password,e.new_password,(i,s)=>{if(i){if(i?.code==="InvalidParameterException")n(new f("Invalid password parameter.",{code:"INVALID_PARAMETER"}));else if(i?.code==="NotAuthorizedException")n(new f("Incorrect password.",{code:"INVALID_REQUEST"}));else if(i?.code==="TooManyRequestsException"||i?.code==="LimitExceededException")n(new f("Too many attempts. Please try again later.",{code:"REQUEST_EXCEED"}));else {let{parsed:o}=xt(i);n(o);}return}t("SUCCESS: Password has been changed.");});})}async function hi(r){if(await this.__connection,!this.session)throw new f("User login is required.",{code:"INVALID_REQUEST"});let e=m.Params(r||{},{user_id:i=>m.UserId(i),email:i=>m.Email(i),address:i=>{if(!i)return "";if(typeof i=="string")return i;if(typeof i=="object")return JSON.stringify(i)},name:"string",gender:"string",birthdate:i=>i?m.Birthdate(i):"",phone_number:i=>i?m.PhoneNumber(i):"",email_public:"boolean",phone_number_public:"boolean",address_public:"boolean",gender_public:"boolean",birthdate_public:"boolean",misc:"string",picture:i=>i?m.Url(i):"",profile:i=>i?m.Url(i):"",family_name:"string",given_name:"string",middle_name:"string",nickname:"string",website:i=>i?m.Url(i):""});if(e&&typeof e=="object"&&!Object.keys(e).length)return this.user;e.email&&(e.preferred_username=this.service+"-"+Q.hash(e.email));let t=[["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 i of t)if(e[i[0]]&&!this.__user[i[1]])throw new f(`${i[2]} "${i[0]}" to true.`,{code:"INVALID_REQUEST"})}let n=[];for(let i in e){if(e[i]===this.user[i]){n.push(i);continue}if(["email_public","phone_number_public","address_public","gender_public","birthdate_public","misc"].includes(i)){let o=e[i];typeof o=="boolean"&&(o=o?"1":"0"),e["custom:"+i]=o,n.push(i);}}for(let i of n)delete e[i];if(e.user_id)if(e.user_id===this.user.user_id)delete e.user_id;else return v.bind(this)("admin-edit-profile",{attributes:e},{auth:true});if(e&&typeof e=="object"&&Object.keys(e).length){let i=[];for(let s in e)i.push(new ce({Name:s,Value:e[s]}));return await new Promise((s,o)=>{O?.updateAttributes(i,(a,u)=>{a&&o([a?.code||a?.name,a?.message||"Failed to update user settings."]),s(u);});}),await W.bind(this)().getSession({refreshToken:true}),this.user}return this.user}async function gi(r,e){r=L(r).data,r||(r={searchFor:"timestamp",condition:">",value:0},e||(e={}),e.ascending=false),await this.__connection;let t={user_id:i=>Array.isArray(i)?i.map(s=>m.UserId(s)):m.UserId(i),email:"string",phone_number:"string",locale:i=>{if(typeof i!="string"||typeof i=="string"&&i.length>5)throw new f('Value of "locale" should be a country code.',{code:"INVALID_PARAMETER"});return i},name:"string",address:"string",gender:"string",birthdate:i=>m.Birthdate(i),subscribers:"number",timestamp:"number",access_group:"number",approved:"string"},n=["searchFor","value"];if(r=m.Params(r,{searchFor:["user_id","name","email","phone_number","address","gender","birthdate","locale","subscribers","timestamp","access_group","approved"],condition:[">",">=","=","<","<=","gt","gte","eq","lt","lte",()=>"="],value:i=>{let s=t[r.searchFor];if(typeof s=="function")return s(i);if(typeof i!==s)throw new f(`Value does not match the type of "${r.searchFor}" index.`,{code:"INVALID_PARAMETER"});return i},range:i=>{let s=t[r.searchFor];if(typeof s=="function")return s(i);if(typeof i!==s)throw new f(`Range does not match the type of "${r.searchFor}" index.`,{code:"INVALID_PARAMETER"});return i}},n),r?.condition&&r?.condition!=="="&&r.hasOwnProperty("range"))throw new f("Conditions does not apply on range search.",{code:"INVALID_PARAMETER"});if(r.searchFor==="user_id"&&(r.condition!=="="||r.range))throw new f(`Conditions are not allowed on "${r.searchFor}"`,{code:"INVALID_PARAMETER"});if(typeof r?.value=="string"&&!r?.value)throw new f("Value should not be an empty string.",{code:"INVALID_PARAMETER"});if(typeof r?.searchFor=="string"&&!r?.searchFor)throw new f('"searchFor" should not be an empty string.',{code:"INVALID_PARAMETER"});return v.bind(this)("get-users",r,{auth:true,fetchOptions:e})}async function pi(r){await this.__connection;let e=await v.bind(this)("last-verified-email",r,{auth:true});return e.includes("SUCCESS")?(await W.bind(this)().getSession({refreshToken:true}),this.user):e}async function mi(r){return await this.__connection,r=m.Params(r,{username:m.Email,redirect:m.Url},["username"]),await v.bind(this)("request-username-change",r,{auth:true})}var Uu="1.1.0",Cu=class{constructor(r){fe(this,"version",Uu);fe(this,"items",[]);fe(this,"breakWhenError",false);fe(this,"batchSize",1);fe(this,"onProgress");fe(this,"activeCount",0);fe(this,"currentCycleCompleted",[]);fe(this,"stopProcessing",false);if(this.breakWhenError=!!r?.breakWhenError,this.batchSize=r?.batchSize??1,typeof this.batchSize!="number"||this.batchSize<1)throw new Error("batchSize must be at least 1");if(r?.onProgress)if(typeof r.onProgress=="function")this.onProgress=r.onProgress;else throw new Error("onProgress must be a function")}get batchToProcess(){return Math.ceil(this.items.length/this.batchSize)}add(r){let e=Array.isArray(r)?r:[r];for(let t of e){if(typeof t!="function")throw new Error("Each job must be a function that returns a Promise");this.items.push(t);}this.processNext();}processNext(){if(this.stopProcessing||this.items.length===0||this.activeCount>0)return;let r=this.items.splice(0,this.batchSize);this.activeCount=r.length,this.currentCycleCompleted=new Array(r.length),r.forEach((e,t)=>{Promise.resolve().then(()=>e()).then(n=>(this.finalizeJob(t,n,false),n)).catch(n=>(this.finalizeJob(t,n,true),n));});}finalizeJob(r,e,t){if(this.currentCycleCompleted[r]=e,this.activeCount-=1,t&&this.breakWhenError&&(this.stopProcessing=true,this.items=[]),this.activeCount!==0)return;let n=this.currentCycleCompleted.slice();this.currentCycleCompleted=[],this.onProgress&&this.onProgress({batchToProcess:this.batchToProcess,itemsToProcess:this.items.length,completed:n}),this.processNext();}terminate(){this.items=[];}},_i=Cu;var Ke=null,yi=typeof SubmitEvent<"u",Du=typeof HTMLFormElement<"u",et=z(),Tr=0;function wi(r){if(!r)return null;let e=Number(r);if(Number.isFinite(e))return Math.max(0,e*1e3);let t=Date.parse(r);return Number.isNaN(t)?null:Math.max(0,t-Date.now())}function Rr(r,e){return e>0?r/e*100:0}var bi=r=>{let{auth:e,type:t,endpoints:n}=r,i=n[0],s=n[1];if(Tr++,t==="admin"){let o=Object.entries(i).filter(([a,u])=>a.includes(e?"_private":"_public")&&a!=="get_users_private"&&a!=="service_public"&&typeof u=="string").map(([,a])=>a);if(!o.length)throw new f("No available admin gateways.",{code:"INVALID_REQUEST"});return o[Tr%o.length]}if(t==="record"){let o=Object.entries(s).filter(([a,u])=>a.includes(e?"record_private":"record_public")&&typeof u=="string").map(([,a])=>a);if(!o.length)throw new f("No available record gateways.",{code:"INVALID_REQUEST"});return o[Tr%o.length]}throw new f("Invalid gateway type.",{code:"INVALID_REQUEST"})};async function ku(r,e){let t=await Promise.all([this.admin_endpoint,this.record_endpoint]),n=t[0],i=t[1],s=r.split("?"),o=s.length>1?"?"+s[1]:"";switch(r=s[0],r){case "get-users":return n.get_users_private+r+o;case "service":return n.service_public+r+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":case "csr-poll":return bi.bind(this)({auth:e,type:"admin",endpoints:t})+r+o;case "post-record":return (e?i.post_private:i.post_public)+r+o;case "get-records":return (e?i.get_private:i.get_public)+r+o;case "del-files":case "del-records":return i.del_private+r+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 bi.bind(this)({auth:e,type:"record",endpoints:t})+r+o;default:return m.Url(r)+o}}var Ze={};function Ai(){Ke&&(Ke.terminate(),Ke=null);}async function v(r,e=null,t,n){this.log("request",{url:r,data:e,options:t,_etc:n||{}}),t=t||{};let{auth:i=false,method:s="post",bypassAwaitConnection:o=false}=t;s=s.toUpperCase();let a=null,u=e?.service||this.service,c=e?.owner||this.owner,d=null,l=await ku.bind(this)(r,!!i);if(!o&&(a=await this.__connection,!a))throw new f("Invalid connection. The service could have been disabled, or has a restricted CORS.",{code:"INVALID_REQUEST"});let g=t?.tokenHeaders?.idToken===true;(i||g)&&(d=await je.bind(this)());let p={},{fetchMore:h=false,progress:b}=t?.fetchOptions||{};if(t?.fetchOptions&&Object.keys(t.fetchOptions).length){for(let P of ["limit","startKey","ascending"])if(t.fetchOptions.hasOwnProperty(P)){if(P==="startKey"&&t.fetchOptions[P]===null)continue;p[P]=t.fetchOptions[P];}p=m.Params(p,{limit:P=>{if(typeof P!="number")throw new f("Fetch limit should be a number.",{code:"INVALID_REQUEST"});if(P>1e3)throw new f("Fetch limit should be below 1000.",{code:"INVALID_REQUEST"});return P},startKey:P=>P,ascending:"boolean"});}let w=n?.ignoreService?{}:{service:u,owner:c};Object.assign(w,p),e=L(e).data,e?e&&typeof e=="object"&&(e=Object.assign(w,e)):e=w;let _=`${s}:${i?"auth":"public"}:${r}`,R=(()=>{if(e&&typeof e=="object"&&Object.keys(e).length&&!(et&&e instanceof FormData)){let P=function(D){return typeof D=="object"&&D!==null?Object.keys(D).sort().reduce((N,F)=>(typeof D[F]=="object"&&D[F]!==null?N[F]=P(D[F]):N[F]=D[F],N),{}):D};return Q.hash(_+"/"+JSON.stringify(P(e)))}return Q.hash(_+"/"+u)})(),{requestKey:C,requestKeyWithStartKey:I}=Nu.bind(this)({params:e,url:r,fetchMore:h,hashedParams:R});if(!C||C&&typeof C=="object")return C;if(this.log("requestKey",I),typeof I=="string"&&Ze[I]instanceof Promise)return this.log("request:returning pending",I),Ze[I];let k={Accept:"*/*"};if(Object.prototype.hasOwnProperty.call(t,"contentType")&&t.contentType!==void 0){let P=t.contentType===null?"application/x-www-form-urlencoded":t.contentType;P&&(k["Content-Type"]=P);}else k["Content-Type"]="application/json";if(d&&(k.Authorization=d),t?.tokenHeaders){let P=(F,Ce)=>typeof F=="string"?F:F===true?Ce:null,D=P(t.tokenHeaders.accessToken,this.session?.accessToken?.jwtToken||null),N=P(t.tokenHeaders.idToken,this.bearerToken||this.session?.idToken?.jwtToken||d||null);D&&(k["X-Access-Token"]=D),N&&(k["X-Id-Token"]=N);}let ve={public_identifier:this.__public_identifier,service:u,owner:c};k["Content-Meta"]=JSON.stringify(ve);let V={headers:k};if(t?.responseType&&(V.responseType=t.responseType),s==="GET"){if(e){let P=[];if(et&&e instanceof FormData?P=Array.from(e.entries()).map(([D,N])=>{let F=typeof N=="string"?N:N.name;return encodeURIComponent(D)+"="+encodeURIComponent(F)}):P=Object.keys(e).map(D=>{let N=e[D];return typeof N!="string"&&(N=JSON.stringify(N)),encodeURIComponent(D)+"="+encodeURIComponent(N)}),P.length){let D=l.includes("?")?l.endsWith("?")||l.endsWith("&")?"":"&":"?";l+=D+P.join("&");}}V.body=null;}else if(et&&e instanceof FormData)V.body=e;else if(k["Content-Type"]==="application/x-www-form-urlencoded"&&e&&typeof e=="object"){let P=new URLSearchParams;for(let D of Object.keys(e)){let N=e[D];P.append(D,typeof N=="string"?N:JSON.stringify(N));}V.body=P.toString();}else typeof e=="string"?V.body=e:V.body=e?JSON.stringify(e):null;if(V.method=s,Ke===null){let P={batchSize:this.requestBatchSize,breakWhenError:false,onProgress:D=>{this.onBatchProcess.forEach(N=>N(D));}};Ke=new _i(P);}return this.log("request-opt",V),new Promise((P,D)=>{Ke.add([async()=>{let N=Si.bind(this)(l,V,b);Ze[I]=N;try{let F=Fu.bind(this)({hashedParam:C,requestKeyWithStartKey:I,url:r,fetched:await N});return delete Ze[I],this.log("request:end",F),P(F),F}catch(F){throw delete Ze[I],this.log("request:err",F),D(F),F}}]);})}function Nu(r){let{params:e={},url:t,fetchMore:n=false,hashedParams:i}=r||{};if(e.startKey){if(!(typeof e.startKey=="object"&&Object.keys(e.startKey).length)&&e.startKey!=="start"&&e.startKey!=="end")throw new f(`"${e.startKey}" is invalid startKey key.`,{code:"INVALID_PARAMETER"});e.startKey==="start"&&(n=false,delete e.startKey);}if(!n){if(this.__cached_requests?.[t]?.[i]&&delete this.__cached_requests[t][i],this.__startKeyHistory?.[t]?.[i]){if(Array.isArray(this.__startKeyHistory[t][i])&&this.__startKeyHistory[t][i].length)for(let u of this.__startKeyHistory[t][i]){let c=i+Q.hash(u);this.__cached_requests?.[t]&&this.__cached_requests?.[t]?.[c]&&delete this.__cached_requests[t][c];}delete this.__startKeyHistory[t][i];}return {requestKeyWithStartKey:i,requestKey:i}}if(!Array.isArray(this.__startKeyHistory?.[t]?.[i]))return {requestKeyWithStartKey:i,requestKey:i};let s=this.__startKeyHistory[t][i],o=s[s.length-1],a=i;if(o){if(o==="end")return {requestKey:{list:[],startKey:"end",endOfList:true,startKeyHistory:s},requestKeyWithStartKey:a};a+=Q.hash(o),e.startKey=JSON.parse(o);}return this.__cached_requests?.[t]?.[a]?{requestKey:this.__cached_requests[t][a],requestKeyWithStartKey:a}:{requestKeyWithStartKey:a,requestKey:i}}function Si(r,e,t){return new Promise((n,i)=>{let s=new XMLHttpRequest;s.open(e.method||"GET",r);for(var o in e.headers||{})s.setRequestHeader(o,e.headers[o]);e.responseType&&(s.responseType=e.responseType),s.onload=()=>{if(s.status<400)if(e.responseType=="json"||e.responseType=="blob")n(s.response);else {let a=s.responseText;try{a=JSON.parse(a);}catch{}n(a);}else if(s.status===429){let a=s.getResponseHeader("Retry-After"),u=wi(a);u!==null?setTimeout(()=>{Si(r,e,t).then(n,i);},u):i("Too many requests");}else {let a=s.status,u=["INVALID_CORS","INVALID_REQUEST","SERVICE_DISABLED","INVALID_PARAMETER","ERROR","EXISTS","NOT_EXISTS"],c=e.responseType=="blob"?s.response:s.responseText;try{c=JSON.parse(c);}catch{}if(typeof c=="string"){let d=c.split(":"),l=d.splice(0,1)[0].trim(),g=d.join(":").trim();i(new f(g||c,{code:u.includes(l)?l:"ERROR"}));}else if(typeof c=="object"&&c?.message){let d=c?.code||(a?a.toString():null)||"ERROR",l=c.message,g=c?.cause;typeof l=="string"&&(l=l.trim()),i(new f(l,{cause:g,code:d}));}else i(c);}},s.onerror=()=>i("Network error"),s.onabort=()=>i("Aborted"),s.ontimeout=()=>i("Timeout"),typeof t=="function"&&(s.onprogress=a=>{t({status:"download",progress:Rr(a.loaded,a.total),loaded:a.loaded,total:a.total,abort:()=>s.abort()});},s.upload&&(s.upload.onprogress=a=>{t({status:"upload",progress:Rr(a.loaded,a.total),loaded:a.loaded,total:a.total,abort:()=>s.abort()});})),s.send(e.body);})}function Fu(r){let{hashedParam:e,requestKeyWithStartKey:t,url:n,fetched:i}=r;if(!i?.startKey)return i;this.__startKeyHistory.hasOwnProperty(n)||(this.__startKeyHistory[n]={}),this.__startKeyHistory[n].hasOwnProperty(e)||(this.__startKeyHistory[n][e]=[]);let s=i.startKey==="end"?"end":JSON.stringify(i.startKey);return this.__startKeyHistory[n][e].includes(s)||this.__startKeyHistory[n][e].push(s),this.__cached_requests?.[n]||(this.__cached_requests[n]={}),this.__cached_requests[n][t]=i,Object.assign({startKeyHistory:this.__startKeyHistory[n][e]},i)}async function Ct(r,e){await this.__connection;let{record_id:t,service:n=this.service,progress:i}=e;if(!t)throw new f('"record_id" is required.',{code:"INVALID_PARAMETER"});if(yi&&r instanceof SubmitEvent&&(r=r.target),Du&&r instanceof HTMLFormElement&&(r=new FormData(r)),!et||!(r instanceof FormData))throw new f('"fileList" should be a FormData or HTMLFormElement.',{code:"INVALID_PARAMETER"});let o={reserved_key:Qe(),service:n,request:"post"};e?.record_id&&(o.id=e.record_id);let a,u=(p,h,b)=>new Promise((w,_)=>{a=new XMLHttpRequest,a.open("POST",p),a.onload=()=>{let R=a.responseText;try{R=JSON.parse(R);}catch{}if(a.status>=200&&a.status<300)w(R);else if(a.status===429){let C=a.getResponseHeader("Retry-After"),I=wi(C);I!==null?setTimeout(()=>{u(p,h,b).then(w,_);},I):_("Too many requests");}else _(R);},a.onerror=()=>_("Network error"),a.onabort=()=>_("Aborted"),a.ontimeout=()=>_("Timeout"),a.upload&&typeof b=="function"&&(a.upload.onprogress=b),a.send(h);});function c(p){let h="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";if(p===0)return h[0];let b="";for(;p>0;)b=h[p%62]+b,p=Math.floor(p/62);return b}let d=[],l=[],g=[];for(let[p,h]of r.entries()){if(!(h instanceof File))continue;let b=Object.assign({key:p+"/"+h.name,sizeKey:c(h.size),contentType:h.type||null},o),{fields:w=null,url:_,cdn:R}=await v.bind(this)("get-signed-url",b,{auth:!!this.__user});g.push(R);let C=new FormData;for(let I in w)C.append(I,w[I]);C.append("file",h);try{await u(_,C,typeof i=="function"?I=>i({status:"upload",progress:Rr(I.loaded,I.total),currentFile:h,completed:d,failed:l,loaded:I.loaded,total:I.total,abort:()=>a.abort()}):null),d.push(h);}catch{l.push(h);}}return {completed:d,failed:l,bin_endpoints:g}}var Ut={};function T(r){let{preventMultipleCalls:e=false}=r||{};return function(t,n,i){let s=i.value;i.value=function(...o){let a=o[0],u=true,c=null,d="",l={},g=false;if(yi&&a instanceof SubmitEvent){a.preventDefault();let _=window.location.href;c=a.target;let R=new URL(c.action);d=R.href;let C=d?d.match(/(?<=\{).*?(?=\})/g):"";if(C)for(let I of C){if(!I)continue;let k=c.querySelector(`[name="${I}"]`);if(k)if(k.type==="file")for(let K=0;K<=k.files.length-1;K++)k.files[K]&&(l[I]||(l[I]=[]),l[I].push(new Promise((ve,V)=>{let P=new FileReader;P.onload=function(){ve(P.result);},P.readAsDataURL(k.files[K]),P.onerror=V;})));else d=d.replace(`{${I}}`,k.value);}c.getAttribute("action")===null?u=false:g=R.href===_;}let p=async _=>{if(d)for(let R in l)l[R].length&&(d=d.replace(`{${R}}`,(await Promise.all(l[R])).join(",")));return c&&u&&(window.sessionStorage.setItem(`${this.service}:${Q.hash(d)}`,JSON.stringify(_)),g?window.location.replace(d):window.location.href=d),_},h,b=_=>{throw _ instanceof f?_.name=n+"()":_=_ instanceof Error?_:new f(_,{name:n+"()"}),_},w=async()=>{try{if(h=s.bind(this)(...o),h instanceof Promise){let _=await h;return p(_)}return p(h)}catch(_){throw b(_)}};if(e){let _=`${n}:${this?.__public_identifier||""}:${this?.service||""}:${this?.owner||""}`;return Ut?.[_]||(Ut[_]=w().finally(()=>{delete Ut[_];})),Ut[_]}return w()};}}async function Ei(){await this.__connection;let r=`${this.service}:${Q.hash(window.location.href.split("?")[0])}`,e=window.sessionStorage.getItem(r);if(window.sessionStorage.removeItem(r),e!==null){try{e=JSON.parse(e);}catch{}return e}return null}var Lu=128,Ou=64,Mu=128,Vu=256,qu="\u{10FFFF}",Bu=/[\u0000-\u001F\u007F]|\u{10FFFF}/u,$u=/[\/!*#]/,ju={"/":"%2F","!":"%21","*":"%2A","#":"%23"},Ku={"%2F":"/","%21":"!","%2A":"*","%23":"#"};function Hu(r){return r.replace(/%/g,"%25").replace(/[\/!*#]/g,t=>ju[t]||t)}function ie(r){return typeof r!="string"?r:r.replace(/%(2F|21|2A|23)/gi,t=>{let n=t.toUpperCase();return Ku[n]||t}).replace(/%25/gi,"%")}function Ae(r,e,t={}){let{allowEmpty:n=false,maxLength:i,blockKeyDelimiters:s=false,disallowLeadingDollar:o=false,onlyAlphanumeric:a=false}=t;if(typeof r!="string")throw new f(`"${e}" should be type: <string>.`,{code:"INVALID_PARAMETER"});if(a&&/[^a-zA-Z0-9]/.test(r))throw new f(`"${e}" should only contain alphanumeric characters.`,{code:"INVALID_PARAMETER"});if(!n&&r.length===0)throw new f(`"${e}" is required.`,{code:"INVALID_PARAMETER"});if(i&&r.length>i)throw new f(`"${e}" should be <= ${i} characters.`,{code:"INVALID_PARAMETER"});if(Bu.test(r)||r.includes(qu))throw new f(`"${e}" cannot include control characters or unsupported sentinel characters.`,{code:"INVALID_PARAMETER"});if(s&&$u.test(r)&&(r=Hu(r)),o&&r.startsWith("$"))throw new f(`"${e}" cannot start with "$".`,{code:"INVALID_PARAMETER"});return r}function Ir(r,e="table.name"){return Ae(r,e,{allowEmpty:false,maxLength:Lu,blockKeyDelimiters:true})}function Pr(r,e="tag"){return Ae(r,e,{allowEmpty:false,maxLength:Ou,blockKeyDelimiters:true})}function tt(r,e="index.name"){return Ae(r,e,{allowEmpty:false,maxLength:Mu,blockKeyDelimiters:true,disallowLeadingDollar:true})}function vi(r,e="index.value"){return Ae(r,e,{allowEmpty:true,maxLength:Vu})}function Ti(r){if(!r.record_id&&!r.unique_id)return null;let e={};return r?.service&&(e.service=r.service),r?.owner&&(e.owner=r.owner),r?.record_id?e.record_id=Ae(r.record_id,"record_id",{allowEmpty:false,onlyAlphanumeric:true}):r?.unique_id&&(e.unique_id=r.unique_id),e}function xr(r){if(r===void 0)return 0;if(typeof r=="number"){if(r>99||r<0)throw new f('"table.access_group" value should be within a range of 0 ~ 99.',{code:"INVALID_REQUEST"})}else if(typeof r=="string"){if(r={private:"private",public:0,authorized:1,admin:99}[r],r===void 0)throw new f('"table.access_group" is invalid.',{code:"INVALID_PARAMETER"})}else throw new f('"table.access_group" should be type: <number | string>.',{code:"INVALID_PARAMETER"});if(!this.__user&&r)throw new f("Unsigned users have no access to records with access group.",{code:"INVALID_REQUEST"});return r}var Dt=4503599627370496;function kt(r){if(typeof r=="number"){if(r>Dt||r<-Dt)throw new f(`Number value should be within range -${Dt} ~ +${Dt}`,{code:"INVALID_PARAMETER"});return r}if(typeof r=="boolean")return r;if(typeof r=="string")return vi(r,"index.value");throw new f('"index.value" should be type: <number | boolean | string>.',{code:"INVALID_PARAMETER"})}function Ri(r,e){if(!e.index||!("value"in e.index))throw new f('"index.value" is required.',{code:"INVALID_PARAMETER"});if(e.index.name==="$record_id")throw new f(`Cannot do "index.range" on ${e.index.name}`,{code:"INVALID_PARAMETER"});if(typeof e.index.value!=typeof r)throw new f('"index.range" type should match the type of "index.value".',{code:"INVALID_PARAMETER"});return typeof r=="string"?vi(r,"index.range"):r}var Nt={};async function He(r,e){let t={user_id:"",record_id:"",updated:0,uploaded:0,readonly:false,table:{name:"",access_group:0,subscription:{is_subscription_record:false,upload_to_feed:false,notify_subscribers:false,feed_referencing_records:false,notify_referencing_records:false}},referenced_count:0,source:{referencing_limit:null,prevent_multiple_referencing:false,can_remove_referencing_records:false,only_granted_can_reference:false},ip:"",bin:{}},n=false;function i(o){let a=o=="**"?"private":parseInt(o);return a=a==0?"public":a==1?"authorized":a==99?"admin":a,a}let s={ip:o=>{let a=o.split("#"),u=a[0];a.length>1&&(t.unique_id=a[1]),u.slice(-1)==="R"?(t.readonly=true,u=u.slice(0,-1)):t.readonly=false,/^\d{1,3}-\d{1,3}-\d{1,3}-\d{1,3}$/.test(u)&&(u=u.split("-").join("."),n=true),t.ip=u;},rec:o=>{if(!o)return;t.record_id=o;let a=o.substring(0,o.length-9),u=ne(a);t.uploaded=u;},usr:o=>{t.user_id=o;},tbl:o=>{if(o&&!t.table.name){let a=o.split("/");t.table.name=ie(a[0]),t.table.access_group=i(a[2]),a?.[3]&&(t.table.subscription.is_subscription_record=true);}},usr_tbl:o=>{let a=o.split("/");t.user_id||(t.user_id=a[0]),t.table.name||(t.table.name=ie(a[1]),t.table.access_group=i(a[3]),a?.[4]&&(t.table.subscription.is_subscription_record=true));},idx:o=>{if(!o)return;let a=o.split("!"),u=ie(a.splice(0,1)[0]),c=Wu("!"+a.join("!"));typeof c=="string"&&(c=ie(c)),t.index={name:u,value:c};},ref:o=>{o&&(t.reference=o.split("/")[0]);},tags:o=>{t.tags=Array.isArray(o)?o.map(a=>ie(a)):o;},upd:o=>{t.updated=o;},acpt_mrf:o=>{t.source.prevent_multiple_referencing=!o;},ref_limt:o=>{t.source.referencing_limit=o;},rfd:o=>{t.referenced_count=o;},bin:async o=>{let a={},u=t?.reference||null;if(Array.isArray(o)){let c=await Promise.all(o.map(async d=>{try{let l=d.split("/").slice(3).join("/"),g=l.split("/");if(g.length<12)return null;let p=decodeURIComponent(g[g.length-1]),h=decodeURIComponent(g[10]),b=g[9],w=g[8],_=i(g[6]),R=d;if(_!=="public")try{R=await Ft.bind(this)(d,{dataType:"endpoint",_ref:u});}catch(I){console.error("Error getting signed url for private file:",I),R=d;}let C={access_group:_,filename:p,url:R,path:l,size:ne(b),uploaded:ne(w),getFile:(I,k)=>{let K={dataType:I||"download",progress:k,_ref:u,_update:C};return Ft.bind(this)(R,K)}};return {pathKey:h,obj:C}}catch{return null}}));for(let d of c)if(d){if(a[d.pathKey]){a[d.pathKey].push(d.obj);continue}a[d.pathKey]=[d.obj];}}t.bin=a;},prv_acs:o=>{for(let a in o)["notify_subscribers","upload_to_feed","feed_referencing_records","notify_referencing_records"].includes(a)?t.table.subscription[a]=o[a]:t.source[a]=o[a];},data:o=>{let a=o;o==="!D%{}"?a={}:o==="!L%[]"&&(a=[]),t.data=a;}};if(r.record_id)return r;for(let o in s)if(r.hasOwnProperty(o)){let a=s[o](r[o]);a instanceof Promise&&await a;}return n&&(t.user_id="anonymous:"+t.user_id),t}function Wu(r){let e=r.substring(3);switch(r.substring(0,3)){case "!S%":return e;case "!N%":let n=e.split("."),i=Number(n[0])-4503599627370496;return n.length===1?i:parseFloat(i.toString()+"."+n[1]);case "!B%":return e==="1";case "!L%":case "!D%":try{return JSON.parse(e)}catch{throw new f("Value parse error.",{code:"PARSE_ERROR"})}default:return r}}async function Ii(r){let{endpoints:e}=r;if(typeof e=="string"&&(e=[e]),!Array.isArray(e))throw new f('"endpoints" should be type: array | string.',{code:"INVALID_PARAMETER"});let t=await v.bind(this)("del-files",{endpoints:e,storage:"records"},{auth:true,method:"post"}),n=[];for(let i in t)n.push(He.bind(this)(t[i]));return Promise.all(n)}async function Ft(r,e){if(typeof r!="string")throw new f('"url" should be type: string.',{code:"INVALID_PARAMETER"});let t=r.split("?"),n=t.shift()||"",i=t.length?"?"+t.join("?"):"",s=m.Url(n);r=s+i;let o=false,a=s.split("/"),c=a[2].split("."),d=null;c.length===3&&c[1]==="skapi"&&(d=c[0],o=true);let l=a.slice(3),g=false;if(!o&&(l[0]==="auth"||l[0]==="publ"))try{m.UserId(l[2]),m.UserId(l[3]),g=l[0]=="auth",o=!0;}catch{throw new f("Invalid file url.",{code:"INVALID_PARAMETER"})}let p=d?null:l[1];if(e=m.Params(e,{expires:["number",()=>0],dataType:["base64","blob","endpoint","text","info",()=>"download"],progress:"function",_ref:[null,"string"],_update:_=>_}),e?.dataType==="info")return {url:r,filename:l[l.length-1],fileKey:l[l.length-2],access_group:l[6]==="**"?"private":l[6]==="01"?"authorized":l[6]==="00"?"public":parseInt(l[6]),uploader:l[3],record_id:l[4]==="records"?l[5]:"N/A",filesize:ne(l[9]),uploaded:ne(l[8])};let h=r.split("/").slice(-1)[0],b=e.expires;if(b){if(!o)throw new f("Expires option can only be used on skapi cdn endpoints.",{code:"INVALID_PARAMETER"});if(b<0)throw new f('"config.expires" should be > 0. (seconds)',{code:"INVALID_PARAMETER"});let _={request:d?"get-host":"get",id:d||l[5],key:r,expires:b};p&&(_.service=p),r=(await v.bind(this)("get-signed-url",_,{auth:true})).url;}else if(g){let _=Math.floor(Date.now()/1e3);if(!this.bearerToken&&(!this.session?.idToken?.payload?.exp||this.session.idToken.payload.exp<_)){this.log("getFile:requesting new token",null);try{await W.bind(this)().getSession({refreshToken:!0}),this.log("getFile:received new tokens",{exp:this.session?.idToken?.payload?.exp,currTime:_,expiresIn:this.session?.idToken?.payload?.exp-_,token:this.session?.accessToken?.jwtToken,refreshToken:this.session?.refreshToken?.token});}catch(k){throw this.log("getFile:new token error",k),new f("User login is required.",{code:"INVALID_REQUEST"})}}let R=this.bearerToken||this.session?.idToken?.jwtToken;if(!R||!this.user?.user_id)throw new f("User login is required.",{code:"INVALID_REQUEST"});r+=`${r.includes("?")?"&":"?"}t=${encodeURIComponent(R)}`;let C=l[6]==="**"?"**":parseInt(l[6]),I=this.user?.access_group??-1;if(this.user.user_id!==l[3]&&(C==="**"||I<C)){let k=l[5];if(this.__private_access_key[k]&&typeof this.__private_access_key[k]=="string")r+=`&p=${encodeURIComponent(this.__private_access_key[k])}`;else if(this.owner!==this.host)try{let K=await this.requestPrivateRecordAccessKey({record_id:k,reference_id:e?._ref});r+=`&p=${encodeURIComponent(K)}`;}catch{}}}if(e?.dataType==="endpoint")return e._update&&(e._update.url=r),r;if(e?.dataType==="download"){let _=document.createElement("a");return _.href=r,document.body.appendChild(_),_.setAttribute("download",h),_.target="_blank",_.click(),document.body.removeChild(_),null}return new Promise(async(_,R)=>{try{let C=await v.bind(this)(r,null,{method:"get",contentType:null,responseType:e?.dataType==="text"?"text":"blob",fetchOptions:{progress:e?.progress}},{ignoreService:!0});if(e?.dataType==="base64"){let I=new FileReader;I.onloadend=()=>_(I.result),I.readAsDataURL(C);}else _(C);}catch(C){R(C);}})}async function Pi(r,e=false){r=L(r,{ignoreEmpty:true}).data||{};let t="",n=Ti(r);if(n)r=n,t=r.record_id||r.unique_id,typeof t=="string"&&(typeof this.__private_access_key?.[t]=="string"&&(r.private_key=this.__private_access_key?.[t]||void 0),this.__my_unique_ids[t]&&(e?delete this.__my_unique_ids[t]:r.record_id=this.__my_unique_ids[t]));else {let i=await J.bind(this)(),s=r?.reference,o=false;typeof s=="object"&&Object.keys(s).length&&(s?.record_id||s?.unique_id?(t=s.record_id||s.unique_id,t&&typeof this.__private_access_key?.[t]=="string"&&(r.private_key=this.__private_access_key?.[t]||void 0),r.reference=t):s?.user_id&&(o=s.user_id===this.user?.user_id,r.reference=s.user_id)),typeof r?.table=="string"&&(r.table={name:r.table,access_group:0}),r.index&&r.index.hasOwnProperty("range")&&r.index.hasOwnProperty("condition")&&delete r.index.range;let a=u=>({table:{name:c=>Ir(c,"table.name"),access_group:xr.bind(this),subscription:c=>m.UserId(c,'User ID in "subscription"')},reference:"string",index:{name:["$updated","$uploaded","$referenced_count","$user_id",c=>tt(c,"index.name")],value:c=>{let d={$updated:"number",$uploaded:"number",$referenced_count:"number",$user_id:m.UserId};if(d.hasOwnProperty(u.index.name)){let l=d[u.index.name];if(typeof l=="function")return l(c);if(l!==typeof c)throw new f(`"index.value" should be type: ${l}.`,{code:"INVALID_PARAMETER"});return c}return typeof c=="string"&&!c?"":kt(c)},condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq"],range:c=>Ri(c,u)},tag:c=>{if(c==null)return c;if(typeof c=="string")return Pr(c,"tag");throw new f('"tag" should be type: string.',{code:"INVALID_PARAMETER"})},private_key:"string"});r=m.Params(r||{},a(r),o||i?[]:["table"],{ignoreEmpty:true});}return {query:r,is_reference_fetch:t}}async function xi(r,e){await this.__connection;let t=await Pi.bind(this)(r),n=t.is_reference_fetch,i=await v.bind(this)("get-records",t.query,{fetchOptions:e,auth:!!this.__user,method:this.__user?"post":"get"});n&&i?.reference_private_key&&typeof i.reference_private_key=="string"&&(this.__private_access_key[n]=i.reference_private_key);let s=[];for(let o in i.list)s.push(He.bind(this)(i.list[o]));return i.list=await Promise.all(s),i}function Ui(r){let e="",t=[],n=m.Params(r||{},{record_id:s=>Ae(s,"record_id",{allowEmpty:false,onlyAlphanumeric:true}),unique_id:["string",null],readonly:"boolean",table:{name:s=>Ir(s,"table.name"),subscription:[null,{is_subscription_record:"boolean",upload_to_feed:"boolean",notify_subscribers:"boolean",feed_referencing_records:"boolean",notify_referencing_records:"boolean"}],access_group:xr.bind(this)},source:{referencing_limit:s=>{if(s===null)return null;if(typeof s=="number"){if(0>s)throw new f('"reference_limit" should be >= 0',{code:"INVALID_PARAMETER"});if(s>4503599627370546)throw new f('"reference_limit" should be <= 4503599627370546',{code:"INVALID_PARAMETER"});return s}throw new f('"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:s=>{if(s===void 0)return;if(!s||Array.isArray(s)&&!s.length)return null;let o={name:u=>tt(u,'"name" in "index_restrictions"'),value:u=>kt(u),condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne",()=>null],range:u=>{if(u!==null&&typeof s.value!=typeof u)throw new f('Index restriction "range" type should match the type of "value".',{code:"INVALID_PARAMETER"});if(!s.hasOwnProperty("value"))throw new f('Index restriction "value" is required.',{code:"INVALID_PARAMETER"});return u}};Array.isArray(s)||(s=[s]);let a=s.map(u=>m.Params(u,o,["name"]));if(a.length)for(let u of a)u.condition&&u.hasOwnProperty("range")&&delete u.range;return a}},reference:s=>{if(s===null)return {record_id:null};if(s){if(typeof s=="string")return e=s,this.__my_unique_ids[s]?this.__my_unique_ids[s]:s;if(typeof s!="object")throw new f('"reference" should be type: <string | object>.',{code:"INVALID_PARAMETER"});return m.Params(s,{unique_id:"string",record_id:o=>o==null?o:(e=o,typeof this.__private_access_key?.[o]=="string"&&(r.reference_private_key=this.__private_access_key[o]||void 0),Ae(o,"reference.record_id",{allowEmpty:false,onlyAlphanumeric:true}))})}},index:[null,{name:s=>tt(s,"index.name"),value:s=>kt(s)}],tags:s=>{if(s==null)return s;if(typeof s=="string"&&(s=s.split(",").map(o=>o.trim())),!Array.isArray(s))throw new f('"tag" should be type: <string | string[]>.',{code:"INVALID_PARAMETER"});return s.map(o=>Pr(o,"tag"))},remove_bin:s=>{if(!s)return null;let o=[];if(Array.isArray(s))for(let a of s)if(typeof a=="string")o.push(decodeURIComponent(a.split("?")[0]));else if(a.url&&a.size&&a.filename){let c=a.url.split("/").slice(0,3).join("/")+"/"+a.path;o.push(c);}else throw new f('"remove_bin" should be type: <string[] | BinaryFile[] | null>',{code:"INVALID_PARAMETER"});else throw new f('"remove_bin" should be type: <string[] | BinaryFile[] | null>',{code:"INVALID_PARAMETER"});return o},progress:"function",data:s=>s},[],{precall:s=>{let o=s?.data||{};if(!o?.record_id&&!o.table)throw new f('"table.name" is required.',{code:"INVALID_PARAMETER"});typeof o.table=="string"&&(o.table={name:o.table,access_group:0}),s.files&&(t=s.files);}}),i=r.progress||null;if(delete n.progress,!this.__user){let s=!!(n.table?.subscription?.is_subscription_record||n.table?.subscription?.upload_to_feed||n.table?.subscription?.notify_subscribers||n.table?.subscription?.feed_referencing_records||n.table?.subscription?.notify_referencing_records);if(n.record_id)throw new f("Public users cannot update existing records.",{code:"INVALID_REQUEST"});if(n.table.access_group!=="public"&&n.table.access_group!==0)throw new f("Public users can only post records to public tables.",{code:"INVALID_REQUEST"});if(s)throw new f("Public users cannot post subscription records.",{code:"INVALID_REQUEST"});if(n.remove_bin)throw new f("Public users cannot remove files from records.",{code:"INVALID_REQUEST"});if(n.unique_id)throw new f("Public users cannot set unique_id for records.",{code:"INVALID_REQUEST"})}return {config:n,progress:i,is_reference_post:e,files:t}}async function Ci(r){if(await this.__connection,!Array.isArray(r)||!r.length)throw new f('"params" should be a non-empty array.',{code:"INVALID_PARAMETER"});let e=[],t,n,i=null,o={_is_bulk_:r.map((l,g)=>{if(!l||typeof l!="object"||Array.isArray(l))throw new f(`"params[${g}]" should be type: <object>.`,{code:"INVALID_PARAMETER"});let p=Ui.bind(this)(l),h=p.config;if(p.is_reference_post&&e.push(p.is_reference_post),typeof h.progress=="function"&&i===null&&(i=h.progress),h.service!==void 0){if(t===void 0)t=h.service;else if(t!==h.service)throw new f('All bulk params should share the same "service" value.',{code:"INVALID_PARAMETER"})}if(h.owner!==void 0){if(n===void 0)n=h.owner;else if(n!==h.owner)throw new f('All bulk params should share the same "owner" value.',{code:"INVALID_PARAMETER"})}return delete h.progress,delete h.service,delete h.owner,h}),service:"",owner:""};t!==void 0&&(o.service=t),n!==void 0&&(o.owner=n);let a={auth:!!this.__user,method:"post"},u={};Object.keys(u).length&&Object.assign(a,{fetchOptions:u});let c=await v.bind(this)("post-record",o,a),d=await Promise.all(c.map(l=>He.bind(this)(l,"called from postRecord")));for(let l=0;l<c.length;l++){let g=c[l],p=d[l];if(typeof g?.reference_private_key=="string")for(let h of e)this.__private_access_key[h]=g.reference_private_key;p?.unique_id&&(this.__my_unique_ids[p.unique_id]=p.record_id);}return d}async function Di(r,e,t){if(await this.__connection,!e)throw new f('"config" argument is required.',{code:"INVALID_PARAMETER"});let n=Ui.bind(this)(e),i=n.config,s=n.progress,o=n.is_reference_post,a={auth:!!this.__user,method:"post"},u=[],c=L(r);t&&Array.isArray(t)&&t.length&&(u=u.concat(t)),c.files&&Array.isArray(c.files)&&c.files.length&&(u=u.concat(c.files));let d=null;d=Object.assign({data:c.data},i);let l={};typeof s=="function"&&(l.progress=s),Object.keys(l).length&&Object.assign(a,{fetchOptions:l});let g=await v.bind(this)("post-record",d,a);if(z()&&u.length){let h=new FormData;for(let _ of u)h.append(_.name,_.file,_.file.name);let b={record_id:g.rec,progress:s};i.hasOwnProperty("service")&&(b.service=i.service);let{bin_endpoints:w}=await Ct.bind(this)(h,b);g.bin?g.bin.push(...w):g.bin=w;}o&&typeof g?.reference_private_key=="string"&&(this.__private_access_key[o]=g.reference_private_key);let p=await He.bind(this)(g,"called from postRecord");return p.unique_id&&(this.__my_unique_ids[p.unique_id]=p.record_id,z()&&window.sessionStorage.setItem(`${this.service}:uniqueids`,JSON.stringify(this.__my_unique_ids))),p}async function ki(r,e){let t=await v.bind(this)("get-table",m.Params(r||{},{table:"string",condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}),Object.assign({auth:!!this.__user},{fetchOptions:e})),n={cnt_rec:"number_of_records",tbl:"table",srvc:"service",grp_:"number_of_records_in_access_group_"};if(Array.isArray(t?.list))for(let i of t.list){for(let s in n){if(s==="grp_"){for(let o in i)if(o.startsWith("grp_")){let a=o.substring(4);a==="pv"?a="private":a==="00"?a="public":a==="01"?a="authorized":a==="99"&&(a="admin"),i[`number_of_records_in_access_group_${a}`]=i[o],delete i[o];}}i.hasOwnProperty(s)&&(i[n[s]]=i[s],delete i[s]);}typeof i.table=="string"&&(i.table=ie(i.table));}return t}async function Ni(r,e){if(!r?.table)throw new f('"table" is required.',{code:"INVALID_PARAMETER"});let t=m.Params(r||{},{table:"string",index:s=>tt(s,"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(t.hasOwnProperty("order")){if(!t.order?.by)throw new f('"order.by" is required.',{code:"INVALID_PARAMETER"});if(t.order.hasOwnProperty("condition")&&!t.order.hasOwnProperty("value"))throw new f('"value" is required for "condition".',{code:"INVALID_PARAMETER"});if(t.hasOwnProperty("index")&&t.index.substring(t.index.length-1)!==".")throw new f('"index" should be a parent index name of the compound index when using "order.by"',{code:"INVALID_PARAMETER"})}let n=await v.bind(this)("get-index",t,Object.assign({auth:!!this.__user},{fetchOptions:e})),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(n?.list)&&(n.list=n.list.map(s=>{let o=s.idx.split("/"),a={table:ie(o[1]),index:ie(o[2]),number_of_records:s.cnt_rec};for(let u in i)Object.prototype.hasOwnProperty.call(s,u)&&(a[i[u]]=s[u]);return a})),n}async function Fi(r,e){let t=await v.bind(this)("get-tag",m.Params(r||{},{table:"string",tag:"string",condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}),Object.assign({auth:!!this.__user},{fetchOptions:e}));return Array.isArray(t?.list)&&(t.list=t.list.map(n=>{let i=n.tag.split("/");return {table:ie(i[1]),tag:ie(i[0]),number_of_records:n.cnt_rec}})),t}async function Li(r,e){let t=await v.bind(this)("get-uniqueid",m.Params(r||{},{unique_id:"string",condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}),Object.assign({auth:!!this.__user},{fetchOptions:e}));if(Array.isArray(t?.list))for(let n in t.list){let i=t.list[n];t.list[n]={unique_id:i.unq,record_id:i.rec};}return t}async function Oi(r,e){await this.__connection;let t=await Pi.bind(this)(r,true),n=t.is_reference_fetch,i=await v.bind(this)("del-records",t.query,{auth:true,fetchOptions:e});return n&&typeof i?.reference_private_key=="string"&&(this.__private_access_key[n]=i.reference_private_key),i?.message||i}function Mi(r){return $i.bind(this)({record_id:r.record_id,user_id:r.user_id,execute:"add"})}function Vi(r){return $i.bind(this)({record_id:r.record_id,user_id:r.user_id||null,execute:"remove"})}async function qi(r,e){let t={record_id:r.record_id||void 0,user_id:r.user_id||void 0,execute:"list"};if(!t.record_id&&!t.user_id)throw new f("Either record_id or user_id must be provided.",{code:"INVALID_PARAMETER"});if(t.user_id)if(typeof t.user_id=="string")m.UserId(t.user_id),t.user_id=[t.user_id];else if(Array.isArray(t.user_id))for(let s of t.user_id)m.UserId(s);else throw new f("user_id should be type: <string | string[]>",{code:"INVALID_PARAMETER"});let n=s=>(s.rec_usr?(s.record_id=s.rec_usr.split("/")[0],s.user_id=s.rec_usr.split("/")[1]):s.usr_rec&&(s.user_id=s.usr_rec.split("/")[0],s.record_id=s.usr_rec.split("/")[1]),s),i=await v.bind(this)("grant-private-access",t,{auth:true,fetchOptions:e});return i.list=i.list.map(n),i}function Bi(r){let e=r.record_id,t=r.reference_id||void 0;if(!e)throw new f("Record ID is required.",{code:"INVALID_PARAMETER"});if(typeof e!="string")throw new f("Record ID should be type: <string | string[]>",{code:"INVALID_PARAMETER"});if(t&&typeof t!="string")throw new f("Reference ID should be type: <string>",{code:"INVALID_PARAMETER"});if(typeof this.__private_access_key[e]=="string")return Promise.resolve(this.__private_access_key[e]);if(Nt[e])return Nt[e];let n=v.bind(this)("request-private-access-key",{record_id:e,reference_id:t},{auth:true}).then(i=>{let s=typeof i=="string"?i:i?.private_key;if(typeof s!="string")throw new f("Invalid private access key response.",{code:"ERROR"});return this.__private_access_key[e]=s,s}).finally(()=>{delete Nt[e];});return Nt[e]=n,n}function $i(r){r.execute;let t=m.Params(r,{record_id:"string",user_id:n=>{if(!n)throw new f("User ID is required.",{code:"INVALID_PARAMETER"});let i=n;if(typeof i=="string"&&(i=[i]),i.length>100)throw new f("Cannot process more than 100 users at once.",{code:"INVALID_REQUEST"});for(let s of i)m.UserId(s,'User ID in "user_id"');return i},execute:["add","remove"]},["execute","record_id","user_id"]);return t.user_id||(t.user_id=null),v.bind(this)("grant-private-access",t,{auth:true})}var x={},$={},se={},de={},le={},Lt={},Ot={};function ji(r,e,t){r[e]||(r[e]=[]),r[e].push(t);}async function Mt(r,e,t){let n=[];if(r[e]){for(let i of r[e])if(i){let s=t(i);s instanceof Promise&&(s=await s),n.push(s);}delete r[e];}return n}async function Cr(r,e){if(!this?.session?.accessToken?.jwtToken)throw new f("Access token is required.",{code:"INVALID_PARAMETER"});let t=await this.__socket;async function n(i,s,o){this.log("answerSdpOffer from",s),await x[s].setRemoteDescription(new RTCSessionDescription(i));let a=await x[s].createAnswer();await x[s].setLocalDescription(a),o.send(JSON.stringify({action:"rtc",uid:s,content:{sdpanswer:a},token:this.session.accessToken.jwtToken}));}x?.[e]?r?(await Mt(Ot,e,i=>n.bind(this)(i,e,t)),await n.bind(this)(r,e,t)):await Mt(Ot,e,i=>n.bind(this)(i,e,t)):r&&ji(Ot,e,r);}async function Dr(r,e){if(this.log("receiveIceCandidate",r),x?.[e]&&x[e]?.remoteDescription&&x[e]?.remoteDescription?.type){if(!r)return Mt(Lt,e,t=>x[e].addIceCandidate(t));await Mt(Lt,e,t=>x[e].addIceCandidate(t)),await x[e].addIceCandidate(r);}else ji(Lt,e,r);}async function oe(r){if(typeof window>"u"||window._runningInNodeJS)throw new f("WebRTC is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});m.Params(r,{cid:s=>{if(typeof s!="string")throw new f('"cid" should be type: <string>.',{code:"INVALID_PARAMETER"});if(s&&s.slice(0,4)!=="cid:")throw new f('"cid" should be a valid connection id.',{code:"INVALID_PARAMETER"});return s},close:"boolean"});let e=await this.__socket,{cid:t,close_all:n=false}=r||{};if(!n&&!t)throw new f('"cid" is required.',{code:"INVALID_PARAMETER"});let i=s=>{if(!s)throw new f('"cid" is required.',{code:"INVALID_PARAMETER"});if(delete Ot[s],delete Lt[s],$[s]&&Object.values($[s]).forEach(o=>{o.readyState!=="closed"&&o.close();}),delete $[s],x?.[s]){x[s].connectionState!=="closed"&&(x[s].close(),e.send(JSON.stringify({action:"rtc",uid:s,content:{hungup:this.user.user_id},token:this.session.accessToken.jwtToken})));let o={type:"connectionstatechange",target:x[s],timestamp:new Date().toISOString(),state:x[s].connectionState,iceState:x[s].iceConnectionState,signalingState:x[s].signalingState};le[s]&&le[s](o),this.log("closeRTC",o);}delete le[s],delete de[s],delete se[s],delete x[s];};if(n)for(let s in x)i(s);else i(t);this.log("Cleaning up media stream..."),this.__mediaStream&&(this.__mediaStream.getTracks().forEach(s=>{s.stop();}),this.__mediaStream=null);}async function Ki(r){if(r instanceof MediaStream)return r;if(!r.video&&!r.audio){let e=new MediaStream,t=document.createElement("canvas");t.width=1,t.height=1;let i=t.captureStream().getVideoTracks()[0];return e.addTrack(i),e}return window.navigator.mediaDevices.getUserMedia(r)}async function Hi(r,e){if(typeof window>"u"||window._runningInNodeJS)throw new f("WebRTC is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(typeof e!="function")throw new f("Callback is required.",{code:"INVALID_PARAMETER"});if(!this?.session?.accessToken?.jwtToken)throw new f("Access token is required.",{code:"INVALID_PARAMETER"});r=m.Params(r,{cid:o=>{if(typeof o!="string")throw new f('"cid" should be type: <string>.',{code:"INVALID_PARAMETER"});if(o&&o.slice(0,4)!=="cid:")throw new f('"cid" should be a valid connection id.',{code:"INVALID_PARAMETER"});return o},ice:["string",()=>"stun:stun.skapi.com:3468"],media:o=>o,channels:["text-chat","file-transfer","video-chat","voice-chat","gaming",{ordered:"boolean",maxPacketLifeTime:"number",maxRetransmits:"number",protocol:"string"},()=>[{ordered:true,maxPacketLifeTime:10,protocol:"default"}]]},["cid"]);let{cid:t,ice:n}=r;if(!(r?.media instanceof MediaStream)&&(r?.media?.video||r?.media?.audio)&&window.location.hostname!=="localhost"&&window.location.protocol!=="https:")throw new f("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 f("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});if(i.readyState!==1)throw new f("Realtime connection is not ready.",{code:"INVALID_REQUEST"});let s={iceServers:[{urls:n}]};x?.[t]||(x[t]=new RTCPeerConnection(s)),r?.media&&(this.__mediaStream=await Ki(r.media),this.__mediaStream.getTracks().forEach(o=>{x[t].addTrack(o,this.__mediaStream);})),le[t]=e,$[t]||($[t]={});for(let o=0;o<r.channels.length;o++){let a=r.channels[o];if(typeof a=="string")switch(a){case "text-chat":a={ordered:true,maxRetransmits:10,protocol:"text-chat"};break;case "file-transfer":a={ordered:false,maxPacketLifeTime:3e3,protocol:"file-transfer"};break;case "video-chat":a={ordered:true,maxRetransmits:10,protocol:"video-chat"};break;case "voice-chat":a={ordered:true,maxRetransmits:10,protocol:"voice-chat"};break;case "gaming":a={ordered:false,maxPacketLifeTime:100,protocol:"gaming"};break;default:a={ordered:true,maxRetransmits:10,protocol:"default"};break}let u=a.protocol||"default";if(Object.keys($[t]).includes(u))throw new f(`Data channel with the protocol "${u}" already exists.`,{code:"INVALID_REQUEST"});let c=x[t].createDataChannel(u,a);$[t][u]=c;}for(let o in $[t]){let a=$[t][o];Gi.bind(this)(t,a);}return Ji.bind(this)(t,["onnegotiationneeded"]),await Ur.bind(this)(t),{hangup:()=>se[t]&&se[t](false),connection:new Promise(o=>{se[t]=(a=>{if(this.log("receiver picked up the call",t),!a)return oe.bind(this)({cid:t}),null;x[t].onnegotiationneeded=()=>{this.log("onnegotiationneeded",`sending offer to "${t}".`),Ur.bind(this)(t),le[t]&&le[t]({type:"negotiationneeded",target:x[t],timestamp:new Date().toISOString(),signalingState:x[t].signalingState,connectionState:x[t].iceConnectionState,gatheringState:x[t].iceGatheringState});},o({target:x[t],channels:$[t],hangup:()=>oe.bind(this)({cid:t}),media:this.__mediaStream});}).bind(this);})}}function Wi(r){return async(e,t)=>{e=e||{},e=L(e).data;let n=r.sender_cid,i=await this.__socket;if(!de[n])return null;if(typeof t!="function")throw new f("Callback is required.",{code:"INVALID_PARAMETER"});if(!(e?.media instanceof MediaStream)&&(e?.media?.video||e?.media?.audio)&&window.location.hostname!=="localhost"&&window.location.protocol!=="https:")throw new f("Media stream is only supported on either localhost or https.",{code:"INVALID_REQUEST"});let{ice:s="stun:stun.skapi.com:3468"}=e;return x?.[n]||(x[n]=new RTCPeerConnection({iceServers:[{urls:s}]})),e?.media&&(this.__mediaStream=await Ki(e.media),this.__mediaStream.getTracks().forEach(o=>{x[n].addTrack(o,this.__mediaStream);})),delete de[n],le[n]=t,$[n]||($[n]={}),x[n].ondatachannel=o=>{this.log("ondatachannel",`received data channel "${o.channel.label}".`);let a=o.channel;$[n][a.label]=a,Gi.bind(this)(n,a);},Ji.bind(this)(n,["onnegotiationneeded"]),await Cr.bind(this)(null,n),await Dr.bind(this)(null,n),i.send(JSON.stringify({action:"rtc",uid:n,content:{pickup:this.user.user_id},token:this.session.accessToken.jwtToken})),{target:x[n],channels:$[n],hangup:()=>oe.bind(this)({cid:n}),media:this.__mediaStream}}}async function Ur(r){if(!this?.session?.accessToken?.jwtToken)throw new f("Access token is required.",{code:"INVALID_PARAMETER"});this.log("sendOffer",r);let e=await this.__socket,t=await x[r].createOffer();await x[r].setLocalDescription(t);let n=x[r].localDescription;this.log("rtcSdpOffer to",n),e.send(JSON.stringify({action:"rtc",uid:r,content:{sdpoffer:n},token:this.session.accessToken.jwtToken}));}async function Ju(r,e){if(!this?.session?.accessToken?.jwtToken)throw new f("Access token is required.",{code:"INVALID_PARAMETER"});this.log("sendIceCandidate to",e);let t=await this.__socket;if(!r.candidate){this.log("candidate-end","all ice candidates have been sent");return}let n=le[e]||(()=>{}),i=r.candidate;this.log("ice gathering state set to",x[e].iceGatheringState),n({type:"icecandidate",target:x[e],timestamp:new Date().toISOString(),candidate:r.candidate.candidate,sdpMid:r.candidate.sdpMid,sdpMLineIndex:r.candidate.sdpMLineIndex,usernameFragment:r.candidate.usernameFragment,protocol:r.candidate.protocol,gatheringState:x[e].iceGatheringState,connectionState:x[e].iceConnectionState}),t.send(JSON.stringify({action:"rtc",uid:e,content:{candidate:i},token:this.session.accessToken.jwtToken}));}function Ji(r,e){let t=new Set(e),n=le[r]||(o=>{}),i=x[r],s={ontrack:o=>{n({type:"track",target:i,timeStamp:o.timeStamp,streams:o.streams,track:o.track});},onicecandidate:o=>{Ju.bind(this)(o,r),o.candidate?n({type:"icecandidate",target:i,timestamp:new Date().toISOString(),candidate:o.candidate.candidate,sdpMid:o.candidate.sdpMid,sdpMLineIndex:o.candidate.sdpMLineIndex,usernameFragment:o.candidate.usernameFragment,protocol:o.candidate.protocol,gatheringState:i.iceGatheringState,connectionState:i.iceConnectionState}):n({type:"icecandidateend",target:i,timestamp:new Date().toISOString()});},onicecandidateerror:o=>{n({type:"icecandidateerror",target:i,timestamp:new Date().toISOString(),errorCode:o.errorCode,errorText:o.errorText,url:o.url,hostCandidate:o.hostCandidate,gatheringState:i.iceGatheringState,connectionState:i.iceConnectionState});},oniceconnectionstatechange:()=>{n({type:"iceconnectionstatechange",target:i,timestamp:new Date().toISOString(),state:i.iceConnectionState,gatheringState:i.iceGatheringState,signalingState:i.signalingState});},onicegatheringstatechange:()=>{n({type:"icegatheringstatechange",target:i,timestamp:new Date().toISOString(),state:i.iceGatheringState,connectionState:i.iceConnectionState,signalingState:i.signalingState});},onsignalingstatechange:()=>{n({type:"signalingstatechange",target:i,timestamp:new Date().toISOString(),state:i.signalingState,connectionState:i.iceConnectionState,gatheringState:i.iceGatheringState});},onnegotiationneeded:()=>{Ur.bind(this)(r),n({type:"negotiationneeded",target:i,timestamp:new Date().toISOString(),signalingState:i.signalingState,connectionState:i.iceConnectionState,gatheringState:i.iceGatheringState});},onconnectionstatechange:()=>{n({type:"connectionstatechange",target:i,timestamp:new Date().toISOString(),state:i.connectionState,iceState:i.iceConnectionState,signalingState:i.signalingState});let o=i.connectionState;(o==="disconnected"||o==="failed"||o==="closed")&&oe.bind(this)({cid:r});}};for(let[o,a]of Object.entries(s))t.has(o)||(i[o]=a);}function Gi(r,e,t){let n=new Set(t),i=le[r]||(o=>{}),s={onmessage:o=>{let a={type:o.type,target:e,timeStamp:o.timeStamp,data:o.data,lastEventId:o.lastEventId,origin:o.origin,readyState:e.readyState,bufferedAmount:e.bufferedAmount};this.log(`${e.label}: message`,o.data),i(a);},onerror:o=>{let a={type:o.type,target:e,timeStamp:o.timeStamp,error:o.error.message,errorCode:o.error.errorDetail,readyState:e.readyState,label:e.label};this.log(`${e.label}: error`,o.error.message),i(a);},onclose:o=>{let a={type:o.type,target:e,timeStamp:o.timeStamp,readyState:e.readyState,label:e.label,id:e.id};this.log(`${e.label}: closed`,null),i(a),$[r]&&(delete $[r][e.label],Object.keys($[r]).length===0&&oe.bind(this)({cid:r}));},onbufferedamountlow:o=>{let a={target:e,bufferedAmount:e.bufferedAmount,bufferedAmountLowThreshold:e.bufferedAmountLowThreshold,type:o.type,timeStamp:o.timeStamp};this.log(`${e.label}: bufferedamountlow`,e.bufferedAmount),i(a);},onopen:o=>{this.log("dataChannel",`data channel: "${e.label}" is open and ready to send messages.`);let a={type:o.type,target:e,timeStamp:o.timeStamp,readyState:e.readyState,label:e.label,id:e.id,ordered:e.ordered,maxRetransmits:e.maxRetransmits,protocol:e.protocol};i(a);}};for(let[o,a]of Object.entries(s))n.has(o)||(e[o]=a);}var Ee,Se=null,rt=true,We=0;async function Gu(){if(typeof window>"u"||window._runningInNodeJS)throw new f("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.getProfile(),!this.session)throw new f("No access.",{code:"INVALID_REQUEST"});let r=await this.record_endpoint;return new WebSocket(r.websocket_private+"?token="+this.session.accessToken.jwtToken)}var kr=null;async function Qi(){if(typeof window>"u"||window._runningInNodeJS)throw new f("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});rt=true;let r=this.__socket?await this.__socket:this.__socket;oe.bind(this)({close_all:true}),Ee&&Nr.bind(this)({group:null}),We=0,Se&&(Se.terminate(),Se=null);try{r&&r.close();}catch{}return window.removeEventListener("visibilitychange",kr),this.__socket=null,null}async function Vt(r,e=50,t){if(typeof window>"u"||window._runningInNodeJS)throw new f("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(typeof r!="function")throw new f("Callback must be a function.",{code:"INVALID_REQUEST"});if(t==="reconnect"){if(this.__socket instanceof Promise){let n=await this.__socket;if(n.readyState!==WebSocket.CLOSED&&n.readyState!==WebSocket.CLOSING)return this.__socket}}else if(rt&&(kr=()=>{!document.hidden&&!rt&&Vt.bind(this)(r,0,"reconnect");},this.__socket instanceof Promise))return this.__socket;Se&&(Se.terminate(),Se=null),this.__socket=new Promise(async n=>{await je.bind(this)(),setTimeout(async()=>{let i=await Gu.bind(this)();i.onopen=()=>{rt=false,We=0,t!=="reconnect"&&window.addEventListener("visibilitychange",kr),this.log("realtime onopen","Connected to WebSocket server."),r({type:"success",message:"Connected to WebSocket server."}),Ee&&i.send(JSON.stringify({action:"joinRoom",rid:Ee,token:this.session.accessToken.jwtToken}));let s=`
206
+ var Ds=Object.create;var De=Object.defineProperty;var Or=Object.getOwnPropertyDescriptor;var ks=Object.getOwnPropertyNames;var Ns=Object.getPrototypeOf,Fs=Object.prototype.hasOwnProperty;var Ls=(r,e,t)=>e in r?De(r,e,{enumerable:true,configurable:true,writable:true,value:t}):r[e]=t;var Mr=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')});var ke=(r,e)=>()=>(r&&(e=r(r=0)),e);var j=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),st=(r,e)=>{for(var t in e)De(r,t,{get:e[t],enumerable:true});},Vr=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of ks(e))!Fs.call(r,i)&&i!==t&&De(r,i,{get:()=>e[i],enumerable:!(n=Or(e,i))||n.enumerable});return r};var Te=(r,e,t)=>(t=r!=null?Ds(Ns(r)):{},Vr(!r||!r.__esModule?De(t,"default",{value:r,enumerable:true}):t,r)),re=r=>Vr(De({},"__esModule",{value:true}),r),S=(r,e,t,n)=>{for(var i=Or(e,t),s=r.length-1,o;s>=0;s--)(o=r[s])&&(i=(o(e,t,i))||i);return i&&De(e,t,i),i};var fe=(r,e,t)=>Ls(r,typeof e!="symbol"?e+"":e,t);var Re={};st(Re,{default:()=>Ms});var Os,Ms,Ie=ke(()=>{Os={},Ms=Os;});var $r=j(at=>{at.byteLength=Bs;at.toByteArray=js;at.fromByteArray=Ws;var ae=[],Y=[],qs=typeof Uint8Array<"u"?Uint8Array:Array,$t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(Pe=0,qr=$t.length;Pe<qr;++Pe)ae[Pe]=$t[Pe],Y[$t.charCodeAt(Pe)]=Pe;var Pe,qr;Y[45]=62;Y[95]=63;function Br(r){var e=r.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var t=r.indexOf("=");t===-1&&(t=e);var n=t===e?0:4-t%4;return [t,n]}function Bs(r){var e=Br(r),t=e[0],n=e[1];return (t+n)*3/4-n}function $s(r,e,t){return (e+t)*3/4-t}function js(r){var e,t=Br(r),n=t[0],i=t[1],s=new qs($s(r,n,i)),o=0,a=i>0?n-4:n,u;for(u=0;u<a;u+=4)e=Y[r.charCodeAt(u)]<<18|Y[r.charCodeAt(u+1)]<<12|Y[r.charCodeAt(u+2)]<<6|Y[r.charCodeAt(u+3)],s[o++]=e>>16&255,s[o++]=e>>8&255,s[o++]=e&255;return i===2&&(e=Y[r.charCodeAt(u)]<<2|Y[r.charCodeAt(u+1)]>>4,s[o++]=e&255),i===1&&(e=Y[r.charCodeAt(u)]<<10|Y[r.charCodeAt(u+1)]<<4|Y[r.charCodeAt(u+2)]>>2,s[o++]=e>>8&255,s[o++]=e&255),s}function Ks(r){return ae[r>>18&63]+ae[r>>12&63]+ae[r>>6&63]+ae[r&63]}function Hs(r,e,t){for(var n,i=[],s=e;s<t;s+=3)n=(r[s]<<16&16711680)+(r[s+1]<<8&65280)+(r[s+2]&255),i.push(Ks(n));return i.join("")}function Ws(r){for(var e,t=r.length,n=t%3,i=[],s=16383,o=0,a=t-n;o<a;o+=s)i.push(Hs(r,o,o+s>a?a:o+s));return n===1?(e=r[t-1],i.push(ae[e>>2]+ae[e<<4&63]+"==")):n===2&&(e=(r[t-2]<<8)+r[t-1],i.push(ae[e>>10]+ae[e>>4&63]+ae[e<<2&63]+"=")),i.join("")}});var jr=j(jt=>{jt.read=function(r,e,t,n,i){var s,o,a=i*8-n-1,u=(1<<a)-1,c=u>>1,d=-7,l=t?i-1:0,g=t?-1:1,p=r[e+l];for(l+=g,s=p&(1<<-d)-1,p>>=-d,d+=a;d>0;s=s*256+r[e+l],l+=g,d-=8);for(o=s&(1<<-d)-1,s>>=-d,d+=n;d>0;o=o*256+r[e+l],l+=g,d-=8);if(s===0)s=1-c;else {if(s===u)return o?NaN:(p?-1:1)*(1/0);o=o+Math.pow(2,n),s=s-c;}return (p?-1:1)*o*Math.pow(2,s-n)};jt.write=function(r,e,t,n,i,s){var o,a,u,c=s*8-i-1,d=(1<<c)-1,l=d>>1,g=i===23?Math.pow(2,-24)-Math.pow(2,-77):0,p=n?0:s-1,h=n?1:-1,b=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,o=d):(o=Math.floor(Math.log(e)/Math.LN2),e*(u=Math.pow(2,-o))<1&&(o--,u*=2),o+l>=1?e+=g/u:e+=g*Math.pow(2,1-l),e*u>=2&&(o++,u/=2),o+l>=d?(a=0,o=d):o+l>=1?(a=(e*u-1)*Math.pow(2,i),o=o+l):(a=e*Math.pow(2,l-1)*Math.pow(2,i),o=0));i>=8;r[t+p]=a&255,p+=h,a/=256,i-=8);for(o=o<<i|a,c+=i;c>0;r[t+p]=o&255,p+=h,o/=256,c-=8);r[t+p-h]|=b*128;};});var Hr=j((rc,Kr)=>{var Js={}.toString;Kr.exports=Array.isArray||function(r){return Js.call(r)=="[object Array]"};});var ht=j(Fe=>{var Kt=$r(),Ne=jr(),Gr=Hr();Fe.Buffer=y;Fe.SlowBuffer=Zs;Fe.INSPECT_MAX_BYTES=50;y.TYPED_ARRAY_SUPPORT=globalThis.TYPED_ARRAY_SUPPORT!==void 0?globalThis.TYPED_ARRAY_SUPPORT:Gs();Fe.kMaxLength=ut();function Gs(){try{var r=new Uint8Array(1);return r.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},r.foo()===42&&typeof r.subarray=="function"&&r.subarray(1,1).byteLength===0}catch{return false}}function ut(){return y.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function ge(r,e){if(ut()<e)throw new RangeError("Invalid typed array length");return y.TYPED_ARRAY_SUPPORT?(r=new Uint8Array(e),r.__proto__=y.prototype):(r===null&&(r=new y(e)),r.length=e),r}function y(r,e,t){if(!y.TYPED_ARRAY_SUPPORT&&!(this instanceof y))return new y(r,e,t);if(typeof r=="number"){if(typeof e=="string")throw new Error("If encoding is specified then the first argument must be a string");return Wt(this,r)}return Qr(this,r,e,t)}y.poolSize=8192;y._augment=function(r){return r.__proto__=y.prototype,r};function Qr(r,e,t,n){if(typeof e=="number")throw new TypeError('"value" argument must not be a number');return typeof ArrayBuffer<"u"&&e instanceof ArrayBuffer?Ys(r,e,t,n):typeof e=="string"?zs(r,e,t):Xs(r,e)}y.from=function(r,e,t){return Qr(null,r,e,t)};y.TYPED_ARRAY_SUPPORT&&(y.prototype.__proto__=Uint8Array.prototype,y.__proto__=Uint8Array,typeof Symbol<"u"&&Symbol.species&&y[Symbol.species]===y&&Object.defineProperty(y,Symbol.species,{value:null,configurable:true}));function zr(r){if(typeof r!="number")throw new TypeError('"size" argument must be a number');if(r<0)throw new RangeError('"size" argument must not be negative')}function Qs(r,e,t,n){return zr(e),e<=0?ge(r,e):t!==void 0?typeof n=="string"?ge(r,e).fill(t,n):ge(r,e).fill(t):ge(r,e)}y.alloc=function(r,e,t){return Qs(null,r,e,t)};function Wt(r,e){if(zr(e),r=ge(r,e<0?0:Jt(e)|0),!y.TYPED_ARRAY_SUPPORT)for(var t=0;t<e;++t)r[t]=0;return r}y.allocUnsafe=function(r){return Wt(null,r)};y.allocUnsafeSlow=function(r){return Wt(null,r)};function zs(r,e,t){if((typeof t!="string"||t==="")&&(t="utf8"),!y.isEncoding(t))throw new TypeError('"encoding" must be a valid string encoding');var n=Yr(e,t)|0;r=ge(r,n);var i=r.write(e,t);return i!==n&&(r=r.slice(0,i)),r}function Ht(r,e){var t=e.length<0?0:Jt(e.length)|0;r=ge(r,t);for(var n=0;n<t;n+=1)r[n]=e[n]&255;return r}function Ys(r,e,t,n){if(e.byteLength,t<0||e.byteLength<t)throw new RangeError("'offset' is out of bounds");if(e.byteLength<t+(n||0))throw new RangeError("'length' is out of bounds");return t===void 0&&n===void 0?e=new Uint8Array(e):n===void 0?e=new Uint8Array(e,t):e=new Uint8Array(e,t,n),y.TYPED_ARRAY_SUPPORT?(r=e,r.__proto__=y.prototype):r=Ht(r,e),r}function Xs(r,e){if(y.isBuffer(e)){var t=Jt(e.length)|0;return r=ge(r,t),r.length===0||e.copy(r,0,0,t),r}if(e){if(typeof ArrayBuffer<"u"&&e.buffer instanceof ArrayBuffer||"length"in e)return typeof e.length!="number"||yo(e.length)?ge(r,0):Ht(r,e);if(e.type==="Buffer"&&Gr(e.data))return Ht(r,e.data)}throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")}function Jt(r){if(r>=ut())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+ut().toString(16)+" bytes");return r|0}function Zs(r){return +r!=r&&(r=0),y.alloc(+r)}y.isBuffer=function(e){return !!(e!=null&&e._isBuffer)};y.compare=function(e,t){if(!y.isBuffer(e)||!y.isBuffer(t))throw new TypeError("Arguments must be Buffers");if(e===t)return 0;for(var n=e.length,i=t.length,s=0,o=Math.min(n,i);s<o;++s)if(e[s]!==t[s]){n=e[s],i=t[s];break}return n<i?-1:i<n?1:0};y.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 true;default:return false}};y.concat=function(e,t){if(!Gr(e))throw new TypeError('"list" argument must be an Array of Buffers');if(e.length===0)return y.alloc(0);var n;if(t===void 0)for(t=0,n=0;n<e.length;++n)t+=e[n].length;var i=y.allocUnsafe(t),s=0;for(n=0;n<e.length;++n){var o=e[n];if(!y.isBuffer(o))throw new TypeError('"list" argument must be an Array of Buffers');o.copy(i,s),s+=o.length;}return i};function Yr(r,e){if(y.isBuffer(r))return r.length;if(typeof ArrayBuffer<"u"&&typeof ArrayBuffer.isView=="function"&&(ArrayBuffer.isView(r)||r instanceof ArrayBuffer))return r.byteLength;typeof r!="string"&&(r=""+r);var t=r.length;if(t===0)return 0;for(var n=false;;)switch(e){case "ascii":case "latin1":case "binary":return t;case "utf8":case "utf-8":case void 0:return ct(r).length;case "ucs2":case "ucs-2":case "utf16le":case "utf-16le":return t*2;case "hex":return t>>>1;case "base64":return sn(r).length;default:if(n)return ct(r).length;e=(""+e).toLowerCase(),n=true;}}y.byteLength=Yr;function eo(r,e,t){var n=false;if((e===void 0||e<0)&&(e=0),e>this.length||((t===void 0||t>this.length)&&(t=this.length),t<=0)||(t>>>=0,e>>>=0,t<=e))return "";for(r||(r="utf8");;)switch(r){case "hex":return lo(this,e,t);case "utf8":case "utf-8":return en(this,e,t);case "ascii":return uo(this,e,t);case "latin1":case "binary":return co(this,e,t);case "base64":return oo(this,e,t);case "ucs2":case "ucs-2":case "utf16le":case "utf-16le":return fo(this,e,t);default:if(n)throw new TypeError("Unknown encoding: "+r);r=(r+"").toLowerCase(),n=true;}}y.prototype._isBuffer=true;function xe(r,e,t){var n=r[e];r[e]=r[t],r[t]=n;}y.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)xe(this,t,t+1);return this};y.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)xe(this,t,t+3),xe(this,t+1,t+2);return this};y.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)xe(this,t,t+7),xe(this,t+1,t+6),xe(this,t+2,t+5),xe(this,t+3,t+4);return this};y.prototype.toString=function(){var e=this.length|0;return e===0?"":arguments.length===0?en(this,0,e):eo.apply(this,arguments)};y.prototype.equals=function(e){if(!y.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e?true:y.compare(this,e)===0};y.prototype.inspect=function(){var e="",t=Fe.INSPECT_MAX_BYTES;return this.length>0&&(e=this.toString("hex",0,t).match(/.{2}/g).join(" "),this.length>t&&(e+=" ... ")),"<Buffer "+e+">"};y.prototype.compare=function(e,t,n,i,s){if(!y.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(t===void 0&&(t=0),n===void 0&&(n=e?e.length:0),i===void 0&&(i=0),s===void 0&&(s=this.length),t<0||n>e.length||i<0||s>this.length)throw new RangeError("out of range index");if(i>=s&&t>=n)return 0;if(i>=s)return -1;if(t>=n)return 1;if(t>>>=0,n>>>=0,i>>>=0,s>>>=0,this===e)return 0;for(var o=s-i,a=n-t,u=Math.min(o,a),c=this.slice(i,s),d=e.slice(t,n),l=0;l<u;++l)if(c[l]!==d[l]){o=c[l],a=d[l];break}return o<a?-1:a<o?1:0};function Xr(r,e,t,n,i){if(r.length===0)return -1;if(typeof t=="string"?(n=t,t=0):t>2147483647?t=2147483647:t<-2147483648&&(t=-2147483648),t=+t,isNaN(t)&&(t=i?0:r.length-1),t<0&&(t=r.length+t),t>=r.length){if(i)return -1;t=r.length-1;}else if(t<0)if(i)t=0;else return -1;if(typeof e=="string"&&(e=y.from(e,n)),y.isBuffer(e))return e.length===0?-1:Wr(r,e,t,n,i);if(typeof e=="number")return e=e&255,y.TYPED_ARRAY_SUPPORT&&typeof Uint8Array.prototype.indexOf=="function"?i?Uint8Array.prototype.indexOf.call(r,e,t):Uint8Array.prototype.lastIndexOf.call(r,e,t):Wr(r,[e],t,n,i);throw new TypeError("val must be string, number or Buffer")}function Wr(r,e,t,n,i){var s=1,o=r.length,a=e.length;if(n!==void 0&&(n=String(n).toLowerCase(),n==="ucs2"||n==="ucs-2"||n==="utf16le"||n==="utf-16le")){if(r.length<2||e.length<2)return -1;s=2,o/=2,a/=2,t/=2;}function u(p,h){return s===1?p[h]:p.readUInt16BE(h*s)}var c;if(i){var d=-1;for(c=t;c<o;c++)if(u(r,c)===u(e,d===-1?0:c-d)){if(d===-1&&(d=c),c-d+1===a)return d*s}else d!==-1&&(c-=c-d),d=-1;}else for(t+a>o&&(t=o-a),c=t;c>=0;c--){for(var l=true,g=0;g<a;g++)if(u(r,c+g)!==u(e,g)){l=false;break}if(l)return c}return -1}y.prototype.includes=function(e,t,n){return this.indexOf(e,t,n)!==-1};y.prototype.indexOf=function(e,t,n){return Xr(this,e,t,n,true)};y.prototype.lastIndexOf=function(e,t,n){return Xr(this,e,t,n,false)};function to(r,e,t,n){t=Number(t)||0;var i=r.length-t;n?(n=Number(n),n>i&&(n=i)):n=i;var s=e.length;if(s%2!==0)throw new TypeError("Invalid hex string");n>s/2&&(n=s/2);for(var o=0;o<n;++o){var a=parseInt(e.substr(o*2,2),16);if(isNaN(a))return o;r[t+o]=a;}return o}function ro(r,e,t,n){return ft(ct(e,r.length-t),r,t,n)}function Zr(r,e,t,n){return ft(_o(e),r,t,n)}function no(r,e,t,n){return Zr(r,e,t,n)}function io(r,e,t,n){return ft(sn(e),r,t,n)}function so(r,e,t,n){return ft(bo(e,r.length-t),r,t,n)}y.prototype.write=function(e,t,n,i){if(t===void 0)i="utf8",n=this.length,t=0;else if(n===void 0&&typeof t=="string")i=t,n=this.length,t=0;else if(isFinite(t))t=t|0,isFinite(n)?(n=n|0,i===void 0&&(i="utf8")):(i=n,n=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");var s=this.length-t;if((n===void 0||n>s)&&(n=s),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");i||(i="utf8");for(var o=false;;)switch(i){case "hex":return to(this,e,t,n);case "utf8":case "utf-8":return ro(this,e,t,n);case "ascii":return Zr(this,e,t,n);case "latin1":case "binary":return no(this,e,t,n);case "base64":return io(this,e,t,n);case "ucs2":case "ucs-2":case "utf16le":case "utf-16le":return so(this,e,t,n);default:if(o)throw new TypeError("Unknown encoding: "+i);i=(""+i).toLowerCase(),o=true;}};y.prototype.toJSON=function(){return {type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function oo(r,e,t){return e===0&&t===r.length?Kt.fromByteArray(r):Kt.fromByteArray(r.slice(e,t))}function en(r,e,t){t=Math.min(r.length,t);for(var n=[],i=e;i<t;){var s=r[i],o=null,a=s>239?4:s>223?3:s>191?2:1;if(i+a<=t){var u,c,d,l;switch(a){case 1:s<128&&(o=s);break;case 2:u=r[i+1],(u&192)===128&&(l=(s&31)<<6|u&63,l>127&&(o=l));break;case 3:u=r[i+1],c=r[i+2],(u&192)===128&&(c&192)===128&&(l=(s&15)<<12|(u&63)<<6|c&63,l>2047&&(l<55296||l>57343)&&(o=l));break;case 4:u=r[i+1],c=r[i+2],d=r[i+3],(u&192)===128&&(c&192)===128&&(d&192)===128&&(l=(s&15)<<18|(u&63)<<12|(c&63)<<6|d&63,l>65535&&l<1114112&&(o=l));}}o===null?(o=65533,a=1):o>65535&&(o-=65536,n.push(o>>>10&1023|55296),o=56320|o&1023),n.push(o),i+=a;}return ao(n)}var Jr=4096;function ao(r){var e=r.length;if(e<=Jr)return String.fromCharCode.apply(String,r);for(var t="",n=0;n<e;)t+=String.fromCharCode.apply(String,r.slice(n,n+=Jr));return t}function uo(r,e,t){var n="";t=Math.min(r.length,t);for(var i=e;i<t;++i)n+=String.fromCharCode(r[i]&127);return n}function co(r,e,t){var n="";t=Math.min(r.length,t);for(var i=e;i<t;++i)n+=String.fromCharCode(r[i]);return n}function lo(r,e,t){var n=r.length;(!e||e<0)&&(e=0),(!t||t<0||t>n)&&(t=n);for(var i="",s=e;s<t;++s)i+=mo(r[s]);return i}function fo(r,e,t){for(var n=r.slice(e,t),i="",s=0;s<n.length;s+=2)i+=String.fromCharCode(n[s]+n[s+1]*256);return i}y.prototype.slice=function(e,t){var n=this.length;e=~~e,t=t===void 0?n:~~t,e<0?(e+=n,e<0&&(e=0)):e>n&&(e=n),t<0?(t+=n,t<0&&(t=0)):t>n&&(t=n),t<e&&(t=e);var i;if(y.TYPED_ARRAY_SUPPORT)i=this.subarray(e,t),i.__proto__=y.prototype;else {var s=t-e;i=new y(s,void 0);for(var o=0;o<s;++o)i[o]=this[o+e];}return i};function q(r,e,t){if(r%1!==0||r<0)throw new RangeError("offset is not uint");if(r+e>t)throw new RangeError("Trying to access beyond buffer length")}y.prototype.readUIntLE=function(e,t,n){e=e|0,t=t|0,n||q(e,t,this.length);for(var i=this[e],s=1,o=0;++o<t&&(s*=256);)i+=this[e+o]*s;return i};y.prototype.readUIntBE=function(e,t,n){e=e|0,t=t|0,n||q(e,t,this.length);for(var i=this[e+--t],s=1;t>0&&(s*=256);)i+=this[e+--t]*s;return i};y.prototype.readUInt8=function(e,t){return t||q(e,1,this.length),this[e]};y.prototype.readUInt16LE=function(e,t){return t||q(e,2,this.length),this[e]|this[e+1]<<8};y.prototype.readUInt16BE=function(e,t){return t||q(e,2,this.length),this[e]<<8|this[e+1]};y.prototype.readUInt32LE=function(e,t){return t||q(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+this[e+3]*16777216};y.prototype.readUInt32BE=function(e,t){return t||q(e,4,this.length),this[e]*16777216+(this[e+1]<<16|this[e+2]<<8|this[e+3])};y.prototype.readIntLE=function(e,t,n){e=e|0,t=t|0,n||q(e,t,this.length);for(var i=this[e],s=1,o=0;++o<t&&(s*=256);)i+=this[e+o]*s;return s*=128,i>=s&&(i-=Math.pow(2,8*t)),i};y.prototype.readIntBE=function(e,t,n){e=e|0,t=t|0,n||q(e,t,this.length);for(var i=t,s=1,o=this[e+--i];i>0&&(s*=256);)o+=this[e+--i]*s;return s*=128,o>=s&&(o-=Math.pow(2,8*t)),o};y.prototype.readInt8=function(e,t){return t||q(e,1,this.length),this[e]&128?(255-this[e]+1)*-1:this[e]};y.prototype.readInt16LE=function(e,t){t||q(e,2,this.length);var n=this[e]|this[e+1]<<8;return n&32768?n|4294901760:n};y.prototype.readInt16BE=function(e,t){t||q(e,2,this.length);var n=this[e+1]|this[e]<<8;return n&32768?n|4294901760:n};y.prototype.readInt32LE=function(e,t){return t||q(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24};y.prototype.readInt32BE=function(e,t){return t||q(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]};y.prototype.readFloatLE=function(e,t){return t||q(e,4,this.length),Ne.read(this,e,true,23,4)};y.prototype.readFloatBE=function(e,t){return t||q(e,4,this.length),Ne.read(this,e,false,23,4)};y.prototype.readDoubleLE=function(e,t){return t||q(e,8,this.length),Ne.read(this,e,true,52,8)};y.prototype.readDoubleBE=function(e,t){return t||q(e,8,this.length),Ne.read(this,e,false,52,8)};function G(r,e,t,n,i,s){if(!y.isBuffer(r))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>i||e<s)throw new RangeError('"value" argument is out of bounds');if(t+n>r.length)throw new RangeError("Index out of range")}y.prototype.writeUIntLE=function(e,t,n,i){if(e=+e,t=t|0,n=n|0,!i){var s=Math.pow(2,8*n)-1;G(this,e,t,n,s,0);}var o=1,a=0;for(this[t]=e&255;++a<n&&(o*=256);)this[t+a]=e/o&255;return t+n};y.prototype.writeUIntBE=function(e,t,n,i){if(e=+e,t=t|0,n=n|0,!i){var s=Math.pow(2,8*n)-1;G(this,e,t,n,s,0);}var o=n-1,a=1;for(this[t+o]=e&255;--o>=0&&(a*=256);)this[t+o]=e/a&255;return t+n};y.prototype.writeUInt8=function(e,t,n){return e=+e,t=t|0,n||G(this,e,t,1,255,0),y.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=e&255,t+1};function lt(r,e,t,n){e<0&&(e=65535+e+1);for(var i=0,s=Math.min(r.length-t,2);i<s;++i)r[t+i]=(e&255<<8*(n?i:1-i))>>>(n?i:1-i)*8;}y.prototype.writeUInt16LE=function(e,t,n){return e=+e,t=t|0,n||G(this,e,t,2,65535,0),y.TYPED_ARRAY_SUPPORT?(this[t]=e&255,this[t+1]=e>>>8):lt(this,e,t,true),t+2};y.prototype.writeUInt16BE=function(e,t,n){return e=+e,t=t|0,n||G(this,e,t,2,65535,0),y.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=e&255):lt(this,e,t,false),t+2};function dt(r,e,t,n){e<0&&(e=4294967295+e+1);for(var i=0,s=Math.min(r.length-t,4);i<s;++i)r[t+i]=e>>>(n?i:3-i)*8&255;}y.prototype.writeUInt32LE=function(e,t,n){return e=+e,t=t|0,n||G(this,e,t,4,4294967295,0),y.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=e&255):dt(this,e,t,true),t+4};y.prototype.writeUInt32BE=function(e,t,n){return e=+e,t=t|0,n||G(this,e,t,4,4294967295,0),y.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=e&255):dt(this,e,t,false),t+4};y.prototype.writeIntLE=function(e,t,n,i){if(e=+e,t=t|0,!i){var s=Math.pow(2,8*n-1);G(this,e,t,n,s-1,-s);}var o=0,a=1,u=0;for(this[t]=e&255;++o<n&&(a*=256);)e<0&&u===0&&this[t+o-1]!==0&&(u=1),this[t+o]=(e/a>>0)-u&255;return t+n};y.prototype.writeIntBE=function(e,t,n,i){if(e=+e,t=t|0,!i){var s=Math.pow(2,8*n-1);G(this,e,t,n,s-1,-s);}var o=n-1,a=1,u=0;for(this[t+o]=e&255;--o>=0&&(a*=256);)e<0&&u===0&&this[t+o+1]!==0&&(u=1),this[t+o]=(e/a>>0)-u&255;return t+n};y.prototype.writeInt8=function(e,t,n){return e=+e,t=t|0,n||G(this,e,t,1,127,-128),y.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=e&255,t+1};y.prototype.writeInt16LE=function(e,t,n){return e=+e,t=t|0,n||G(this,e,t,2,32767,-32768),y.TYPED_ARRAY_SUPPORT?(this[t]=e&255,this[t+1]=e>>>8):lt(this,e,t,true),t+2};y.prototype.writeInt16BE=function(e,t,n){return e=+e,t=t|0,n||G(this,e,t,2,32767,-32768),y.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=e&255):lt(this,e,t,false),t+2};y.prototype.writeInt32LE=function(e,t,n){return e=+e,t=t|0,n||G(this,e,t,4,2147483647,-2147483648),y.TYPED_ARRAY_SUPPORT?(this[t]=e&255,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):dt(this,e,t,true),t+4};y.prototype.writeInt32BE=function(e,t,n){return e=+e,t=t|0,n||G(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),y.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=e&255):dt(this,e,t,false),t+4};function tn(r,e,t,n,i,s){if(t+n>r.length)throw new RangeError("Index out of range");if(t<0)throw new RangeError("Index out of range")}function rn(r,e,t,n,i){return i||tn(r,e,t,4),Ne.write(r,e,t,n,23,4),t+4}y.prototype.writeFloatLE=function(e,t,n){return rn(this,e,t,true,n)};y.prototype.writeFloatBE=function(e,t,n){return rn(this,e,t,false,n)};function nn(r,e,t,n,i){return i||tn(r,e,t,8),Ne.write(r,e,t,n,52,8),t+8}y.prototype.writeDoubleLE=function(e,t,n){return nn(this,e,t,true,n)};y.prototype.writeDoubleBE=function(e,t,n){return nn(this,e,t,false,n)};y.prototype.copy=function(e,t,n,i){if(n||(n=0),!i&&i!==0&&(i=this.length),t>=e.length&&(t=e.length),t||(t=0),i>0&&i<n&&(i=n),i===n||e.length===0||this.length===0)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(i<0)throw new RangeError("sourceEnd out of bounds");i>this.length&&(i=this.length),e.length-t<i-n&&(i=e.length-t+n);var s=i-n,o;if(this===e&&n<t&&t<i)for(o=s-1;o>=0;--o)e[o+t]=this[o+n];else if(s<1e3||!y.TYPED_ARRAY_SUPPORT)for(o=0;o<s;++o)e[o+t]=this[o+n];else Uint8Array.prototype.set.call(e,this.subarray(n,n+s),t);return s};y.prototype.fill=function(e,t,n,i){if(typeof e=="string"){if(typeof t=="string"?(i=t,t=0,n=this.length):typeof n=="string"&&(i=n,n=this.length),e.length===1){var s=e.charCodeAt(0);s<256&&(e=s);}if(i!==void 0&&typeof i!="string")throw new TypeError("encoding must be a string");if(typeof i=="string"&&!y.isEncoding(i))throw new TypeError("Unknown encoding: "+i)}else typeof e=="number"&&(e=e&255);if(t<0||this.length<t||this.length<n)throw new RangeError("Out of range index");if(n<=t)return this;t=t>>>0,n=n===void 0?this.length:n>>>0,e||(e=0);var o;if(typeof e=="number")for(o=t;o<n;++o)this[o]=e;else {var a=y.isBuffer(e)?e:ct(new y(e,i).toString()),u=a.length;for(o=0;o<n-t;++o)this[o+t]=a[o%u];}return this};var ho=/[^+\/0-9A-Za-z-_]/g;function go(r){if(r=po(r).replace(ho,""),r.length<2)return "";for(;r.length%4!==0;)r=r+"=";return r}function po(r){return r.trim?r.trim():r.replace(/^\s+|\s+$/g,"")}function mo(r){return r<16?"0"+r.toString(16):r.toString(16)}function ct(r,e){e=e||1/0;for(var t,n=r.length,i=null,s=[],o=0;o<n;++o){if(t=r.charCodeAt(o),t>55295&&t<57344){if(!i){if(t>56319){(e-=3)>-1&&s.push(239,191,189);continue}else if(o+1===n){(e-=3)>-1&&s.push(239,191,189);continue}i=t;continue}if(t<56320){(e-=3)>-1&&s.push(239,191,189),i=t;continue}t=(i-55296<<10|t-56320)+65536;}else i&&(e-=3)>-1&&s.push(239,191,189);if(i=null,t<128){if((e-=1)<0)break;s.push(t);}else if(t<2048){if((e-=2)<0)break;s.push(t>>6|192,t&63|128);}else if(t<65536){if((e-=3)<0)break;s.push(t>>12|224,t>>6&63|128,t&63|128);}else if(t<1114112){if((e-=4)<0)break;s.push(t>>18|240,t>>12&63|128,t>>6&63|128,t&63|128);}else throw new Error("Invalid code point")}return s}function _o(r){for(var e=[],t=0;t<r.length;++t)e.push(r.charCodeAt(t)&255);return e}function bo(r,e){for(var t,n,i,s=[],o=0;o<r.length&&!((e-=2)<0);++o)t=r.charCodeAt(o),n=t>>8,i=t%256,s.push(i),s.push(n);return s}function sn(r){return Kt.toByteArray(go(r))}function ft(r,e,t,n){for(var i=0;i<n&&!(i+t>=e.length||i>=r.length);++i)e[i+t]=r[i];return i}function yo(r){return r!==r}});var on=j(()=>{});var Zt={};st(Zt,{__assign:()=>Yt,__asyncDelegator:()=>ko,__asyncGenerator:()=>Do,__asyncValues:()=>No,__await:()=>Je,__awaiter:()=>Ro,__classPrivateFieldGet:()=>Mo,__classPrivateFieldSet:()=>Vo,__createBinding:()=>Po,__decorate:()=>So,__exportStar:()=>xo,__extends:()=>Ao,__generator:()=>Io,__importDefault:()=>Oo,__importStar:()=>Lo,__makeTemplateObject:()=>Fo,__metadata:()=>To,__param:()=>vo,__read:()=>an,__rest:()=>Eo,__spread:()=>Uo,__spreadArrays:()=>Co,__values:()=>Xt});function Ao(r,e){zt(r,e);function t(){this.constructor=r;}r.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t);}function Eo(r,e){var t={};for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&e.indexOf(n)<0&&(t[n]=r[n]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(r);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(r,n[i])&&(t[n[i]]=r[n[i]]);return t}function So(r,e,t,n){var i=arguments.length,s=i<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(r,e,t,n);else for(var a=r.length-1;a>=0;a--)(o=r[a])&&(s=(i<3?o(s):i>3?o(e,t,s):o(e,t))||s);return i>3&&s&&Object.defineProperty(e,t,s),s}function vo(r,e){return function(t,n){e(t,n,r);}}function To(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)}function Ro(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s);})}return new(t||(t=Promise))(function(s,o){function a(d){try{c(n.next(d));}catch(l){o(l);}}function u(d){try{c(n.throw(d));}catch(l){o(l);}}function c(d){d.done?s(d.value):i(d.value).then(a,u);}c((n=n.apply(r,e||[])).next());})}function Io(r,e){var t={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},n,i,s,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(c){return function(d){return u([c,d])}}function u(c){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,i&&(s=c[0]&2?i.return:c[0]?i.throw||((s=i.return)&&s.call(i),0):i.next)&&!(s=s.call(i,c[1])).done)return s;switch(i=0,s&&(c=[c[0]&2,s.value]),c[0]){case 0:case 1:s=c;break;case 4:return t.label++,{value:c[1],done:!1};case 5:t.label++,i=c[1],c=[0];continue;case 7:c=t.ops.pop(),t.trys.pop();continue;default:if(s=t.trys,!(s=s.length>0&&s[s.length-1])&&(c[0]===6||c[0]===2)){t=0;continue}if(c[0]===3&&(!s||c[1]>s[0]&&c[1]<s[3])){t.label=c[1];break}if(c[0]===6&&t.label<s[1]){t.label=s[1],s=c;break}if(s&&t.label<s[2]){t.label=s[2],t.ops.push(c);break}s[2]&&t.ops.pop(),t.trys.pop();continue}c=e.call(r,t);}catch(d){c=[6,d],i=0;}finally{n=s=0;}if(c[0]&5)throw c[1];return {value:c[0]?c[1]:void 0,done:true}}}function Po(r,e,t,n){n===void 0&&(n=t),r[n]=e[t];}function xo(r,e){for(var t in r)t!=="default"&&!e.hasOwnProperty(t)&&(e[t]=r[t]);}function Xt(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],n=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return {next:function(){return r&&n>=r.length&&(r=void 0),{value:r&&r[n++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function an(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),i,s=[],o;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)s.push(i.value);}catch(a){o={error:a};}finally{try{i&&!i.done&&(t=n.return)&&t.call(n);}finally{if(o)throw o.error}}return s}function Uo(){for(var r=[],e=0;e<arguments.length;e++)r=r.concat(an(arguments[e]));return r}function Co(){for(var r=0,e=0,t=arguments.length;e<t;e++)r+=arguments[e].length;for(var n=Array(r),i=0,e=0;e<t;e++)for(var s=arguments[e],o=0,a=s.length;o<a;o++,i++)n[i]=s[o];return n}function Je(r){return this instanceof Je?(this.v=r,this):new Je(r)}function Do(r,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=t.apply(r,e||[]),i,s=[];return i={},o("next"),o("throw"),o("return"),i[Symbol.asyncIterator]=function(){return this},i;function o(g){n[g]&&(i[g]=function(p){return new Promise(function(h,b){s.push([g,p,h,b])>1||a(g,p);})});}function a(g,p){try{u(n[g](p));}catch(h){l(s[0][3],h);}}function u(g){g.value instanceof Je?Promise.resolve(g.value.v).then(c,d):l(s[0][2],g);}function c(g){a("next",g);}function d(g){a("throw",g);}function l(g,p){g(p),s.shift(),s.length&&a(s[0][0],s[0][1]);}}function ko(r){var e,t;return e={},n("next"),n("throw",function(i){throw i}),n("return"),e[Symbol.iterator]=function(){return this},e;function n(i,s){e[i]=r[i]?function(o){return (t=!t)?{value:Je(r[i](o)),done:i==="return"}:s?s(o):o}:s;}}function No(r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=r[Symbol.asyncIterator],t;return e?e.call(r):(r=typeof Xt=="function"?Xt(r):r[Symbol.iterator](),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(s){t[s]=r[s]&&function(o){return new Promise(function(a,u){o=r[s](o),i(a,u,o.done,o.value);})};}function i(s,o,a,u){Promise.resolve(u).then(function(c){s({value:c,done:a});},o);}}function Fo(r,e){return Object.defineProperty?Object.defineProperty(r,"raw",{value:e}):r.raw=e,r}function Lo(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)Object.hasOwnProperty.call(r,t)&&(e[t]=r[t]);return e.default=r,e}function Oo(r){return r&&r.__esModule?r:{default:r}}function Mo(r,e){if(!e.has(r))throw new TypeError("attempted to get private field on non-instance");return e.get(r)}function Vo(r,e,t){if(!e.has(r))throw new TypeError("attempted to set private field on non-instance");return e.set(r,t),t}var zt,Yt,er=ke(()=>{zt=function(r,e){return zt=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,n){t.__proto__=n;}||function(t,n){for(var i in n)n.hasOwnProperty(i)&&(t[i]=n[i]);},zt(r,e)};Yt=function(){return Yt=Object.assign||function(e){for(var t,n=1,i=arguments.length;n<i;n++){t=arguments[n];for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&(e[s]=t[s]);}return e},Yt.apply(this,arguments)};});var tr=j(Z=>{Object.defineProperty(Z,"__esModule",{value:true});Z.MAX_HASHABLE_LENGTH=Z.INIT=Z.KEY=Z.DIGEST_LENGTH=Z.BLOCK_SIZE=void 0;Z.BLOCK_SIZE=64;Z.DIGEST_LENGTH=32;Z.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]);Z.INIT=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225];Z.MAX_HASHABLE_LENGTH=Math.pow(2,53)-1;});var un=j(gt=>{Object.defineProperty(gt,"__esModule",{value:true});gt.RawSha256=void 0;var ee=tr(),qo=(function(){function r(){this.state=Int32Array.from(ee.INIT),this.temp=new Int32Array(64),this.buffer=new Uint8Array(64),this.bufferLength=0,this.bytesHashed=0,this.finished=false;}return r.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,this.bytesHashed*8>ee.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===ee.BLOCK_SIZE&&(this.hashBuffer(),this.bufferLength=0);},r.prototype.digest=function(){if(!this.finished){var e=this.bytesHashed*8,t=new DataView(this.buffer.buffer,this.buffer.byteOffset,this.buffer.byteLength),n=this.bufferLength;if(t.setUint8(this.bufferLength++,128),n%ee.BLOCK_SIZE>=ee.BLOCK_SIZE-8){for(var i=this.bufferLength;i<ee.BLOCK_SIZE;i++)t.setUint8(i,0);this.hashBuffer(),this.bufferLength=0;}for(var i=this.bufferLength;i<ee.BLOCK_SIZE-8;i++)t.setUint8(i,0);t.setUint32(ee.BLOCK_SIZE-8,Math.floor(e/4294967296),true),t.setUint32(ee.BLOCK_SIZE-4,e),this.hashBuffer(),this.finished=true;}for(var s=new Uint8Array(ee.DIGEST_LENGTH),i=0;i<8;i++)s[i*4]=this.state[i]>>>24&255,s[i*4+1]=this.state[i]>>>16&255,s[i*4+2]=this.state[i]>>>8&255,s[i*4+3]=this.state[i]>>>0&255;return s},r.prototype.hashBuffer=function(){for(var e=this,t=e.buffer,n=e.state,i=n[0],s=n[1],o=n[2],a=n[3],u=n[4],c=n[5],d=n[6],l=n[7],g=0;g<ee.BLOCK_SIZE;g++){if(g<16)this.temp[g]=(t[g*4]&255)<<24|(t[g*4+1]&255)<<16|(t[g*4+2]&255)<<8|t[g*4+3]&255;else {var p=this.temp[g-2],h=(p>>>17|p<<15)^(p>>>19|p<<13)^p>>>10;p=this.temp[g-15];var b=(p>>>7|p<<25)^(p>>>18|p<<14)^p>>>3;this.temp[g]=(h+this.temp[g-7]|0)+(b+this.temp[g-16]|0);}var w=(((u>>>6|u<<26)^(u>>>11|u<<21)^(u>>>25|u<<7))+(u&c^~u&d)|0)+(l+(ee.KEY[g]+this.temp[g]|0)|0)|0,_=((i>>>2|i<<30)^(i>>>13|i<<19)^(i>>>22|i<<10))+(i&s^i&o^s&o)|0;l=d,d=c,c=u,u=a+w|0,a=o,o=s,s=i,i=w+_|0;}n[0]+=i,n[1]+=s,n[2]+=o,n[3]+=a,n[4]+=u,n[5]+=c,n[6]+=d,n[7]+=l;},r})();gt.RawSha256=qo;});var cn,ln,dn=ke(()=>{cn=r=>{let e=[];for(let t=0,n=r.length;t<n;t++){let i=r.charCodeAt(t);if(i<128)e.push(i);else if(i<2048)e.push(i>>6|192,i&63|128);else if(t+1<r.length&&(i&64512)===55296&&(r.charCodeAt(t+1)&64512)===56320){let s=65536+((i&1023)<<10)+(r.charCodeAt(++t)&1023);e.push(s>>18|240,s>>12&63|128,s>>6&63|128,s&63|128);}else e.push(i>>12|224,i>>6&63|128,i&63|128);}return Uint8Array.from(e)},ln=r=>{let e="";for(let t=0,n=r.length;t<n;t++){let i=r[t];if(i<128)e+=String.fromCharCode(i);else if(192<=i&&i<224){let s=r[++t];e+=String.fromCharCode((i&31)<<6|s&63);}else if(240<=i&&i<365){let o="%"+[i,r[++t],r[++t],r[++t]].map(a=>a.toString(16)).join("%");e+=decodeURIComponent(o);}else e+=String.fromCharCode((i&15)<<12|(r[++t]&63)<<6|r[++t]&63);}return e};});function fn(r){return new TextEncoder().encode(r)}function hn(r){return new TextDecoder("utf-8").decode(r)}var gn=ke(()=>{});var pn={};st(pn,{fromUtf8:()=>Bo,toUtf8:()=>$o});var Bo,$o,mn=ke(()=>{dn();gn();Bo=r=>typeof TextEncoder=="function"?fn(r):cn(r),$o=r=>typeof TextDecoder=="function"?hn(r):ln(r);});var _n=j(pt=>{Object.defineProperty(pt,"__esModule",{value:true});pt.convertToBuffer=void 0;var jo=(mn(),re(pn)),Ko=typeof Buffer<"u"&&Buffer.from?function(r){return Buffer.from(r,"utf8")}:jo.fromUtf8;function Ho(r){return r instanceof Uint8Array?r:typeof r=="string"?Ko(r):ArrayBuffer.isView(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(r)}pt.convertToBuffer=Ho;});var bn=j(mt=>{Object.defineProperty(mt,"__esModule",{value:true});mt.isEmptyData=void 0;function Wo(r){return typeof r=="string"?r.length===0:r.byteLength===0}mt.isEmptyData=Wo;});var yn=j(_t=>{Object.defineProperty(_t,"__esModule",{value:true});_t.numToUint8=void 0;function Jo(r){return new Uint8Array([(r&4278190080)>>24,(r&16711680)>>16,(r&65280)>>8,r&255])}_t.numToUint8=Jo;});var wn=j(bt=>{Object.defineProperty(bt,"__esModule",{value:true});bt.uint32ArrayFrom=void 0;function Go(r){if(!Array.from){for(var e=new Uint32Array(r.length),t=0;t<r.length;)e[t]=r[t];return e}return Uint32Array.from(r)}bt.uint32ArrayFrom=Go;});var An=j(ue=>{Object.defineProperty(ue,"__esModule",{value:true});ue.uint32ArrayFrom=ue.numToUint8=ue.isEmptyData=ue.convertToBuffer=void 0;var Qo=_n();Object.defineProperty(ue,"convertToBuffer",{enumerable:true,get:function(){return Qo.convertToBuffer}});var zo=bn();Object.defineProperty(ue,"isEmptyData",{enumerable:true,get:function(){return zo.isEmptyData}});var Yo=yn();Object.defineProperty(ue,"numToUint8",{enumerable:true,get:function(){return Yo.numToUint8}});var Xo=wn();Object.defineProperty(ue,"uint32ArrayFrom",{enumerable:true,get:function(){return Xo.uint32ArrayFrom}});});var Sn=j(wt=>{Object.defineProperty(wt,"__esModule",{value:true});wt.Sha256=void 0;var En=(er(),re(Zt)),yt=tr(),rr=un(),nr=An(),Zo=(function(){function r(e){if(this.hash=new rr.RawSha256,e){this.outer=new rr.RawSha256;var t=ea(e),n=new Uint8Array(yt.BLOCK_SIZE);n.set(t);for(var i=0;i<yt.BLOCK_SIZE;i++)t[i]^=54,n[i]^=92;this.hash.update(t),this.outer.update(n);for(var i=0;i<t.byteLength;i++)t[i]=0;}}return r.prototype.update=function(e){if(!((0, nr.isEmptyData)(e)||this.error))try{this.hash.update((0,nr.convertToBuffer)(e));}catch(t){this.error=t;}},r.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()},r.prototype.digest=function(){return (0, En.__awaiter)(this,void 0,void 0,function(){return (0, En.__generator)(this,function(e){return [2,this.digestSync()]})})},r})();wt.Sha256=Zo;function ea(r){var e=(0, nr.convertToBuffer)(r);if(e.byteLength>yt.BLOCK_SIZE){var t=new rr.RawSha256;t.update(e),e=t.digest();}var n=new Uint8Array(yt.BLOCK_SIZE);return n.set(e),n}});var sr=j(ir=>{Object.defineProperty(ir,"__esModule",{value:true});var ta=(er(),re(Zt));(0, ta.__exportStar)(Sn(),ir);});var gr={};st(gr,{default:()=>Qa});function Qa(r,e){return e=e||{},new Promise(function(t,n){var i=new XMLHttpRequest,s=[],o=[],a={},u=function(){return {ok:(i.status/100|0)==2,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:u,headers:{keys:function(){return s},entries:function(){return o},get:function(d){return a[d.toLowerCase()]},has:function(d){return d.toLowerCase()in a}}}};for(var c in i.open(e.method||"get",r,true),i.onload=function(){i.getAllResponseHeaders().replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm,function(d,l,g){s.push(l=l.toLowerCase()),o.push([l,g]),a[l]=a[l]?a[l]+","+g:g;}),t(u());},i.onerror=n,i.withCredentials=e.credentials=="include",e.headers)i.setRequestHeader(c,e.headers[c]);i.send(e.body||null);})}var pr=ke(()=>{});var Dn=j((Yc,Cn)=>{Cn.exports=self.fetch||(self.fetch=(pr(),re(gr)).default||(pr(),re(gr)));});var Vn=j((On,Mn)=>{(function(r){var e;if(typeof define=="function"&&define.amd&&(define(r),e=true),typeof On=="object"&&(Mn.exports=r(),e=true),!e){var t=window.Cookies,n=window.Cookies=r();n.noConflict=function(){return window.Cookies=t,n};}})(function(){function r(){for(var n=0,i={};n<arguments.length;n++){var s=arguments[n];for(var o in s)i[o]=s[o];}return i}function e(n){return n.replace(/(%[0-9A-Z]{2})+/g,decodeURIComponent)}function t(n){function i(){}function s(a,u,c){if(!(typeof document>"u")){c=r({path:"/"},i.defaults,c),typeof c.expires=="number"&&(c.expires=new Date(new Date*1+c.expires*864e5)),c.expires=c.expires?c.expires.toUTCString():"";try{var d=JSON.stringify(u);/^[\{\[]/.test(d)&&(u=d);}catch{}u=n.write?n.write(u,a):encodeURIComponent(String(u)).replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g,decodeURIComponent),a=encodeURIComponent(String(a)).replace(/%(23|24|26|2B|5E|60|7C)/g,decodeURIComponent).replace(/[\(\)]/g,escape);var l="";for(var g in c)c[g]&&(l+="; "+g,c[g]!==true&&(l+="="+c[g].split(";")[0]));return document.cookie=a+"="+u+l}}function o(a,u){if(!(typeof document>"u")){for(var c={},d=document.cookie?document.cookie.split("; "):[],l=0;l<d.length;l++){var g=d[l].split("="),p=g.slice(1).join("=");!u&&p.charAt(0)==='"'&&(p=p.slice(1,-1));try{var h=e(g[0]);if(p=(n.read||n)(p,h)||e(p),u)try{p=JSON.parse(p);}catch{}if(c[h]=p,a===h)break}catch{}}return a?c[a]:c}}return i.set=s,i.get=function(a){return o(a,false)},i.getJSON=function(a){return o(a,true)},i.remove=function(a,u){s(a,"",r(u,{expires:-1}));},i.defaults={},i.withConverter=t,i}return t(function(){})});});var he=typeof globalThis<"u"?globalThis:void 0,ot=he?.window;function Vs(r){if(Buffer)return Buffer.from(r).toString("base64");let e="",t=new Uint8Array(r),n=32768;for(let i=0;i<t.length;i+=n){let s=t.subarray(i,i+n);e+=String.fromCharCode.apply(null,Array.from(s));}if(typeof btoa=="function")return btoa(e);throw new Error("No base64 encoder available in this environment.")}if(ot)ot.global=ot,ot.global._runningInNodeJS=false;else if(he&&(he.global=he,typeof he.window>"u")){class r{constructor(){this.result=null;this.error=null;this.onload=null;this.onloadend=null;this.onerror=null;}readAsDataURL(n){n.arrayBuffer().then(i=>{let s=Vs(i),o=n.type||"application/octet-stream";this.result=`data:${o};base64,${s}`,this.onload&&this.onload({target:this}),this.onloadend&&this.onloadend({target:this});}).catch(i=>{this.error=i,this.onerror&&this.onerror({target:this});});}readAsArrayBuffer(n){n.arrayBuffer().then(i=>{this.result=i,this.onload&&this.onload({target:this}),this.onloadend&&this.onloadend({target:this});}).catch(i=>{this.error=i,this.onerror&&this.onerror({target:this});});}readAsText(n,i="utf-8"){n.text().then(s=>{this.result=s,this.onload&&this.onload({target:this}),this.onloadend&&this.onloadend({target:this});}).catch(s=>{this.error=s,this.onerror&&this.onerror({target:this});});}}he.FileReader=r;class e{constructor(){this.status=0;this.statusText="";this.readyState=0;this.responseText="";this.response=null;this.responseType="";this.responseURL="";this.timeout=0;this.withCredentials=false;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=false;}open(n,i){this._method=n,this._url=i,this.readyState=1;}setRequestHeader(n,i){this._headers[n]=i;}getResponseHeader(n){return null}abort(){this._aborted=true,this.onabort&&this.onabort({});}send(n){if(this._aborted)return;let i={method:this._method,headers:this._headers};n&&this._method!=="GET"&&this._method!=="HEAD"&&(i.body=n),fetch(this._url,i).then(async s=>{if(!this._aborted){if(this.status=s.status,this.statusText=s.statusText,this.responseURL=s.url,this.readyState=4,this.responseType==="blob")this.response=await s.blob();else if(this.responseType==="json")try{this.response=await s.json();}catch{this.response=null;}else this.responseType==="arraybuffer"?this.response=await s.arrayBuffer():(this.responseText=await s.text(),this.response=this.responseText);this.onload&&this.onload({});}}).catch(s=>{this._aborted||this.onerror&&this.onerror(s);});}}he.XMLHttpRequest=e,he.window={_runningInNodeJS:true,alert:t=>console.error("[Alert]",t),sessionStorage:{getItem:t=>null,setItem:(t,n)=>{},removeItem:t=>{}},localStorage:{getItem:t=>{let n=(Ie(),re(Re)),i=(Ie(),re(Re));try{let s=i.resolve(process.cwd(),"states","localStorage",`${t}.skapi`);return n.existsSync(s)?n.readFileSync(s,"utf8"):null}catch{return null}},setItem:(t,n)=>{let i=(Ie(),re(Re)),s=(Ie(),re(Re));try{let o=s.resolve(process.cwd(),"states","localStorage");i.existsSync(o)||i.mkdirSync(o,{recursive:!0});let a=s.resolve(o,`${t}.skapi`);i.writeFileSync(a,n,"utf8");}catch{}},removeItem:t=>{let n=(Ie(),re(Re)),i=(Ie(),re(Re));try{let s=i.resolve(process.cwd(),"states","localStorage",`${t}.skapi`);n.existsSync(s)&&n.unlinkSync(s);}catch{}}},location:{href:"",origin:"",hostname:"",protocol:"",replace:t=>{}},navigator:{userAgent:`nodejs/${he?.process?.versions?.node||"unknown"}`,mediaDevices:{getUserMedia:async t=>{throw new Error("getUserMedia is not supported in Node.js environment.")}}},addEventListener:()=>{},removeEventListener:()=>{}};}var Bt=(function(){function r(t){var n=t||{},i=n.ValidationData,s=n.Username,o=n.Password,a=n.AuthParameters,u=n.ClientMetadata;this.validationData=i||{},this.authParameters=a||{},this.clientMetadata=u||{},this.username=s,this.password=o;}var e=r.prototype;return e.getUsername=function(){return this.username},e.getPassword=function(){return this.password},e.getValidationData=function(){return this.validationData},e.getAuthParameters=function(){return this.authParameters},e.getClientMetadata=function(){return this.clientMetadata},r})();var pe=Te(ht());var X;typeof window<"u"&&window.crypto&&(X=window.crypto);!X&&typeof window<"u"&&window.msCrypto&&(X=window.msCrypto);!X&&typeof globalThis<"u"&&globalThis.crypto&&(X=globalThis.crypto);if(!X&&typeof Mr=="function")try{X=on();}catch{}function Gt(){if(X){if(typeof X.getRandomValues=="function")try{return X.getRandomValues(new Uint32Array(1))[0]}catch{}if(typeof X.randomBytes=="function")try{return X.randomBytes(4).readInt32LE()}catch{}}throw new Error("Native crypto module could not be used to get secure random number.")}function wo(r){for(var e=r.words,t=r.sigBytes,n=[],i=0;i<t;i++){var s=e[i>>>2]>>>24-i%4*8&255;n.push((s>>>4).toString(16)),n.push((s&15).toString(16));}return n.join("")}var Qt=(function(){function r(t,n){t=this.words=t||[],n!=null?this.sigBytes=n:this.sigBytes=t.length*4;}var e=r.prototype;return e.random=function(n){for(var i=[],s=0;s<n;s+=4)i.push(Gt());return new r(i,n)},e.toString=function(){return wo(this)},r})();var Et=Te(sr());var M=U;function U(r,e){r!=null&&this.fromString(r,e);}function H(){return new U(null)}var ye,ra=0xdeadbeefcafe,vn=(ra&16777215)==15715070;function na(r,e,t,n,i,s){for(;--s>=0;){var o=e*this[r++]+t[n]+i;i=Math.floor(o/67108864),t[n++]=o&67108863;}return i}function ia(r,e,t,n,i,s){for(var o=e&32767,a=e>>15;--s>=0;){var u=this[r]&32767,c=this[r++]>>15,d=a*u+c*o;u=o*u+((d&32767)<<15)+t[n]+(i&1073741823),i=(u>>>30)+(d>>>15)+a*c+(i>>>30),t[n++]=u&1073741823;}return i}function sa(r,e,t,n,i,s){for(var o=e&16383,a=e>>14;--s>=0;){var u=this[r]&16383,c=this[r++]>>14,d=a*u+c*o;u=o*u+((d&16383)<<14)+t[n]+i,i=(u>>28)+(d>>14)+a*c,t[n++]=u&268435455;}return i}var Tn=typeof navigator<"u";Tn&&vn&&navigator.appName=="Microsoft Internet Explorer"?(U.prototype.am=ia,ye=30):Tn&&vn&&navigator.appName!="Netscape"?(U.prototype.am=na,ye=26):(U.prototype.am=sa,ye=28);U.prototype.DB=ye;U.prototype.DM=(1<<ye)-1;U.prototype.DV=1<<ye;var or=52;U.prototype.FV=Math.pow(2,or);U.prototype.F1=or-ye;U.prototype.F2=2*ye-or;var oa="0123456789abcdefghijklmnopqrstuvwxyz",At=new Array,Le,te;Le=48;for(te=0;te<=9;++te)At[Le++]=te;Le=97;for(te=10;te<36;++te)At[Le++]=te;Le=65;for(te=10;te<36;++te)At[Le++]=te;function Rn(r){return oa.charAt(r)}function aa(r,e){var t=At[r.charCodeAt(e)];return t??-1}function ua(r){for(var e=this.t-1;e>=0;--e)r[e]=this[e];r.t=this.t,r.s=this.s;}function ca(r){this.t=1,this.s=r<0?-1:0,r>0?this[0]=r:r<-1?this[0]=r+this.DV:this.t=0;}function ar(r){var e=H();return e.fromInt(r),e}function la(r,e){var t;if(e==16)t=4;else if(e==8)t=3;else if(e==2)t=1;else if(e==32)t=5;else if(e==4)t=2;else throw new Error("Only radix 2, 4, 8, 16, 32 are supported");this.t=0,this.s=0;for(var n=r.length,i=false,s=0;--n>=0;){var o=aa(r,n);if(o<0){r.charAt(n)=="-"&&(i=true);continue}i=false,s==0?this[this.t++]=o:s+t>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+=t,s>=this.DB&&(s-=this.DB);}this.clamp(),i&&U.ZERO.subTo(this,this);}function da(){for(var r=this.s&this.DM;this.t>0&&this[this.t-1]==r;)--this.t;}function fa(r){if(this.s<0)return "-"+this.negate().toString(r);var e;if(r==16)e=4;else if(r==8)e=3;else if(r==2)e=1;else if(r==32)e=5;else if(r==4)e=2;else throw new Error("Only radix 2, 4, 8, 16, 32 are supported");var t=(1<<e)-1,n,i=false,s="",o=this.t,a=this.DB-o*this.DB%e;if(o-- >0)for(a<this.DB&&(n=this[o]>>a)>0&&(i=true,s=Rn(n));o>=0;)a<e?(n=(this[o]&(1<<a)-1)<<e-a,n|=this[--o]>>(a+=this.DB-e)):(n=this[o]>>(a-=e)&t,a<=0&&(a+=this.DB,--o)),n>0&&(i=true),i&&(s+=Rn(n));return i?s:"0"}function ha(){var r=H();return U.ZERO.subTo(this,r),r}function ga(){return this.s<0?this.negate():this}function pa(r){var e=this.s-r.s;if(e!=0)return e;var t=this.t;if(e=t-r.t,e!=0)return this.s<0?-e:e;for(;--t>=0;)if((e=this[t]-r[t])!=0)return e;return 0}function ur(r){var e=1,t;return (t=r>>>16)!=0&&(r=t,e+=16),(t=r>>8)!=0&&(r=t,e+=8),(t=r>>4)!=0&&(r=t,e+=4),(t=r>>2)!=0&&(r=t,e+=2),(t=r>>1)!=0&&(r=t,e+=1),e}function ma(){return this.t<=0?0:this.DB*(this.t-1)+ur(this[this.t-1]^this.s&this.DM)}function _a(r,e){var t;for(t=this.t-1;t>=0;--t)e[t+r]=this[t];for(t=r-1;t>=0;--t)e[t]=0;e.t=this.t+r,e.s=this.s;}function ba(r,e){for(var t=r;t<this.t;++t)e[t-r]=this[t];e.t=Math.max(this.t-r,0),e.s=this.s;}function ya(r,e){var t=r%this.DB,n=this.DB-t,i=(1<<n)-1,s=Math.floor(r/this.DB),o=this.s<<t&this.DM,a;for(a=this.t-1;a>=0;--a)e[a+s+1]=this[a]>>n|o,o=(this[a]&i)<<t;for(a=s-1;a>=0;--a)e[a]=0;e[s]=o,e.t=this.t+s+1,e.s=this.s,e.clamp();}function wa(r,e){e.s=this.s;var t=Math.floor(r/this.DB);if(t>=this.t){e.t=0;return}var n=r%this.DB,i=this.DB-n,s=(1<<n)-1;e[0]=this[t]>>n;for(var o=t+1;o<this.t;++o)e[o-t-1]|=(this[o]&s)<<i,e[o-t]=this[o]>>n;n>0&&(e[this.t-t-1]|=(this.s&s)<<i),e.t=this.t-t,e.clamp();}function Aa(r,e){for(var t=0,n=0,i=Math.min(r.t,this.t);t<i;)n+=this[t]-r[t],e[t++]=n&this.DM,n>>=this.DB;if(r.t<this.t){for(n-=r.s;t<this.t;)n+=this[t],e[t++]=n&this.DM,n>>=this.DB;n+=this.s;}else {for(n+=this.s;t<r.t;)n-=r[t],e[t++]=n&this.DM,n>>=this.DB;n-=r.s;}e.s=n<0?-1:0,n<-1?e[t++]=this.DV+n:n>0&&(e[t++]=n),e.t=t,e.clamp();}function Ea(r,e){var t=this.abs(),n=r.abs(),i=t.t;for(e.t=i+n.t;--i>=0;)e[i]=0;for(i=0;i<n.t;++i)e[i+t.t]=t.am(0,n[i],e,i,0,t.t);e.s=0,e.clamp(),this.s!=r.s&&U.ZERO.subTo(e,e);}function Sa(r){for(var e=this.abs(),t=r.t=2*e.t;--t>=0;)r[t]=0;for(t=0;t<e.t-1;++t){var n=e.am(t,e[t],r,2*t,0,1);(r[t+e.t]+=e.am(t+1,2*e[t],r,2*t+1,n,e.t-t-1))>=e.DV&&(r[t+e.t]-=e.DV,r[t+e.t+1]=1);}r.t>0&&(r[r.t-1]+=e.am(t,e[t],r,2*t,0,1)),r.s=0,r.clamp();}function va(r,e,t){var n=r.abs();if(!(n.t<=0)){var i=this.abs();if(i.t<n.t){e?.fromInt(0),t!=null&&this.copyTo(t);return}t==null&&(t=H());var s=H(),o=this.s,a=r.s,u=this.DB-ur(n[n.t-1]);u>0?(n.lShiftTo(u,s),i.lShiftTo(u,t)):(n.copyTo(s),i.copyTo(t));var c=s.t,d=s[c-1];if(d!=0){var l=d*(1<<this.F1)+(c>1?s[c-2]>>this.F2:0),g=this.FV/l,p=(1<<this.F1)/l,h=1<<this.F2,b=t.t,w=b-c,_=e??H();for(s.dlShiftTo(w,_),t.compareTo(_)>=0&&(t[t.t++]=1,t.subTo(_,t)),U.ONE.dlShiftTo(c,_),_.subTo(s,s);s.t<c;)s[s.t++]=0;for(;--w>=0;){var R=t[--b]==d?this.DM:Math.floor(t[b]*g+(t[b-1]+h)*p);if((t[b]+=s.am(0,R,t,w,0,c))<R)for(s.dlShiftTo(w,_),t.subTo(_,t);t[b]<--R;)t.subTo(_,t);}e!=null&&(t.drShiftTo(c,e),o!=a&&U.ZERO.subTo(e,e)),t.t=c,t.clamp(),u>0&&t.rShiftTo(u,t),o<0&&U.ZERO.subTo(t,t);}}}function Ta(r){var e=H();return this.abs().divRemTo(r,null,e),this.s<0&&e.compareTo(U.ZERO)>0&&r.subTo(e,e),e}function Ra(){if(this.t<1)return 0;var r=this[0];if((r&1)==0)return 0;var e=r&3;return e=e*(2-(r&15)*e)&15,e=e*(2-(r&255)*e)&255,e=e*(2-((r&65535)*e&65535))&65535,e=e*(2-r*e%this.DV)%this.DV,e>0?this.DV-e:-e}function Ia(r){return this.compareTo(r)==0}function Pa(r,e){for(var t=0,n=0,i=Math.min(r.t,this.t);t<i;)n+=this[t]+r[t],e[t++]=n&this.DM,n>>=this.DB;if(r.t<this.t){for(n+=r.s;t<this.t;)n+=this[t],e[t++]=n&this.DM,n>>=this.DB;n+=this.s;}else {for(n+=this.s;t<r.t;)n+=r[t],e[t++]=n&this.DM,n>>=this.DB;n+=r.s;}e.s=n<0?-1:0,n>0?e[t++]=n:n<-1&&(e[t++]=this.DV+n),e.t=t,e.clamp();}function xa(r){var e=H();return this.addTo(r,e),e}function Ua(r){var e=H();return this.subTo(r,e),e}function Ca(r){var e=H();return this.multiplyTo(r,e),e}function Da(r){var e=H();return this.divRemTo(r,e,null),e}function Oe(r){this.m=r,this.mp=r.invDigit(),this.mpl=this.mp&32767,this.mph=this.mp>>15,this.um=(1<<r.DB-15)-1,this.mt2=2*r.t;}function ka(r){var e=H();return r.abs().dlShiftTo(this.m.t,e),e.divRemTo(this.m,null,e),r.s<0&&e.compareTo(U.ZERO)>0&&this.m.subTo(e,e),e}function Na(r){var e=H();return r.copyTo(e),this.reduce(e),e}function Fa(r){for(;r.t<=this.mt2;)r[r.t++]=0;for(var e=0;e<this.m.t;++e){var t=r[e]&32767,n=t*this.mpl+((t*this.mph+(r[e]>>15)*this.mpl&this.um)<<15)&r.DM;for(t=e+this.m.t,r[t]+=this.m.am(0,n,r,e,0,this.m.t);r[t]>=r.DV;)r[t]-=r.DV,r[++t]++;}r.clamp(),r.drShiftTo(this.m.t,r),r.compareTo(this.m)>=0&&r.subTo(this.m,r);}function La(r,e){r.squareTo(e),this.reduce(e);}function Oa(r,e,t){r.multiplyTo(e,t),this.reduce(t);}Oe.prototype.convert=ka;Oe.prototype.revert=Na;Oe.prototype.reduce=Fa;Oe.prototype.mulTo=Oa;Oe.prototype.sqrTo=La;function Ma(r,e,t){var n=r.bitLength(),i,s=ar(1),o=new Oe(e);if(n<=0)return s;n<18?i=1:n<48?i=3:n<144?i=4:n<768?i=5:i=6;var a=new Array,u=3,c=i-1,d=(1<<i)-1;if(a[1]=o.convert(this),i>1){var l=H();for(o.sqrTo(a[1],l);u<=d;)a[u]=H(),o.mulTo(l,a[u-2],a[u]),u+=2;}var g=r.t-1,p,h=true,b=H(),w;for(n=ur(r[g])-1;g>=0;){for(n>=c?p=r[g]>>n-c&d:(p=(r[g]&(1<<n+1)-1)<<c-n,g>0&&(p|=r[g-1]>>this.DB+n-c)),u=i;(p&1)==0;)p>>=1,--u;if((n-=u)<0&&(n+=this.DB,--g),h)a[p].copyTo(s),h=false;else {for(;u>1;)o.sqrTo(s,b),o.sqrTo(b,s),u-=2;u>0?o.sqrTo(s,b):(w=s,s=b,b=w),o.mulTo(b,a[p],s);}for(;g>=0&&(r[g]&1<<n)==0;)o.sqrTo(s,b),w=s,s=b,b=w,--n<0&&(n=this.DB-1,--g);}var _=o.revert(s);return t(null,_),_}U.prototype.copyTo=ua;U.prototype.fromInt=ca;U.prototype.fromString=la;U.prototype.clamp=da;U.prototype.dlShiftTo=_a;U.prototype.drShiftTo=ba;U.prototype.lShiftTo=ya;U.prototype.rShiftTo=wa;U.prototype.subTo=Aa;U.prototype.multiplyTo=Ea;U.prototype.squareTo=Sa;U.prototype.divRemTo=va;U.prototype.invDigit=Ra;U.prototype.addTo=Pa;U.prototype.toString=fa;U.prototype.negate=ha;U.prototype.abs=ga;U.prototype.compareTo=pa;U.prototype.bitLength=ma;U.prototype.mod=Ta;U.prototype.equals=Ia;U.prototype.add=xa;U.prototype.subtract=Ua;U.prototype.multiply=Ca;U.prototype.divide=Da;U.prototype.modPow=Ma;U.ZERO=ar(0);U.ONE=ar(1);function cr(r){return pe.Buffer.from(new Qt().random(r).toString(),"hex")}var Va=/^[89a-f]/i,qa="FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200CBBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF",Ba="userAttributes.",we=(function(){function r(t){this.N=new M(qa,16),this.g=new M("2",16),this.k=new M(this.hexHash(""+this.padHex(this.N)+this.padHex(this.g)),16),this.smallAValue=this.generateRandomSmallA(),this.getLargeAValue(function(){}),this.infoBits=pe.Buffer.from("Caldera Derived Key","utf8"),this.poolName=t;}var e=r.prototype;return e.getSmallAValue=function(){return this.smallAValue},e.getLargeAValue=function(n){var i=this;this.largeAValue?n(null,this.largeAValue):this.calculateA(this.smallAValue,function(s,o){s&&n(s,null),i.largeAValue=o,n(null,i.largeAValue);});},e.generateRandomSmallA=function(){var n=cr(128).toString("hex"),i=new M(n,16);return i},e.generateRandomString=function(){return cr(40).toString("base64")},e.getRandomPassword=function(){return this.randomPassword},e.getSaltDevices=function(){return this.SaltToHashDevices},e.getVerifierDevices=function(){return this.verifierDevices},e.generateHashDevice=function(n,i,s){var o=this;this.randomPassword=this.generateRandomString();var a=""+n+i+":"+this.randomPassword,u=this.hash(a),c=cr(16).toString("hex");this.SaltToHashDevices=this.padHex(new M(c,16)),this.g.modPow(new M(this.hexHash(this.SaltToHashDevices+u),16),this.N,function(d,l){d&&s(d,null),o.verifierDevices=o.padHex(l),s(null,null);});},e.calculateA=function(n,i){var s=this;this.g.modPow(n,this.N,function(o,a){o&&i(o,null),a.mod(s.N).equals(M.ZERO)&&i(new Error("Illegal paramater. A mod N cannot be 0."),null),i(null,a);});},e.calculateU=function(n,i){this.UHexHash=this.hexHash(this.padHex(n)+this.padHex(i));var s=new M(this.UHexHash,16);return s},e.hash=function(n){var i=new Et.Sha256;i.update(n);var s=i.digestSync(),o=pe.Buffer.from(s).toString("hex");return new Array(64-o.length).join("0")+o},e.hexHash=function(n){return this.hash(pe.Buffer.from(n,"hex"))},e.computehkdf=function(n,i){var s=pe.Buffer.concat([this.infoBits,pe.Buffer.from("","utf8")]),o=new Et.Sha256(i);o.update(n);var a=o.digestSync(),u=new Et.Sha256(a);u.update(s);var c=u.digestSync(),d=c,l=d.slice(0,16);return l},e.getPasswordAuthenticationKey=function(n,i,s,o,a){var u=this;if(s.mod(this.N).equals(M.ZERO))throw new Error("B cannot be zero.");if(this.UValue=this.calculateU(this.largeAValue,s),this.UValue.equals(M.ZERO))throw new Error("U cannot be zero.");var c=""+this.poolName+n+":"+i,d=this.hash(c),l=new M(this.hexHash(this.padHex(o)+d),16);this.calculateS(l,s,function(g,p){g&&a(g,null);var h=u.computehkdf(pe.Buffer.from(u.padHex(p),"hex"),pe.Buffer.from(u.padHex(u.UValue),"hex"));a(null,h);});},e.calculateS=function(n,i,s){var o=this;this.g.modPow(n,this.N,function(a,u){a&&s(a,null);var c=i.subtract(o.k.multiply(u));c.modPow(o.smallAValue.add(o.UValue.multiply(n)),o.N,function(d,l){d&&s(d,null),s(null,l.mod(o.N));});});},e.getNewPasswordRequiredChallengeUserAttributePrefix=function(){return Ba},e.padHex=function(n){if(!(n instanceof M))throw new Error("Not a BigInteger");var i=n.compareTo(M.ZERO)<0,s=n.abs().toString(16);if(s=s.length%2!==0?"0"+s:s,s=Va.test(s)?"00"+s:s,i){var o=s.split("").map(function(u){var c=~parseInt(u,16)&15;return "0123456789ABCDEF".charAt(c)}).join(""),a=new M(o,16).add(M.ONE);s=a.toString(16),s.toUpperCase().startsWith("FF8")&&(s=s.substring(2));}return s},r})();var In=Te(ht());var St=(function(){function r(t){this.jwtToken=t||"",this.payload=this.decodePayload();}var e=r.prototype;return e.getJwtToken=function(){return this.jwtToken},e.getExpiration=function(){return this.payload.exp},e.getIssuedAt=function(){return this.payload.iat},e.decodePayload=function(){var n=this.jwtToken.split(".")[1];try{return JSON.parse(In.Buffer.from(n,"base64").toString("utf8"))}catch{return {}}},r})();function $a(r,e){r.prototype=Object.create(e.prototype),r.prototype.constructor=r,lr(r,e);}function lr(r,e){return lr=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,n){return t.__proto__=n,t},lr(r,e)}var Me=(function(r){function e(t){var n=t===void 0?{}:t,i=n.AccessToken;return r.call(this,i||"")||this}return $a(e,r),e})(St);function ja(r,e){r.prototype=Object.create(e.prototype),r.prototype.constructor=r,dr(r,e);}function dr(r,e){return dr=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,n){return t.__proto__=n,t},dr(r,e)}var Ve=(function(r){function e(t){var n=t===void 0?{}:t,i=n.IdToken;return r.call(this,i||"")||this}return ja(e,r),e})(St);var qe=(function(){function r(t){var n=t===void 0?{}:t,i=n.RefreshToken;this.token=i||"";}var e=r.prototype;return e.getToken=function(){return this.token},r})();var B=Te(ht()),hr=Te(sr());var Pn="5.0.4";var Ka="aws-amplify/"+Pn,fr={userAgent:Ka,isReactNative:typeof navigator<"u"&&navigator.product==="ReactNative"},xn=function(){return fr.userAgent};var Be=(function(){function r(t){var n=t===void 0?{}:t,i=n.IdToken,s=n.RefreshToken,o=n.AccessToken,a=n.ClockDrift;if(o==null||i==null)throw new Error("Id token and Access Token must be present.");this.idToken=i,this.refreshToken=s,this.accessToken=o,this.clockDrift=a===void 0?this.calculateClockDrift():a;}var e=r.prototype;return e.getIdToken=function(){return this.idToken},e.getRefreshToken=function(){return this.refreshToken},e.getAccessToken=function(){return this.accessToken},e.getClockDrift=function(){return this.clockDrift},e.calculateClockDrift=function(){var n=Math.floor(new Date/1e3),i=Math.min(this.accessToken.getIssuedAt(),this.idToken.getIssuedAt());return n-i},e.isValid=function(){var n=Math.floor(new Date/1e3),i=n-this.clockDrift;return i<this.accessToken.getExpiration()&&i<this.idToken.getExpiration()},r})();var Ha=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],Wa=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],vt=(function(){function r(){}var e=r.prototype;return e.getNowString=function(){var n=new Date,i=Wa[n.getUTCDay()],s=Ha[n.getUTCMonth()],o=n.getUTCDate(),a=n.getUTCHours();a<10&&(a="0"+a);var u=n.getUTCMinutes();u<10&&(u="0"+u);var c=n.getUTCSeconds();c<10&&(c="0"+c);var d=n.getUTCFullYear(),l=i+" "+s+" "+o+" "+a+":"+u+":"+c+" UTC "+d;return l},r})();var ce=(function(){function r(t){var n=t===void 0?{}:t,i=n.Name,s=n.Value;this.Name=i||"",this.Value=s||"";}var e=r.prototype;return e.getValue=function(){return this.Value},e.setValue=function(n){return this.Value=n,this},e.getName=function(){return this.Name},e.setName=function(n){return this.Name=n,this},e.toString=function(){return JSON.stringify(this)},e.toJSON=function(){return {Name:this.Name,Value:this.Value}},r})();var Ue={},Ja=(function(){function r(){}return r.setItem=function(t,n){return Ue[t]=n,Ue[t]},r.getItem=function(t){return Object.prototype.hasOwnProperty.call(Ue,t)?Ue[t]:void 0},r.removeItem=function(t){return delete Ue[t]},r.clear=function(){return Ue={},Ue},r})(),Tt=(function(){function r(){try{this.storageWindow=window.localStorage,this.storageWindow.setItem("aws.cognito.test-ls",1),this.storageWindow.removeItem("aws.cognito.test-ls");}catch{this.storageWindow=Ja;}}var e=r.prototype;return e.getStorage=function(){return this.storageWindow},r})();var Ga=typeof navigator<"u",Un=Ga?fr.isReactNative?"react-native":navigator.userAgent:"nodejs",me=(function(){function r(t){if(t==null||t.Username==null||t.Pool==null)throw new Error("Username and Pool information are required.");this.username=t.Username||"",this.pool=t.Pool,this.Session=null,this.client=t.Pool.client,this.signInUserSession=null,this.authenticationFlowType="USER_SRP_AUTH",this.storage=t.Storage||new Tt().getStorage(),this.keyPrefix="CognitoIdentityServiceProvider."+this.pool.getClientId(),this.userDataKey=this.keyPrefix+"."+this.username+".userData";}var e=r.prototype;return e.setSignInUserSession=function(n){this.clearCachedUserData(),this.signInUserSession=n,this.cacheTokens();},e.getSignInUserSession=function(){return this.signInUserSession},e.getUsername=function(){return this.username},e.getAuthenticationFlowType=function(){return this.authenticationFlowType},e.setAuthenticationFlowType=function(n){this.authenticationFlowType=n;},e.initiateAuth=function(n,i){var s=this,o=n.getAuthParameters();o.USERNAME=this.username;var a=Object.keys(n.getValidationData()).length!==0?n.getValidationData():n.getClientMetadata(),u={AuthFlow:"CUSTOM_AUTH",ClientId:this.pool.getClientId(),AuthParameters:o,ClientMetadata:a};this.getUserContextData()&&(u.UserContextData=this.getUserContextData()),this.client.request("InitiateAuth",u,function(c,d){if(c)return i.onFailure(c);var l=d.ChallengeName,g=d.ChallengeParameters;return l==="CUSTOM_CHALLENGE"?(s.Session=d.Session,i.customChallenge(g)):(s.signInUserSession=s.getCognitoUserSession(d.AuthenticationResult),s.cacheTokens(),i.onSuccess(s.signInUserSession))});},e.authenticateUser=function(n,i){return this.authenticationFlowType==="USER_PASSWORD_AUTH"?this.authenticateUserPlainUsernamePassword(n,i):this.authenticationFlowType==="USER_SRP_AUTH"||this.authenticationFlowType==="CUSTOM_AUTH"?this.authenticateUserDefaultAuth(n,i):i.onFailure(new Error("Authentication flow type is invalid."))},e.authenticateUserDefaultAuth=function(n,i){var s=this,o=new we(this.pool.getUserPoolName()),a=new vt,u,c,d={};this.deviceKey!=null&&(d.DEVICE_KEY=this.deviceKey),d.USERNAME=this.username,o.getLargeAValue(function(l,g){l&&i.onFailure(l),d.SRP_A=g.toString(16),s.authenticationFlowType==="CUSTOM_AUTH"&&(d.CHALLENGE_NAME="SRP_A");var p=Object.keys(n.getValidationData()).length!==0?n.getValidationData():n.getClientMetadata(),h={AuthFlow:s.authenticationFlowType,ClientId:s.pool.getClientId(),AuthParameters:d,ClientMetadata:p};s.getUserContextData(s.username)&&(h.UserContextData=s.getUserContextData(s.username)),s.client.request("InitiateAuth",h,function(b,w){if(b)return i.onFailure(b);var _=w.ChallengeParameters;s.username=_.USER_ID_FOR_SRP,s.userDataKey=s.keyPrefix+"."+s.username+".userData",u=new M(_.SRP_B,16),c=new M(_.SALT,16),s.getCachedDeviceKeyAndPassword(),o.getPasswordAuthenticationKey(s.username,n.getPassword(),u,c,function(R,C){R&&i.onFailure(R);var I=a.getNowString(),k=B.Buffer.concat([B.Buffer.from(s.pool.getUserPoolName(),"utf8"),B.Buffer.from(s.username,"utf8"),B.Buffer.from(_.SECRET_BLOCK,"base64"),B.Buffer.from(I,"utf8")]),K=new hr.Sha256(C);K.update(k);var ve=K.digestSync(),V=B.Buffer.from(ve).toString("base64"),P={};P.USERNAME=s.username,P.PASSWORD_CLAIM_SECRET_BLOCK=_.SECRET_BLOCK,P.TIMESTAMP=I,P.PASSWORD_CLAIM_SIGNATURE=V,s.deviceKey!=null&&(P.DEVICE_KEY=s.deviceKey);var D=function(Ce,Lr){return s.client.request("RespondToAuthChallenge",Ce,function(it,Cs){return it&&it.code==="ResourceNotFoundException"&&it.message.toLowerCase().indexOf("device")!==-1?(P.DEVICE_KEY=null,s.deviceKey=null,s.randomPassword=null,s.deviceGroupKey=null,s.clearCachedDeviceKeyAndPassword(),D(Ce,Lr)):Lr(it,Cs)})},N={ChallengeName:"PASSWORD_VERIFIER",ClientId:s.pool.getClientId(),ChallengeResponses:P,Session:w.Session,ClientMetadata:p};s.getUserContextData()&&(N.UserContextData=s.getUserContextData()),D(N,function(F,Ce){return F?i.onFailure(F):s.authenticateUserInternal(Ce,o,i)});});});});},e.authenticateUserPlainUsernamePassword=function(n,i){var s=this,o={};if(o.USERNAME=this.username,o.PASSWORD=n.getPassword(),!o.PASSWORD){i.onFailure(new Error("PASSWORD parameter is required"));return}var a=new we(this.pool.getUserPoolName());this.getCachedDeviceKeyAndPassword(),this.deviceKey!=null&&(o.DEVICE_KEY=this.deviceKey);var u=Object.keys(n.getValidationData()).length!==0?n.getValidationData():n.getClientMetadata(),c={AuthFlow:"USER_PASSWORD_AUTH",ClientId:this.pool.getClientId(),AuthParameters:o,ClientMetadata:u};this.getUserContextData(this.username)&&(c.UserContextData=this.getUserContextData(this.username)),this.client.request("InitiateAuth",c,function(d,l){return d?i.onFailure(d):s.authenticateUserInternal(l,a,i)});},e.authenticateUserInternal=function(n,i,s){var o=this,a=n.ChallengeName,u=n.ChallengeParameters;if(a==="SMS_MFA")return this.Session=n.Session,s.mfaRequired(a,u);if(a==="SELECT_MFA_TYPE")return this.Session=n.Session,s.selectMFAType(a,u);if(a==="MFA_SETUP")return this.Session=n.Session,s.mfaSetup(a,u);if(a==="SOFTWARE_TOKEN_MFA")return this.Session=n.Session,s.totpRequired(a,u);if(a==="CUSTOM_CHALLENGE")return this.Session=n.Session,s.customChallenge(u);if(a==="NEW_PASSWORD_REQUIRED"){this.Session=n.Session;var c=null,d=null,l=[],g=i.getNewPasswordRequiredChallengeUserAttributePrefix();if(u&&(c=JSON.parse(n.ChallengeParameters.userAttributes),d=JSON.parse(n.ChallengeParameters.requiredAttributes)),d)for(var p=0;p<d.length;p++)l[p]=d[p].substr(g.length);return s.newPasswordRequired(c,l)}if(a==="DEVICE_SRP_AUTH"){this.Session=n.Session,this.getDeviceResponse(s);return}this.signInUserSession=this.getCognitoUserSession(n.AuthenticationResult),this.challengeName=a,this.cacheTokens();var h=n.AuthenticationResult.NewDeviceMetadata;if(h==null)return s.onSuccess(this.signInUserSession);i.generateHashDevice(n.AuthenticationResult.NewDeviceMetadata.DeviceGroupKey,n.AuthenticationResult.NewDeviceMetadata.DeviceKey,function(b){if(b)return s.onFailure(b);var w={Salt:B.Buffer.from(i.getSaltDevices(),"hex").toString("base64"),PasswordVerifier:B.Buffer.from(i.getVerifierDevices(),"hex").toString("base64")};o.verifierDevices=w.PasswordVerifier,o.deviceGroupKey=h.DeviceGroupKey,o.randomPassword=i.getRandomPassword(),o.client.request("ConfirmDevice",{DeviceKey:h.DeviceKey,AccessToken:o.signInUserSession.getAccessToken().getJwtToken(),DeviceSecretVerifierConfig:w,DeviceName:Un},function(_,R){return _?s.onFailure(_):(o.deviceKey=n.AuthenticationResult.NewDeviceMetadata.DeviceKey,o.cacheDeviceKeyAndPassword(),R.UserConfirmationNecessary===true?s.onSuccess(o.signInUserSession,R.UserConfirmationNecessary):s.onSuccess(o.signInUserSession))});});},e.completeNewPasswordChallenge=function(n,i,s,o){var a=this;if(!n)return s.onFailure(new Error("New password is required."));var u=new we(this.pool.getUserPoolName()),c=u.getNewPasswordRequiredChallengeUserAttributePrefix(),d={};i&&Object.keys(i).forEach(function(g){d[c+g]=i[g];}),d.NEW_PASSWORD=n,d.USERNAME=this.username;var l={ChallengeName:"NEW_PASSWORD_REQUIRED",ClientId:this.pool.getClientId(),ChallengeResponses:d,Session:this.Session,ClientMetadata:o};this.getUserContextData()&&(l.UserContextData=this.getUserContextData()),this.client.request("RespondToAuthChallenge",l,function(g,p){return g?s.onFailure(g):a.authenticateUserInternal(p,u,s)});},e.getDeviceResponse=function(n,i){var s=this,o=new we(this.deviceGroupKey),a=new vt,u={};u.USERNAME=this.username,u.DEVICE_KEY=this.deviceKey,o.getLargeAValue(function(c,d){c&&n.onFailure(c),u.SRP_A=d.toString(16);var l={ChallengeName:"DEVICE_SRP_AUTH",ClientId:s.pool.getClientId(),ChallengeResponses:u,ClientMetadata:i,Session:s.Session};s.getUserContextData()&&(l.UserContextData=s.getUserContextData()),s.client.request("RespondToAuthChallenge",l,function(g,p){if(g)return n.onFailure(g);var h=p.ChallengeParameters,b=new M(h.SRP_B,16),w=new M(h.SALT,16);o.getPasswordAuthenticationKey(s.deviceKey,s.randomPassword,b,w,function(_,R){if(_)return n.onFailure(_);var C=a.getNowString(),I=B.Buffer.concat([B.Buffer.from(s.deviceGroupKey,"utf8"),B.Buffer.from(s.deviceKey,"utf8"),B.Buffer.from(h.SECRET_BLOCK,"base64"),B.Buffer.from(C,"utf8")]),k=new hr.Sha256(R);k.update(I);var K=k.digestSync(),ve=B.Buffer.from(K).toString("base64"),V={};V.USERNAME=s.username,V.PASSWORD_CLAIM_SECRET_BLOCK=h.SECRET_BLOCK,V.TIMESTAMP=C,V.PASSWORD_CLAIM_SIGNATURE=ve,V.DEVICE_KEY=s.deviceKey;var P={ChallengeName:"DEVICE_PASSWORD_VERIFIER",ClientId:s.pool.getClientId(),ChallengeResponses:V,Session:p.Session};s.getUserContextData()&&(P.UserContextData=s.getUserContextData()),s.client.request("RespondToAuthChallenge",P,function(D,N){return D?n.onFailure(D):(s.signInUserSession=s.getCognitoUserSession(N.AuthenticationResult),s.cacheTokens(),n.onSuccess(s.signInUserSession))});});});});},e.confirmRegistration=function(n,i,s,o){var a={ClientId:this.pool.getClientId(),ConfirmationCode:n,Username:this.username,ForceAliasCreation:i,ClientMetadata:o};this.getUserContextData()&&(a.UserContextData=this.getUserContextData()),this.client.request("ConfirmSignUp",a,function(u){return u?s(u,null):s(null,"SUCCESS")});},e.sendCustomChallengeAnswer=function(n,i,s){var o=this,a={};a.USERNAME=this.username,a.ANSWER=n;var u=new we(this.pool.getUserPoolName());this.getCachedDeviceKeyAndPassword(),this.deviceKey!=null&&(a.DEVICE_KEY=this.deviceKey);var c={ChallengeName:"CUSTOM_CHALLENGE",ChallengeResponses:a,ClientId:this.pool.getClientId(),Session:this.Session,ClientMetadata:s};this.getUserContextData()&&(c.UserContextData=this.getUserContextData()),this.client.request("RespondToAuthChallenge",c,function(d,l){return d?i.onFailure(d):o.authenticateUserInternal(l,u,i)});},e.sendMFACode=function(n,i,s,o){var a=this,u={};u.USERNAME=this.username,u.SMS_MFA_CODE=n;var c=s||"SMS_MFA";c==="SOFTWARE_TOKEN_MFA"&&(u.SOFTWARE_TOKEN_MFA_CODE=n),this.deviceKey!=null&&(u.DEVICE_KEY=this.deviceKey);var d={ChallengeName:c,ChallengeResponses:u,ClientId:this.pool.getClientId(),Session:this.Session,ClientMetadata:o};this.getUserContextData()&&(d.UserContextData=this.getUserContextData()),this.client.request("RespondToAuthChallenge",d,function(l,g){if(l)return i.onFailure(l);var p=g.ChallengeName;if(p==="DEVICE_SRP_AUTH"){a.getDeviceResponse(i);return}if(a.signInUserSession=a.getCognitoUserSession(g.AuthenticationResult),a.cacheTokens(),g.AuthenticationResult.NewDeviceMetadata==null)return i.onSuccess(a.signInUserSession);var h=new we(a.pool.getUserPoolName());h.generateHashDevice(g.AuthenticationResult.NewDeviceMetadata.DeviceGroupKey,g.AuthenticationResult.NewDeviceMetadata.DeviceKey,function(b){if(b)return i.onFailure(b);var w={Salt:B.Buffer.from(h.getSaltDevices(),"hex").toString("base64"),PasswordVerifier:B.Buffer.from(h.getVerifierDevices(),"hex").toString("base64")};a.verifierDevices=w.PasswordVerifier,a.deviceGroupKey=g.AuthenticationResult.NewDeviceMetadata.DeviceGroupKey,a.randomPassword=h.getRandomPassword(),a.client.request("ConfirmDevice",{DeviceKey:g.AuthenticationResult.NewDeviceMetadata.DeviceKey,AccessToken:a.signInUserSession.getAccessToken().getJwtToken(),DeviceSecretVerifierConfig:w,DeviceName:Un},function(_,R){return _?i.onFailure(_):(a.deviceKey=g.AuthenticationResult.NewDeviceMetadata.DeviceKey,a.cacheDeviceKeyAndPassword(),R.UserConfirmationNecessary===true?i.onSuccess(a.signInUserSession,R.UserConfirmationNecessary):i.onSuccess(a.signInUserSession))});});});},e.changePassword=function(n,i,s,o){if(!(this.signInUserSession!=null&&this.signInUserSession.isValid()))return s(new Error("User is not authenticated"),null);this.client.request("ChangePassword",{PreviousPassword:n,ProposedPassword:i,AccessToken:this.signInUserSession.getAccessToken().getJwtToken(),ClientMetadata:o},function(a){return a?s(a,null):s(null,"SUCCESS")});},e.enableMFA=function(n){if(this.signInUserSession==null||!this.signInUserSession.isValid())return n(new Error("User is not authenticated"),null);var i=[],s={DeliveryMedium:"SMS",AttributeName:"phone_number"};i.push(s),this.client.request("SetUserSettings",{MFAOptions:i,AccessToken:this.signInUserSession.getAccessToken().getJwtToken()},function(o){return o?n(o,null):n(null,"SUCCESS")});},e.setUserMfaPreference=function(n,i,s){if(this.signInUserSession==null||!this.signInUserSession.isValid())return s(new Error("User is not authenticated"),null);this.client.request("SetUserMFAPreference",{SMSMfaSettings:n,SoftwareTokenMfaSettings:i,AccessToken:this.signInUserSession.getAccessToken().getJwtToken()},function(o){return o?s(o,null):s(null,"SUCCESS")});},e.disableMFA=function(n){if(this.signInUserSession==null||!this.signInUserSession.isValid())return n(new Error("User is not authenticated"),null);var i=[];this.client.request("SetUserSettings",{MFAOptions:i,AccessToken:this.signInUserSession.getAccessToken().getJwtToken()},function(s){return s?n(s,null):n(null,"SUCCESS")});},e.deleteUser=function(n,i){var s=this;if(this.signInUserSession==null||!this.signInUserSession.isValid())return n(new Error("User is not authenticated"),null);this.client.request("DeleteUser",{AccessToken:this.signInUserSession.getAccessToken().getJwtToken(),ClientMetadata:i},function(o){return o?n(o,null):(s.clearCachedUser(),n(null,"SUCCESS"))});},e.updateAttributes=function(n,i,s){var o=this;if(this.signInUserSession==null||!this.signInUserSession.isValid())return i(new Error("User is not authenticated"),null);this.client.request("UpdateUserAttributes",{AccessToken:this.signInUserSession.getAccessToken().getJwtToken(),UserAttributes:n,ClientMetadata:s},function(a,u){return a?i(a,null):o.getUserData(function(){return i(null,"SUCCESS",u)},{bypassCache:true})});},e.getUserAttributes=function(n){if(!(this.signInUserSession!=null&&this.signInUserSession.isValid()))return n(new Error("User is not authenticated"),null);this.client.request("GetUser",{AccessToken:this.signInUserSession.getAccessToken().getJwtToken()},function(i,s){if(i)return n(i,null);for(var o=[],a=0;a<s.UserAttributes.length;a++){var u={Name:s.UserAttributes[a].Name,Value:s.UserAttributes[a].Value},c=new ce(u);o.push(c);}return n(null,o)});},e.getMFAOptions=function(n){if(!(this.signInUserSession!=null&&this.signInUserSession.isValid()))return n(new Error("User is not authenticated"),null);this.client.request("GetUser",{AccessToken:this.signInUserSession.getAccessToken().getJwtToken()},function(i,s){return i?n(i,null):n(null,s.MFAOptions)});},e.createGetUserRequest=function(){return this.client.promisifyRequest("GetUser",{AccessToken:this.signInUserSession.getAccessToken().getJwtToken()})},e.refreshSessionIfPossible=function(n){var i=this;return n===void 0&&(n={}),new Promise(function(s){var o=i.signInUserSession.getRefreshToken();o&&o.getToken()?i.refreshSession(o,s,n.clientMetadata):s();})},e.getUserData=function(n,i){var s=this;if(!(this.signInUserSession!=null&&this.signInUserSession.isValid()))return this.clearCachedUserData(),n(new Error("User is not authenticated"),null);var o=this.getUserDataFromCache();if(!o){this.fetchUserData().then(function(a){n(null,a);}).catch(n);return}if(this.isFetchUserDataAndTokenRequired(i)){this.fetchUserData().then(function(a){return s.refreshSessionIfPossible(i).then(function(){return a})}).then(function(a){return n(null,a)}).catch(n);return}try{n(null,JSON.parse(o));return}catch(a){this.clearCachedUserData(),n(a,null);return}},e.getUserDataFromCache=function(){var n=this.storage.getItem(this.userDataKey);return n},e.isFetchUserDataAndTokenRequired=function(n){var i=n||{},s=i.bypassCache,o=s===void 0?false:s;return o},e.fetchUserData=function(){var n=this;return this.createGetUserRequest().then(function(i){return n.cacheUserData(i),i})},e.deleteAttributes=function(n,i){var s=this;if(!(this.signInUserSession!=null&&this.signInUserSession.isValid()))return i(new Error("User is not authenticated"),null);this.client.request("DeleteUserAttributes",{UserAttributeNames:n,AccessToken:this.signInUserSession.getAccessToken().getJwtToken()},function(o){return o?i(o,null):s.getUserData(function(){return i(null,"SUCCESS")},{bypassCache:true})});},e.resendConfirmationCode=function(n,i){var s={ClientId:this.pool.getClientId(),Username:this.username,ClientMetadata:i};this.client.request("ResendConfirmationCode",s,function(o,a){return o?n(o,null):n(null,a)});},e.getSession=function(n,i){if(i===void 0&&(i={}),this.username==null)return n(new Error("Username is null. Cannot retrieve a new session"),null);if(this.signInUserSession!=null&&this.signInUserSession.isValid())return n(null,this.signInUserSession);var s="CognitoIdentityServiceProvider."+this.pool.getClientId()+"."+this.username,o=s+".idToken",a=s+".accessToken",u=s+".refreshToken",c=s+".clockDrift";if(this.storage.getItem(o)){var d=new Ve({IdToken:this.storage.getItem(o)}),l=new Me({AccessToken:this.storage.getItem(a)}),g=new qe({RefreshToken:this.storage.getItem(u)}),p=parseInt(this.storage.getItem(c),0)||0,h={IdToken:d,AccessToken:l,RefreshToken:g,ClockDrift:p},b=new Be(h);if(b.isValid())return this.signInUserSession=b,n(null,this.signInUserSession);if(!g.getToken())return n(new Error("Cannot retrieve a new session. Please authenticate."),null);this.refreshSession(g,n,i.clientMetadata);}else n(new Error("Local storage is missing an ID Token, Please authenticate"),null);},e.refreshSession=function(n,i,s){var o=this,a=this.pool.wrapRefreshSessionCallback?this.pool.wrapRefreshSessionCallback(i):i,u={};u.REFRESH_TOKEN=n.getToken();var c="CognitoIdentityServiceProvider."+this.pool.getClientId(),d=c+".LastAuthUser";if(this.storage.getItem(d)){this.username=this.storage.getItem(d);var l=c+"."+this.username+".deviceKey";this.deviceKey=this.storage.getItem(l),u.DEVICE_KEY=this.deviceKey;}var g={ClientId:this.pool.getClientId(),AuthFlow:"REFRESH_TOKEN_AUTH",AuthParameters:u,ClientMetadata:s};this.getUserContextData()&&(g.UserContextData=this.getUserContextData()),this.client.requestWithRetry("InitiateAuth",g,function(p,h){if(p)return p.code==="NotAuthorizedException"&&o.clearCachedUser(),a(p,null);if(h){var b=h.AuthenticationResult;return Object.prototype.hasOwnProperty.call(b,"RefreshToken")||(b.RefreshToken=n.getToken()),o.signInUserSession=o.getCognitoUserSession(b),o.cacheTokens(),a(null,o.signInUserSession)}});},e.cacheTokens=function(){var n="CognitoIdentityServiceProvider."+this.pool.getClientId(),i=n+"."+this.username+".idToken",s=n+"."+this.username+".accessToken",o=n+"."+this.username+".refreshToken",a=n+"."+this.username+".clockDrift",u=n+".LastAuthUser";this.storage.setItem(i,this.signInUserSession.getIdToken().getJwtToken()),this.storage.setItem(s,this.signInUserSession.getAccessToken().getJwtToken()),this.storage.setItem(o,this.signInUserSession.getRefreshToken().getToken()),this.storage.setItem(a,""+this.signInUserSession.getClockDrift()),this.storage.setItem(u,this.username);},e.cacheUserData=function(n){this.storage.setItem(this.userDataKey,JSON.stringify(n));},e.clearCachedUserData=function(){this.storage.removeItem(this.userDataKey);},e.clearCachedUser=function(){this.clearCachedTokens(),this.clearCachedUserData();},e.cacheDeviceKeyAndPassword=function(){var n="CognitoIdentityServiceProvider."+this.pool.getClientId()+"."+this.username,i=n+".deviceKey",s=n+".randomPasswordKey",o=n+".deviceGroupKey";this.storage.setItem(i,this.deviceKey),this.storage.setItem(s,this.randomPassword),this.storage.setItem(o,this.deviceGroupKey);},e.getCachedDeviceKeyAndPassword=function(){var n="CognitoIdentityServiceProvider."+this.pool.getClientId()+"."+this.username,i=n+".deviceKey",s=n+".randomPasswordKey",o=n+".deviceGroupKey";this.storage.getItem(i)&&(this.deviceKey=this.storage.getItem(i),this.randomPassword=this.storage.getItem(s),this.deviceGroupKey=this.storage.getItem(o));},e.clearCachedDeviceKeyAndPassword=function(){var n="CognitoIdentityServiceProvider."+this.pool.getClientId()+"."+this.username,i=n+".deviceKey",s=n+".randomPasswordKey",o=n+".deviceGroupKey";this.storage.removeItem(i),this.storage.removeItem(s),this.storage.removeItem(o);},e.clearCachedTokens=function(){var n="CognitoIdentityServiceProvider."+this.pool.getClientId(),i=n+"."+this.username+".idToken",s=n+"."+this.username+".accessToken",o=n+"."+this.username+".refreshToken",a=n+".LastAuthUser",u=n+"."+this.username+".clockDrift";this.storage.removeItem(i),this.storage.removeItem(s),this.storage.removeItem(o),this.storage.removeItem(a),this.storage.removeItem(u);},e.getCognitoUserSession=function(n){var i=new Ve(n),s=new Me(n),o=new qe(n),a={IdToken:i,AccessToken:s,RefreshToken:o};return new Be(a)},e.forgotPassword=function(n,i){var s={ClientId:this.pool.getClientId(),Username:this.username,ClientMetadata:i};this.getUserContextData()&&(s.UserContextData=this.getUserContextData()),this.client.request("ForgotPassword",s,function(o,a){return o?n.onFailure(o):typeof n.inputVerificationCode=="function"?n.inputVerificationCode(a):n.onSuccess(a)});},e.confirmPassword=function(n,i,s,o){var a={ClientId:this.pool.getClientId(),Username:this.username,ConfirmationCode:n,Password:i,ClientMetadata:o};this.getUserContextData()&&(a.UserContextData=this.getUserContextData()),this.client.request("ConfirmForgotPassword",a,function(u){return u?s.onFailure(u):s.onSuccess("SUCCESS")});},e.getAttributeVerificationCode=function(n,i,s){if(this.signInUserSession==null||!this.signInUserSession.isValid())return i.onFailure(new Error("User is not authenticated"));this.client.request("GetUserAttributeVerificationCode",{AttributeName:n,AccessToken:this.signInUserSession.getAccessToken().getJwtToken(),ClientMetadata:s},function(o,a){return o?i.onFailure(o):typeof i.inputVerificationCode=="function"?i.inputVerificationCode(a):i.onSuccess("SUCCESS")});},e.verifyAttribute=function(n,i,s){if(this.signInUserSession==null||!this.signInUserSession.isValid())return s.onFailure(new Error("User is not authenticated"));this.client.request("VerifyUserAttribute",{AttributeName:n,Code:i,AccessToken:this.signInUserSession.getAccessToken().getJwtToken()},function(o){return o?s.onFailure(o):s.onSuccess("SUCCESS")});},e.getDevice=function(n){if(this.signInUserSession==null||!this.signInUserSession.isValid())return n.onFailure(new Error("User is not authenticated"));this.client.request("GetDevice",{AccessToken:this.signInUserSession.getAccessToken().getJwtToken(),DeviceKey:this.deviceKey},function(i,s){return i?n.onFailure(i):n.onSuccess(s)});},e.forgetSpecificDevice=function(n,i){if(this.signInUserSession==null||!this.signInUserSession.isValid())return i.onFailure(new Error("User is not authenticated"));this.client.request("ForgetDevice",{AccessToken:this.signInUserSession.getAccessToken().getJwtToken(),DeviceKey:n},function(s){return s?i.onFailure(s):i.onSuccess("SUCCESS")});},e.forgetDevice=function(n){var i=this;this.forgetSpecificDevice(this.deviceKey,{onFailure:n.onFailure,onSuccess:function(o){return i.deviceKey=null,i.deviceGroupKey=null,i.randomPassword=null,i.clearCachedDeviceKeyAndPassword(),n.onSuccess(o)}});},e.setDeviceStatusRemembered=function(n){if(this.signInUserSession==null||!this.signInUserSession.isValid())return n.onFailure(new Error("User is not authenticated"));this.client.request("UpdateDeviceStatus",{AccessToken:this.signInUserSession.getAccessToken().getJwtToken(),DeviceKey:this.deviceKey,DeviceRememberedStatus:"remembered"},function(i){return i?n.onFailure(i):n.onSuccess("SUCCESS")});},e.setDeviceStatusNotRemembered=function(n){if(this.signInUserSession==null||!this.signInUserSession.isValid())return n.onFailure(new Error("User is not authenticated"));this.client.request("UpdateDeviceStatus",{AccessToken:this.signInUserSession.getAccessToken().getJwtToken(),DeviceKey:this.deviceKey,DeviceRememberedStatus:"not_remembered"},function(i){return i?n.onFailure(i):n.onSuccess("SUCCESS")});},e.listDevices=function(n,i,s){if(this.signInUserSession==null||!this.signInUserSession.isValid())return s.onFailure(new Error("User is not authenticated"));var o={AccessToken:this.signInUserSession.getAccessToken().getJwtToken(),Limit:n};i&&(o.PaginationToken=i),this.client.request("ListDevices",o,function(a,u){return a?s.onFailure(a):s.onSuccess(u)});},e.globalSignOut=function(n){var i=this;if(this.signInUserSession==null||!this.signInUserSession.isValid())return n.onFailure(new Error("User is not authenticated"));this.client.request("GlobalSignOut",{AccessToken:this.signInUserSession.getAccessToken().getJwtToken()},function(s){return s?n.onFailure(s):(i.clearCachedUser(),n.onSuccess("SUCCESS"))});},e.signOut=function(n){var i=this;if(!n||typeof n!="function"){this.cleanClientData();return}this.getSession(function(s,o){if(s)return n(s);i.revokeTokens(function(a){i.cleanClientData(),n(a);});});},e.revokeTokens=function(n){if(n===void 0&&(n=function(){}),typeof n!="function")throw new Error("Invalid revokeTokenCallback. It should be a function.");if(!this.signInUserSession){var s=new Error("User is not authenticated");return n(s)}if(!this.signInUserSession.getAccessToken()){var o=new Error("No Access token available");return n(o)}var a=this.signInUserSession.getRefreshToken().getToken(),u=this.signInUserSession.getAccessToken();if(this.isSessionRevocable(u)&&a)return this.revokeToken({token:a,callback:n});n();},e.isSessionRevocable=function(n){if(n&&typeof n.decodePayload=="function")try{var i=n.decodePayload(),s=i.origin_jti;return !!s}catch{}return false},e.cleanClientData=function(){this.signInUserSession=null,this.clearCachedUser();},e.revokeToken=function(n){var i=n.token,s=n.callback;this.client.requestWithRetry("RevokeToken",{Token:i,ClientId:this.pool.getClientId()},function(o){if(o)return s(o);s();});},e.sendMFASelectionAnswer=function(n,i){var s=this,o={};o.USERNAME=this.username,o.ANSWER=n;var a={ChallengeName:"SELECT_MFA_TYPE",ChallengeResponses:o,ClientId:this.pool.getClientId(),Session:this.Session};this.getUserContextData()&&(a.UserContextData=this.getUserContextData()),this.client.request("RespondToAuthChallenge",a,function(u,c){if(u)return i.onFailure(u);if(s.Session=c.Session,n==="SMS_MFA")return i.mfaRequired(c.ChallengeName,c.ChallengeParameters);if(n==="SOFTWARE_TOKEN_MFA")return i.totpRequired(c.ChallengeName,c.ChallengeParameters)});},e.getUserContextData=function(){var n=this.pool;return n.getUserContextData(this.username)},e.associateSoftwareToken=function(n){var i=this;this.signInUserSession!=null&&this.signInUserSession.isValid()?this.client.request("AssociateSoftwareToken",{AccessToken:this.signInUserSession.getAccessToken().getJwtToken()},function(s,o){return s?n.onFailure(s):n.associateSecretCode(o.SecretCode)}):this.client.request("AssociateSoftwareToken",{Session:this.Session},function(s,o){return s?n.onFailure(s):(i.Session=o.Session,n.associateSecretCode(o.SecretCode))});},e.verifySoftwareToken=function(n,i,s){var o=this;this.signInUserSession!=null&&this.signInUserSession.isValid()?this.client.request("VerifySoftwareToken",{AccessToken:this.signInUserSession.getAccessToken().getJwtToken(),UserCode:n,FriendlyDeviceName:i},function(a,u){return a?s.onFailure(a):s.onSuccess(u)}):this.client.request("VerifySoftwareToken",{Session:this.Session,UserCode:n,FriendlyDeviceName:i},function(a,u){if(a)return s.onFailure(a);o.Session=u.Session;var c={};c.USERNAME=o.username;var d={ChallengeName:"MFA_SETUP",ClientId:o.pool.getClientId(),ChallengeResponses:c,Session:o.Session};o.getUserContextData()&&(d.UserContextData=o.getUserContextData()),o.client.request("RespondToAuthChallenge",d,function(l,g){return l?s.onFailure(l):(o.signInUserSession=o.getCognitoUserSession(g.AuthenticationResult),o.cacheTokens(),s.onSuccess(o.signInUserSession))});});},r})();Te(Dn());function $e(){}$e.prototype.userAgent=xn();var kn=function(e){var t=$e.category?" "+$e.category:"",n=$e.framework?" framework/"+$e.framework:"",i=""+$e.prototype.userAgent+t+n;return i};function za(r,e){r.prototype=Object.create(e.prototype),r.prototype.constructor=r,Ge(r,e);}function mr(r){var e=typeof Map=="function"?new Map:void 0;return mr=function(n){if(n===null||!Xa(n))return n;if(typeof n!="function")throw new TypeError("Super expression must either be null or a function");if(e!==void 0){if(e.has(n))return e.get(n);e.set(n,i);}function i(){return Ya(n,arguments,_r(this).constructor)}return i.prototype=Object.create(n.prototype,{constructor:{value:i,enumerable:false,writable:true,configurable:true}}),Ge(i,n)},mr(r)}function Ya(r,e,t){if(Nn())return Reflect.construct.apply(null,arguments);var n=[null];n.push.apply(n,e);var i=new(r.bind.apply(r,n));return t&&Ge(i,t.prototype),i}function Nn(){try{var r=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}));}catch{}return (Nn=function(){return !!r})()}function Xa(r){try{return Function.toString.call(r).indexOf("[native code]")!==-1}catch{return typeof r=="function"}}function Ge(r,e){return Ge=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,n){return t.__proto__=n,t},Ge(r,e)}function _r(r){return _r=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},_r(r)}var Za=(function(r){function e(t,n,i,s){var o;return o=r.call(this,t)||this,o.code=n,o.name=i,o.statusCode=s,o}return za(e,r),e})(mr(Error)),Fn=(function(){function r(t,n,i){this.endpoint=n||"https://cognito-idp."+t+".amazonaws.com/";var s=i||{},o=s.credentials;this.fetchOptions=o?{credentials:o}:{};}var e=r.prototype;return e.promisifyRequest=function(n,i){var s=this;return new Promise(function(o,a){s.request(n,i,function(u,c){u?a(new Za(u.message,u.code,u.name,u.statusCode)):o(c);});})},e.requestWithRetry=function(n,i,s){var o=this,a=5*1e3;nu(function(u){return new Promise(function(c,d){o.request(n,u,function(l,g){l?d(l):c(g);});})},[i],a).then(function(u){return s(null,u)}).catch(function(u){return s(u)});},e.request=function(n,i,s){var o={"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":"AWSCognitoIdentityProviderService."+n,"X-Amz-User-Agent":kn(),"Cache-Control":"no-store"},a=Object.assign({},this.fetchOptions,{headers:o,method:"POST",mode:"cors",body:JSON.stringify(i)}),u;fetch(this.endpoint,a).then(function(d){return u=d,d},function(d){throw d instanceof TypeError?new Error("Network error"):d}).then(function(d){return d.json().catch(function(){return {}})}).then(function(d){if(u.ok)return s(null,d);var l=(d.__type||d.code).split("#").pop(),g=new Error(d.message||d.Message||null);return g.name=l,g.code=l,s(g)}).catch(function(d){if(u&&u.headers&&u.headers.get("x-amzn-errortype"))try{var l=u.headers.get("x-amzn-errortype").split(":")[0],g=new Error(u.status?u.status.toString():null);return g.code=l,g.name=l,g.statusCode=u.status,s(g)}catch{return s(d)}else d instanceof Error&&d.message==="Network error"&&(d.code="NetworkError");return s(d)});},r})();var Rt={debug:function(){}};var eu=function(e){var t="nonRetryable";return e&&e[t]};function Ln(r,e,t,n){if(n===void 0&&(n=1),typeof r!="function")throw Error("functionToRetry must be a function");return Rt.debug(r.name+" attempt #"+n+" with args: "+JSON.stringify(e)),r.apply(void 0,e).catch(function(i){if(Rt.debug("error on "+r.name,i),eu(i))throw Rt.debug(r.name+" non retryable error",i),i;var s=t(n,e,i);if(Rt.debug(r.name+" retrying in "+s+" ms"),s!==false)return new Promise(function(o){return setTimeout(o,s)}).then(function(){return Ln(r,e,t,n+1)});throw i})}function tu(r){var e=100,t=100;return function(n){var i=Math.pow(2,n)*e+t*Math.random();return i>r?false:i}}function nu(r,e,t){return Ln(r,e,tu(t))}var iu=55,br=(function(){function r(t,n){var i=t||{},s=i.UserPoolId,o=i.ClientId,a=i.endpoint,u=i.fetchOptions,c=i.AdvancedSecurityDataCollectionFlag;if(!s||!o)throw new Error("Both UserPoolId and ClientId are required.");if(s.length>iu||!/^[\w-]+_[0-9a-zA-Z]+$/.test(s))throw new Error("Invalid UserPoolId format.");var d=s.split("_")[0];this.userPoolId=s,this.clientId=o,this.client=new Fn(d,a,u),this.advancedSecurityDataCollectionFlag=c!==false,this.storage=t.Storage||new Tt().getStorage(),n&&(this.wrapRefreshSessionCallback=n);}var e=r.prototype;return e.getUserPoolId=function(){return this.userPoolId},e.getUserPoolName=function(){return this.getUserPoolId().split("_")[1]},e.getClientId=function(){return this.clientId},e.signUp=function(n,i,s,o,a,u){var c=this,d={ClientId:this.clientId,Username:n,Password:i,UserAttributes:s,ValidationData:o,ClientMetadata:u};this.getUserContextData(n)&&(d.UserContextData=this.getUserContextData(n)),this.client.request("SignUp",d,function(l,g){if(l)return a(l,null);var p={Username:n,Pool:c,Storage:c.storage},h={user:new me(p),userConfirmed:g.UserConfirmed,userSub:g.UserSub,codeDeliveryDetails:g.CodeDeliveryDetails};return a(null,h)});},e.getCurrentUser=function(){var n="CognitoIdentityServiceProvider."+this.clientId+".LastAuthUser",i=this.storage.getItem(n);if(i){var s={Username:i,Pool:this,Storage:this.storage};return new me(s)}return null},e.getUserContextData=function(n){if(!(typeof AmazonCognitoAdvancedSecurityData>"u")){var i=AmazonCognitoAdvancedSecurityData;if(this.advancedSecurityDataCollectionFlag){var s=i.getData(n,this.userPoolId,this.clientId);if(s){var o={EncodedData:s};return o}}return {}}},r})();Te(Vn());var f=class extends Error{constructor(e,t){if(Array.isArray(e)&&e.length<=2){let n=e[1];if(e.length>2)for(let i=2;i<e.length&&typeof e[i]=="string";i++)n+=e[i];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||(typeof e=="string"?e:"Something went wrong.")).trim()),typeof e=="string"?(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)):typeof e=="object"&&e?.code&&e?.message&&(this.name=t?.name||"SKAPI",this.code=t?.code||"ERROR",this.cause=e?.cause);}};var _e="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",wr=BigInt(_e.length),su=2*1024*1024,ou=["aud","cognito:username","event_id","exp","iat","iss","jti","origin_jti","secret_key","token_use"],qn={auth_time:"log",sub:"user_id"},au=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f","g","h","i","j","k","l"],Hn=["us31","us72","ap51","ap22","ap41","eu71","ap21","us32","us71","af51","ap31","ap43","ap23","ap42","ca01","eu01","eu72","eu51","eu73","eu11","me51","sa31"],Bn=typeof TextEncoder<"u"?new TextEncoder:null;function uu(){if(typeof globalThis<"u")return globalThis.Buffer}function cu(r){if(Bn)return Bn.encode(r);let e=unescape(encodeURIComponent(r)),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}function lu(r){if(r instanceof Uint8Array)return r;if(typeof r=="string")return cu(r);if(typeof ArrayBuffer<"u"&&r instanceof ArrayBuffer)return new Uint8Array(r);if(typeof ArrayBuffer<"u"&&ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);if(Array.isArray(r))return Uint8Array.from(r);let e=uu();if(e)return new Uint8Array(e.from(r));throw new Error("No byte conversion available in this environment.")}var A=class A{static hash(e){typeof e!="string"&&(console.warn("coercing non-string value to empty string"),e="");let t=A.sb(e),n=1732584193,i=-271733879,s=-1732584194,o=271733878,a,u,c,d;for(let l=0;l<t.length;l+=16)a=n,u=i,c=s,d=o,n=A.ff(n,i,s,o,t[l],7,-680876936),o=A.ff(o,n,i,s,t[l+1],12,-389564586),s=A.ff(s,o,n,i,t[l+2],17,606105819),i=A.ff(i,s,o,n,t[l+3],22,-1044525330),n=A.ff(n,i,s,o,t[l+4],7,-176418897),o=A.ff(o,n,i,s,t[l+5],12,1200080426),s=A.ff(s,o,n,i,t[l+6],17,-1473231341),i=A.ff(i,s,o,n,t[l+7],22,-45705983),n=A.ff(n,i,s,o,t[l+8],7,1770035416),o=A.ff(o,n,i,s,t[l+9],12,-1958414417),s=A.ff(s,o,n,i,t[l+10],17,-42063),i=A.ff(i,s,o,n,t[l+11],22,-1990404162),n=A.ff(n,i,s,o,t[l+12],7,1804603682),o=A.ff(o,n,i,s,t[l+13],12,-40341101),s=A.ff(s,o,n,i,t[l+14],17,-1502002290),i=A.ff(i,s,o,n,t[l+15],22,1236535329),n=A.gg(n,i,s,o,t[l+1],5,-165796510),o=A.gg(o,n,i,s,t[l+6],9,-1069501632),s=A.gg(s,o,n,i,t[l+11],14,643717713),i=A.gg(i,s,o,n,t[l],20,-373897302),n=A.gg(n,i,s,o,t[l+5],5,-701558691),o=A.gg(o,n,i,s,t[l+10],9,38016083),s=A.gg(s,o,n,i,t[l+15],14,-660478335),i=A.gg(i,s,o,n,t[l+4],20,-405537848),n=A.gg(n,i,s,o,t[l+9],5,568446438),o=A.gg(o,n,i,s,t[l+14],9,-1019803690),s=A.gg(s,o,n,i,t[l+3],14,-187363961),i=A.gg(i,s,o,n,t[l+8],20,1163531501),n=A.gg(n,i,s,o,t[l+13],5,-1444681467),o=A.gg(o,n,i,s,t[l+2],9,-51403784),s=A.gg(s,o,n,i,t[l+7],14,1735328473),i=A.gg(i,s,o,n,t[l+12],20,-1926607734),n=A.hh(n,i,s,o,t[l+5],4,-378558),o=A.hh(o,n,i,s,t[l+8],11,-2022574463),s=A.hh(s,o,n,i,t[l+11],16,1839030562),i=A.hh(i,s,o,n,t[l+14],23,-35309556),n=A.hh(n,i,s,o,t[l+1],4,-1530992060),o=A.hh(o,n,i,s,t[l+4],11,1272893353),s=A.hh(s,o,n,i,t[l+7],16,-155497632),i=A.hh(i,s,o,n,t[l+10],23,-1094730640),n=A.hh(n,i,s,o,t[l+13],4,681279174),o=A.hh(o,n,i,s,t[l],11,-358537222),s=A.hh(s,o,n,i,t[l+3],16,-722521979),i=A.hh(i,s,o,n,t[l+6],23,76029189),n=A.hh(n,i,s,o,t[l+9],4,-640364487),o=A.hh(o,n,i,s,t[l+12],11,-421815835),s=A.hh(s,o,n,i,t[l+15],16,530742520),i=A.hh(i,s,o,n,t[l+2],23,-995338651),n=A.ii(n,i,s,o,t[l],6,-198630844),o=A.ii(o,n,i,s,t[l+7],10,1126891415),s=A.ii(s,o,n,i,t[l+14],15,-1416354905),i=A.ii(i,s,o,n,t[l+5],21,-57434055),n=A.ii(n,i,s,o,t[l+12],6,1700485571),o=A.ii(o,n,i,s,t[l+3],10,-1894986606),s=A.ii(s,o,n,i,t[l+10],15,-1051523),i=A.ii(i,s,o,n,t[l+1],21,-2054922799),n=A.ii(n,i,s,o,t[l+8],6,1873313359),o=A.ii(o,n,i,s,t[l+15],10,-30611744),s=A.ii(s,o,n,i,t[l+6],15,-1560198380),i=A.ii(i,s,o,n,t[l+13],21,1309151649),n=A.ii(n,i,s,o,t[l+4],6,-145523070),o=A.ii(o,n,i,s,t[l+11],10,-1120210379),s=A.ii(s,o,n,i,t[l+2],15,718787259),i=A.ii(i,s,o,n,t[l+9],21,-343485551),n=A.ad(n,a),i=A.ad(i,u),s=A.ad(s,c),o=A.ad(o,d);return A.rh(n)+A.rh(i)+A.rh(s)+A.rh(o)}static rh(e){let t="";for(let n=0;n<=3;n++)t+=A.alphabet.charAt(e>>n*8+4&15)+A.alphabet.charAt(e>>n*8&15);return t}static ad(e,t){let n=(e&65535)+(t&65535);return (e>>16)+(t>>16)+(n>>16)<<16|n&65535}static rl(e,t){return e<<t|e>>>32-t}static cm(e,t,n,i,s,o){return A.ad(A.rl(A.ad(A.ad(t,e),A.ad(i,o)),s),n)}static ff(e,t,n,i,s,o,a){return A.cm(t&n|~t&i,e,t,s,o,a)}static gg(e,t,n,i,s,o,a){return A.cm(t&i|n&~i,e,t,s,o,a)}static hh(e,t,n,i,s,o,a){return A.cm(t^n^i,e,t,s,o,a)}static ii(e,t,n,i,s,o,a){return A.cm(n^(t|~i),e,t,s,o,a)}static sb(e){let t,n=(e.length+8>>6)+1,i=new Array(n*16);for(t=0;t<n*16;t++)i[t]=0;for(t=0;t<e.length;t++)i[t>>2]|=e.charCodeAt(t)<<t%4*8;return i[t>>2]|=128<<t%4*8,i[n*16-2]=e.length*8,i}};A.alphabet="0123456789abcdef";var Q=A;function Wn(r){if(r===0)return _e[0];let e="";for(;r>0;)e=_e[r%62]+e,r=Math.floor(r/62);return e}function ne(r){return r.split("").reverse().reduce((e,t,n)=>e+_e.indexOf(t)*62**n,0)}function Qe(r=6){let e="",t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n=t.length,i=0;for(;i<r;)e+=t.charAt(Math.floor(Math.random()*n)),i+=1;return e}function Ar(){return typeof window>"u"||!!window?._runningInNodeJS}function z(){return !Ar()&&typeof document<"u"&&typeof document.createElement=="function"}function It(r){let e;try{e=JSON.stringify(r);}catch{throw new f("Invalid data type.",{code:"INVALID_REQUEST"})}if(new Blob([e]).size>su)throw new f("Data should not exceed 2MB",{code:"INVALID_REQUEST"})}function $n(r){return r===""||r==="on"||r==="true"}function jn(r){return r==="false"}function Kn(r,e,t){e.name&&t(r,e.name,e.value);}var Pt=z(),du=typeof SubmitEvent<"u",fu=typeof HTMLFormElement<"u";function L(r,e,t){let n={},i=[];function s(u,c,d){if(e?.ignoreEmpty&&d==="")return;if(e?.nullIfEmpty&&d===""&&(d=null),typeof t=="function"){let p=t(c,d);p!==void 0&&(d=p);}let l=c.split("[").map(p=>{let h=p.replace("]",""),b=Number(h);return !isNaN(b)&&!h.includes(".")?h=b:(h[0]==='"'&&h[h.length-1]==='"'||h[0]==="'"&&h[h.length-1]==="'")&&(h=h.replace(/"/g,"").replace(/'/g,"")),h}),g=u;if(typeof l[0]=="number")throw new f("Form key cannot start with an array index.",{code:"INVALID_REQUEST"});for(let p=0;p<l.length;p++){let h=l[p];p<l.length-1?(g[h]===void 0&&(typeof l[p+1]=="number"?g[h]=[]:g[h]={}),g=g[h]):g[h]===void 0?g[h]=d:Array.isArray(g[h])?g[h].push(d):g[h]=[g[h],d];}}function o(u,c,d){if(d instanceof File)u.push({name:c,file:d});else if(d instanceof FileList&&d&&d.length>0)for(let l=0;l<=d.length-1;l++){let g=d.item(l);g&&u.push({name:c,file:g});}}let a=u=>{u.name&&(u.type==="number"?u.value&&s(n,u.name,Number(u.value)):u.type==="checkbox"||u.type==="radio"?u.checked?u.type==="checkbox"&&u.value===""||$n(u.value)?s(n,u.name,true):jn(u.value)?s(n,u.name,false):u.value&&s(n,u.name,u.value):u.type==="checkbox"&&($n(u.value)?s(n,u.name,false):jn(u.value)&&s(n,u.name,true)):u.type==="file"?u.files&&u.files.length>0&&o(i,u.name,u.files):s(n,u.name,u.value));};if(Pt&&(r instanceof HTMLInputElement||r instanceof HTMLSelectElement||r instanceof HTMLTextAreaElement))return a(r),It(n),{data:n,files:i};if(Pt&&r instanceof FormData){for(let u of r.entries()){let c=u[0],d=u[1];if(d instanceof File||d instanceof FileList)o(i,c,d);else if(d instanceof Blob){let l=d;if(l.type==="application/json")try{let g=JSON.parse(l.text());s(n,c,g);}catch{s(n,c,l);}}else s(n,c,d);}return It(n),{data:n,files:i}}if(Pt&&du&&r instanceof SubmitEvent&&(r=r.target),Pt&&fu&&r instanceof HTMLFormElement){let u=r.querySelectorAll("input"),c=r.querySelectorAll("select"),d=r.querySelectorAll("textarea");for(let l=0;l<c.length;l++)Kn(n,c[l],s);for(let l=0;l<d.length;l++)Kn(n,d[l],s);for(let l=0;l<u.length;l++)a(u[l]);return It(n),{data:n,files:i}}return It(r),{data:r,files:i}}function ze(r){let e={};for(let t in r){let n=r[t];if(!ou.includes(t))if(qn[t])e[qn[t]]=n;else if(t.includes("custom:"))e[t.replace("custom:","")]=n;else if(t==="address"){let i=n;if(i&&typeof i=="object"&&Object.keys(i).length){if(i?.formatted)try{e[t]=JSON.parse(i.formatted);}catch{e[t]=i.formatted;}}else e[t]=i;}else e[t]=n;}for(let t of ["address_public","birthdate_public","email_public","gender_public","phone_number_public","access_group"])t.includes("_public")?e.hasOwnProperty(t.split("_")[0])?e[t]=e.hasOwnProperty(t)?!!Number(e[t]):false:delete e[t]:e[t]=e.hasOwnProperty(t)?Number(e[t]):0;for(let t of ["email","phone_number"])e.hasOwnProperty(t)?e[t+"_verified"]=e[t+"_verified"]===true:delete e[t+"_verified"];return e}function Er(r){if(r=wu(r),r.split("-").length===7){let e=r.split("-"),t,n;try{t=Hn[ne(e[1][0])],n=e.slice(2).join("-");}catch{throw new Error("INVALID_PARAMETER: Service ID is invalid.")}if(!t)throw new Error("INVALID_PARAMETER: Service ID is invalid.");return {service:t+e[0]+e[1].slice(1),owner:n}}return {service:r,owner:""}}function Jn(r,e){let t=Hn.indexOf(r.slice(0,4)),n=au[t],s=`${r.slice(4,-4)}-${n}${r.slice(-4)}-${e}`;return yu(s)}function hu(r){let e=0n;for(let t of r){let n=_e.indexOf(t);if(n<0)throw new Error(`INVALID_PARAMETER: Invalid base62 character: ${t}`);e=e*wr+BigInt(n);}return e}function gu(r,e=1){if(r<0n)throw new Error("INVALID_PARAMETER: Negative values are not supported.");if(r===0n)return "0".repeat(Math.max(1,e));let t="",n=r;for(;n>0n;){let i=Number(n%wr);t=_e[i]+t,n/=wr;}return t.length<e&&(t="0".repeat(e-t.length)+t),t}function pu(r){if(r===0n)return Uint8Array.from([0]);let e=[],t=r;for(;t>0n;)e.push(Number(t&0xffn)),t>>=8n;return e.reverse(),Uint8Array.from(e)}function mu(r){let e=0n;for(let t of r)e=(e<<8n)+BigInt(t);return e}function _u(r){let e=String(r).replace(/-/g,"");if(!/^[0-9a-fA-F]{32}$/.test(e))throw new Error("INVALID_PARAMETER: Invalid UUID format.");let t=new Uint8Array(16);for(let n=0;n<16;n++)t[n]=parseInt(e.slice(n*2,n*2+2),16);return t}function bu(r){let e=Array.from(lu(r),t=>t.toString(16).padStart(2,"0")).join("");return [e.slice(0,8),e.slice(8,12),e.slice(12,16),e.slice(16,20),e.slice(20)].join("-")}function yu(r){let e=String(r);if(e.split("-").length===2)return e;let t=e.match(/^([0-9A-Za-z]+)-([0-9A-Za-z]+)-([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/);if(!t)throw new Error("INVALID_PARAMETER: Input must match <base62>-<base62>-<uuid>.");let[,n,i,s]=t;if(n.length<2)throw new Error("INVALID_PARAMETER: The first part must contain at least 2 characters.");if(i.length>=_e.length)throw new Error("INVALID_PARAMETER: The middle section is too long to encode.");let o=n.slice(0,2),a=n.slice(2),u=i+o,c=_e[i.length]+a+u,d=_u(s),l=gu(mu(d));return `${c}-${l}`}function wu(r){let e=String(r);if(e.split("-").length!==2)return e;let t=e.split("-");if(t.length!==2||!t[0]||!t[1])throw new Error("INVALID_PARAMETER: Corrupt compressed token.");let[n,i]=t,s=_e.indexOf(n[0]);if(s<0)throw new Error("INVALID_PARAMETER: Corrupt compressed token.");let o=n.slice(1),a=s+2;if(o.length<a)throw new Error("INVALID_PARAMETER: Corrupt compressed token.");let u=o.slice(0,o.length-a),c=o.slice(o.length-a),d=c.slice(s),l=c.slice(0,s),g=d+u;if(!/^[0-9A-Za-z]+$/.test(g)||!/^[0-9A-Za-z]+$/.test(l))throw new Error("INVALID_PARAMETER: Corrupt compressed token.");let p=hu(i),h=pu(p);if(h.length>16)throw new Error("INVALID_PARAMETER: Corrupt compressed token.");let b=new Uint8Array(16);b.set(h,16-h.length);let w=bu(b);return `${g}-${l}-${w}`}function Ye(r,e,t=[],n=null){let i=["string","number","boolean","object","array","function","null","undefined"];function s(h){return h!==null&&typeof h=="object"&&!Array.isArray(h)}function o(h){return s(h)}function a(h){return Array.isArray(h)}function u(h){return typeof h=="string"&&i.indexOf(h)!==-1}function c(h){return Array.isArray(h)?"array":h===null?"null":typeof h}function d(h){try{return JSON.stringify(h)}catch{return String(h)}}function l(h){if(u(h))return `Type<${h}>`;if(typeof h=="function")return "custom validator";try{return JSON.stringify(h,(b,w)=>typeof w=="function"?"custom validator":w)}catch{return String(h)}}function g(h,b){return b==="array"?Array.isArray(h):b==="object"?s(h):b==="null"?h===null:b==="undefined"?typeof h>"u":typeof h===b}function p(h){return n===null?h:`${n}[${h}]`}if(typeof e>"u")throw new Error('Argument "struct" is required.');if(typeof e=="function")return e(r);if(o(e)){if(!s(r))throw new Error(`Data schema does not match:
207
+ `+JSON.stringify(r,null,2));for(let h of Object.keys(e)){let b=p(h);if(Object.prototype.hasOwnProperty.call(r,h))r[h]=Ye(r[h],e[h],t,b);else {if(t.indexOf(b)!==-1)throw new Error(`Key "${b}" is required.`);let w=e[h];a(w)&&w.length>1&&typeof w[w.length-1]=="function"&&(r[h]=w[w.length-1]());}}return r}if(a(e)){let h=false;if(e.length===1&&!a(e[0])&&!o(e[0])){let b=e[0];if(!Array.isArray(r))throw new Error(`Type <${c(r)}> is invalid in "${n}". Expected a list.`);for(let w=0;w<r.length;w++){let _=r[w];if(u(b)){if(!g(_,b))throw new Error(`Type <${c(_)}> is invalid in "${n}". Expected a list of Type <${b}>.`)}else if(typeof b=="function")r[w]=b(_);else if(_!==b)throw new Error(`Value ${d(_)} is invalid in "${n}". Expected a list of ${d(b)}.`)}h=true;}else if(Array.isArray(r)&&e.every(w=>!a(w)&&w!=="array")){for(let w=0;w<r.length;w++){let _=false,R="";for(let C of e)try{r[w]=Ye(r[w],C,t,n),_=!0;break}catch(I){typeof C=="function"&&(R=I?.message||String(I));}if(!_&&R)throw new Error(R);if(!_){let C=e.map(l).join(", ");throw new Error(`${d(r[w])} is invalid in "${n}". allowed types or values are: ${C}.`)}}h=true;}else {let w="";for(let _ of e)try{r=Ye(r,_,t,n),h=!0;break}catch(R){typeof _=="function"&&(w=R?.message||String(R));}if(!h&&w)throw new Error(w)}if(!h){let b=e.map(l).join(", ");throw new Error(`${d(r)} is invalid in "${n}". allowed types or values are: ${b}.`)}return r}if(u(e)&&g(r,e)||r===e)return r;throw new Error(`${d(r)} is invalid in "${n}". allowed type or value is: ${l(e)}.`)}function Au(r,e="User ID"){let t=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;if(r){if(typeof r!="string")throw new f(`${e} should be type: string.`,{code:"INVALID_PARAMETER"});if(!r.match(t))throw new f(`${e} is invalid.`,{code:"INVALID_PARAMETER"})}else throw new f(`${e} is empty.`,{code:"INVALID_PARAMETER"});return r}function Eu(r){if(r&&(typeof r!="string"||r.charAt(0)!=="+"||isNaN(Number(r.substring(1)))))throw new f('"phone_number" is invalid. The format should be "+00123456789". Type: string.',{code:"INVALID_PARAMETER"});return r||""}function Su(r){if(r){if(typeof r!="string")throw new f('"birthdate" is invalid. The format should be "yyyy-mm-dd". Type: string.',{code:"INVALID_PARAMETER"});{let e=new RegExp(/([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))/);if(r.length!==10||r.split("-").length!==3||!e.test(r))throw new f('"birthdate" is invalid. The format should be "yyyy-mm-dd". Type: string.',{code:"INVALID_PARAMETER"})}}return r||""}function vu(r){if(r){if(typeof r!="string")throw new f('"password" should be type: string.',{code:"INVALID_PARAMETER"});if(r.length<6)throw new f('"password" should be at least 6 characters.',{code:"INVALID_PARAMETER"});if(r.length>60)throw new f('"password" can be up to 60 characters max.',{code:"INVALID_PARAMETER"})}else throw new f('"password" is required.',{code:"INVALID_PARAMETER"});return r}function Tu(r,e="email"){if(r){if(typeof r!="string")throw new f(`"${e}"should be type: string.`,{code:"INVALID_PARAMETER"});if(r.length<5)throw new f(`"${e}" should be at least 5 characters.`,{code:"INVALID_PARAMETER"});if(/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/.test(r)&&(r=r.trim(),r.split("@")[1].split(".").length>=2))return r.toLowerCase()}else throw new f(`"${e}" is required.`,{code:"INVALID_PARAMETER"});throw new f(`"${r}" is an invalid email.`,{code:"INVALID_PARAMETER"})}function Ru(r){let e=typeof window<"u",t=(()=>{let i=e&&window.location.origin||null;return i&&i.slice(-1)==="/"&&(i=i.slice(0,-1)),i})(),n=i=>{if(typeof i=="string"){if(i==="*")return "*";{let s=i.trim();if(s[0]==="/"&&t){if(t.slice(0,5)==="file:")throw new f(`"${i}" is an invalid url. Relative URL does not work on local file system. Use full URL string.`,{code:"INVALID_PARAMETER"});s=t+s;}else if(s[0]==="."&&t){if(t.slice(0,5)==="file:")throw new f(`"${i}" is an invalid url. Relative URL does not work on local file system. Use full URL string.`,{code:"INVALID_PARAMETER"});let a=e?window.location.href.split("?")[0]:"";a.slice(-1)!=="/"&&(a+="/"),s=a+s.slice(1);}let o;try{o=new URL(s);}catch{throw new f(`"${i}" is an invalid url.`,{code:"INVALID_PARAMETER"})}if(o.protocol)return o.href}}throw new f(`"${i}" is an invalid url.`,{code:"INVALID_PARAMETER"})};return Array.isArray(r)?r.map(i=>n(i)):n(r)}function Iu(r,e,t=[],n){let i=L(r,n),s=i.data;e.service="string",e.owner="string";let o={};for(let a in e)if(s&&typeof s=="object"&&!Array.isArray(s)&&s.hasOwnProperty(a))if(typeof s[a]=="function")o[a]=s[a];else try{o[a]=JSON.parse(JSON.stringify(s[a]));}catch{o[a]=s[a];}n?.precall&&n.precall({data:o,files:i?.files||[]});try{return Ye(o,e,t)}catch(a){throw new f(a.message,{code:"INVALID_PARAMETER"})}}var m={UserId:Au,PhoneNumber:Eu,Birthdate:Su,Password:vu,Email:Tu,Url:Ru,Params:Iu};var O=null;function Sr(r){let e={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"},t={};for(let n in r)if(n==="tkid"){let i=r[n].split("#");if(i.length===1){t.ticket_id=i[0];continue}t.ticket_id=i[1],t.consume_id=i[2],t.user_id=i[3];let s=i[2].slice(-4);if(t.is_test=s===":CHK",!r.stmp){let o=i[2].slice(0,-4);/^[0-9]+$/.test(o)?t.timestamp=parseInt(o,10):t.timestamp=ne(i[2].slice(0,-4));}}else e[n]?t[e[n]]=r[n]:t[n]=r[n];return t}async function Qn(r){if(!r.ticket_id)throw new f("Ticket ID is required.",{code:"INVALID_PARAMETER"});if(!r.method)throw new f('Method is required. Should be either "GET" or "POST"',{code:"INVALID_PARAMETER"});let e=r.ticket_id;await this.__connection;let t=await v.bind(this)(`https://${this.service.slice(0,4)}.${this.customApiDomain}/auth/consume/${this.service}/${this.owner}/${e}`,r?.data||{},{method:r.method,auth:!!r?.auth});return Sr(t)}async function zn(r,e){await this.__connection;let t=await v.bind(this)("ticket",Object.assign({exec:"list"},r||{}),{auth:true,fetchOptions:e});return t.list=t.list.map(Sr),t}async function Yn(r,e){await this.__connection;let t=await v.bind(this)("ticket",Object.assign({exec:"consumed"},r||{}),{auth:true,fetchOptions:e});return t.list=t.list.map(Sr),t}async function Xn(r){return v.bind(this)("register-ticket",Object.assign({exec:"reg"},r),{auth:true})}async function Zn(r){return v.bind(this)("register-ticket",Object.assign({exec:"unreg"},r),{auth:true})}async function je(){if(await this.__connection,this.session){let r=Math.floor(Date.now()/1e3),t=this.session.getIdToken().getExpiration();if(t<r){this.log("request:requesting new token",null);try{await W.bind(this)().getSession({refreshToken:!0}),this.log("request:received new tokens",{exp:this.session?.idToken?.payload?.exp,currentTime:r,expiresIn:t-r,token:this.session?.accessToken?.jwtToken,refreshToken:this.session?.refreshToken?.token});}catch(n){throw this.log("request:new token error",n),new f("User login is required.",{code:"INVALID_REQUEST"})}}else this.log("request:tokens",{exp:this.session.idToken.payload.exp,currentTime:r,expiresIn:t-r,token:this.session.accessToken.jwtToken,refreshToken:this.session.refreshToken.token});return this.session?.idToken?.jwtToken}else throw this.log("request:no session",null),be.bind(this)(),new f("User login is required.",{code:"INVALID_REQUEST"})}function Gn(r,e){return new Promise((t,n)=>{e.refreshSession(r.getRefreshToken(),(i,s)=>{this.log("getSession:refreshSessionCallback",{refreshErr:i,refreshedSession:s}),i?(be.bind(this)(),n(i)):s.isValid()?t(s):(be.bind(this)(),n(new f("Invalid session.",{code:"INVALID_REQUEST"})));});})}function W(){if(!this.userPool)throw new f("User pool is missing",{code:"INVALID_REQUEST"});let r=()=>{let s=O.getSignInUserSession().getIdToken().payload||null,o=ze(s);return this.log("normalized user attribute",o),this.__user=o,o},e=async s=>new Promise((o,a)=>{this.log("getSession:option",s);let{refreshToken:u=false,skipUserUpdateEventTrigger:c=false}=s||{};if(u&&c&&(c=false),O=this.userPool.getCurrentUser(),!O){this.log("getSession:cognitoUser",O),be.bind(this)(),a(null);return}let d=l=>{let g=l.getIdToken().payload;if(this.log("getSession:respond:sessionAttribute",g),g["custom:service"]!==this.service)throw this.log("getSession:respond","invalid service, signing out"),be.bind(this)(),new f("Invalid session.",{code:"INVALID_REQUEST"});return this.session=l,r(),c||this._runOnUserUpdateListeners(this.user),this.session};O.getSession((l,g)=>{if(this.log("getSession:getSessionCallback",{err:l,session:g}),!g){be.bind(this)(),a(new f("Current session does not exist.",{code:"INVALID_REQUEST"}));return}if(l){Gn.bind(this)(g,O).then(_=>o(d(_))).catch(a);return}let p=Math.floor(Date.now()/1e3),h=g.getIdToken(),b=h.getExpiration(),w=b<p;if(this.log("getSession:currentTime",p),this.log("getSession:idTokenExp",b),this.log("getSession:isExpired",w),this.log("getSession:existingBearerToken",this.bearerToken),this.bearerToken=h.getJwtToken(),w||u||!g.isValid())Gn.bind(this)(g,O).then(_=>o(d(_))).catch(a);else try{o(d(g));}catch(_){a(_);}});}),t=(s,o)=>{let a=o||s.includes(this.service+"-")?s:this.service+"-"+Q.hash(s);return {cognitoUser:new me({Username:a,Pool:this.userPool}),cognitoUsername:a}};return {getSession:e,authenticateUser:(s,o,a=false,u=false)=>new Promise((c,d)=>{this.__request_signup_confirmation=null,this.__disabledAccount=null;let l=t(s,a),g=l.cognitoUsername,p=new Bt({Username:g,Password:o});l.cognitoUser.authenticateUser(p,{newPasswordRequired:(h,b)=>{this.__disabledAccount=null,this.__request_signup_confirmation=g,h["custom:signup_ticket"]==="PASS"||h["custom:signup_ticket"]==="MEMBER"||h["custom:signup_ticket"]==="OIDPASS"?l.cognitoUser.completeNewPasswordChallenge(o,{},{onSuccess:w=>{O=l.cognitoUser,e().then(_=>c(this.user));},onFailure:w=>{d(new f(w.message||"Failed to authenticate user.",{code:w.code}));}}):d(new f("User's signup confirmation is required.",{code:"SIGNUP_CONFIRMATION_NEEDED"}));},onSuccess:h=>e({skipUserUpdateEventTrigger:true}).then(b=>{this.__disabledAccount=null,this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user),c(this.user);}),onFailure:h=>{let b=[],{parsed:w,code:_}=xt(h),R=typeof h?.message=="string"?h.message:"";if(_==="NotAuthorizedException"?R.includes("User is disabled.")?(this.__disabledAccount=g,b=["This account is disabled.","USER_IS_DISABLED"]):u?b=["The account already exists.","ACCOUNT_EXISTS"]:b=["Incorrect username or password.","INCORRECT_USERNAME_OR_PASSWORD"]:_==="UserNotFoundException"?b=["Incorrect username or password.","INCORRECT_USERNAME_OR_PASSWORD"]:_==="UserNotConfirmedException"?(this.__request_signup_confirmation=g,b=["User's signup confirmation is required.","SIGNUP_CONFIRMATION_NEEDED"]):(_==="TooManyRequestsException"||_==="LimitExceededException")&&(b=["Too many attempts. Please try again later.","REQUEST_EXCEED"]),w.code==="SIGNUP_CONFIRMATION_NEEDED"&&(this.__request_signup_confirmation=g),b.length){let C=b[1],I=b[0];d(new f(I,{code:C,cause:h}));}else d(w);}});}),createCognitoUser:t,signup:(s,o,a)=>new Promise((u,c)=>{this.userPool.signUp(s,o,a,null,(d,l)=>{if(d){let{parsed:g,code:p}=xt(d),h=[];p==="UsernameExistsException"?h=["The account already exists.","EXISTS"]:p==="InvalidPasswordException"?h=["Invalid password. Password must be at least 6 characters.","INVALID_PARAMETER"]:p==="InvalidParameterException"?h=[g.message||"Invalid parameter.","INVALID_PARAMETER"]:p==="TooManyRequestsException"||p==="LimitExceededException"?h=["Too many attempts. Please try again later.","REQUEST_EXCEED"]:p==="CodeDeliveryFailureException"?h=["Failed to deliver verification code.","CODE_DELIVERY_FAILURE"]:p==="UserLambdaValidationException"&&(h=[g.message||"Signup validation failed.","INVALID_REQUEST"]),h.length?c(new f(h[0],{code:h[1],cause:d})):c(g);return}u(l);});})}}function xt(r){let e=typeof r?.code=="string"&&r.code.trim()?r.code.trim():"ERROR",n=((typeof r?.message=="string"?r.message:typeof r=="string"?r:"An error occurred.")||"An error occurred.").trim();n||(n="An error occurred.");let i=n.match(/#([A-Za-z0-9_]+)\s*:\s*([\s\S]+)/),s=i?.[1]?.trim()||e,o=i?.[2]?.trim()||n;return {parsed:new f(o,{code:s,cause:r}),code:e}}async function ei(r){await this.__authConnection;let e=r?.refreshToken||false;if(!e)return this.user;try{return await W.bind(this)().getSession(Object.assign({skipUserUpdateEventTrigger:!e,refreshToken:e},r)),this.user}catch{return null}}async function ti(r){await this.__connection,r=m.Params(r,{token:"string",id:"string",merge:o=>{if(o===void 0)return false;if(typeof o=="string")return [o];if(Array.isArray(o)){for(let a of o)if(typeof a!="string")throw new f('"merge" array items should be type: <string>.',{code:"INVALID_PARAMETER"})}if(typeof o!="boolean"&&!Array.isArray(o))throw new f('"merge" should be type: <boolean | string[]>.',{code:"INVALID_PARAMETER"});return o},template:o=>{if(typeof o!="object"||o===null)throw new f('"template" should be type: <object>.',{code:"INVALID_PARAMETER"});if(o.welcome!==void 0&&(typeof o.welcome!="string"||!o.welcome))throw new f('"template.welcome" should be a non-empty <string> (template message_id).',{code:"INVALID_PARAMETER"});return o}});let e={token:r.token,id:r.id,merge:r.merge};r.template?.welcome&&(e.template_welcome=r.template.welcome);let t=await v.bind(this)("openid-logger",e),n=t.logger.split("#"),i=this.service+"-"+n[0],s=n[1];return {userProfile:await W.bind(this)().authenticateUser(i,s,true,true),openid:t.openid}}function Pu(r){let e=typeof globalThis<"u"?globalThis:void 0;if(e?.Buffer)return e.Buffer.from(r,"base64").toString("utf8");if(typeof atob=="function"){let t=atob(r),n=new Uint8Array(t.length);for(let i=0;i<t.length;i++)n[i]=t.charCodeAt(i);return typeof TextDecoder<"u"?new TextDecoder().decode(n):t}throw new Error("No base64 decoder available in this environment")}function xu(r){let e=r.split(".");if(e.length!==3)throw new Error("Invalid JWT format");let n=e[1].replace(/-/g,"+").replace(/_/g,"/"),i=Pu(n);return JSON.parse(i)}async function ri(r){await this.__authConnection,this.log("loginWithToken:params",r),r=m.Params(r,{idToken:"string",accessToken:"string",refreshToken:"string"},["idToken"]);let e=xu(r.idToken);if(this.log("loginWithToken:idTokenPayload",e),e["custom:service"]!==this.service)throw new f("Token does not belong to this service.",{code:"INVALID_REQUEST"});let t=Math.floor(Date.now()/1e3);if(e.exp&&e.exp<t)throw new f("Token has expired.",{code:"INVALID_REQUEST"});if(this.__user=ze(e),this.session=null,r.accessToken&&r.refreshToken)try{if(this.session=new Be({IdToken:new Ve({IdToken:r.idToken}),AccessToken:new Me({AccessToken:r.accessToken}),RefreshToken:new qe({RefreshToken:r.refreshToken})}),this.log("loginWithToken:session",this.session),this.log("loginWithToken:CognitoUser",me),this.log("loginWithToken:userPool",this.userPool),me&&this.userPool){this.log("loginWithToken:cognito:username",e["cognito:username"]);let n={Username:e["cognito:username"],Pool:this.userPool};this.log("loginWithToken:cognitoUserParams",n),O=new me(n),O.setSignInUserSession(this.session),this.log("loginWithToken:cognitoUserRestored",{cognitoUserType:typeof O,cognitoUserKeys:Object.keys(O||{}),cognitoUser:O});}}catch(n){this.log("loginWithToken:err",n);try{this.log("loginWithToken:err:stringified",JSON.stringify(n));}catch{this.log("loginWithToken:err:stringifyFail",String(n));}try{let i=Object.keys(n||{}),s=Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(n||{}):[],o=Object.getOwnPropertyDescriptors?Object.getOwnPropertyDescriptors(n||{}):{};this.log("loginWithToken:createSessionError:allKeys",{keys:i,symbols:s,descriptors:o});}catch(i){this.log("loginWithToken:createSessionError:allKeysFail",String(i));}}return this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user),this.user}async function J(){return await this.__connection,this.__user?.service===this.service?this.__user?.owner===this.host:(await Xe.bind(this)(),false)}async function be(r=false){let e=null;O&&(r?e=new Promise((n,i)=>{O.globalSignOut({onSuccess:s=>{this.log("globalSignOut:success",s),n(s);},onFailure:s=>{this.log("globalSignOut:error",s),i(s);}});}):O.signOut());let t={session:null,__startKeyHistory:{},__cached_requests:{},__user:null};e&&(e=await e);for(let n in t)this[n]=t[n];return this._runOnUserUpdateListeners(null),this._runOnLoginListeners(null),e}async function Xe(r){await this.__connection;let{data:e}=L(r);return await be.bind(this)(e?.global),"SUCCESS: The user has been logged out."}async function ni(){if(!this.__request_signup_confirmation)throw new f("Least one login attempt is required.",{code:"INVALID_REQUEST"});return await v.bind(this)("confirm-signup",{username:this.__request_signup_confirmation})}async function ii(r=false){if(typeof r=="string")r=m.Url(r);else if(typeof r!="boolean")throw new f("Argument should be type: <boolean | string>.",{code:"INVALID_REQUEST"});if(!this.__disabledAccount)throw new f("Least one signin attempt of disabled account is required.",{code:"INVALID_REQUEST"});return await v.bind(this)("recover-account",{username:this.__disabledAccount,redirect:r}),"SUCCESS: Recovery e-mail has been sent."}async function vr(r){let e=m.Params(r,{username:"string",email:"string",password:"string"},["password"]);if(await this.__authConnection,e.email)try{m.Email(e.email);}catch{e.username=e.email,delete e.email;}if(!e.username&&!e.email)throw new f('Least one of "username" or "email" is required.',{code:"INVALID_PARAMETER"});return await W.bind(this)().authenticateUser(e.username||e.email,e.password)}async function si(r,e){await this.__authConnection;let t={username:"string",password:c=>m.Password(c),email:c=>m.Email(c),name:"string",address:c=>{if(!c)return "";if(typeof c=="string")return c;if(typeof c=="object")return JSON.stringify(c)},gender:"string",birthdate:c=>c?m.Birthdate(c):"",phone_number:c=>c?m.PhoneNumber(c):"",email_public:["boolean",()=>false],address_public:["boolean",()=>false],gender_public:["boolean",()=>false],birthdate_public:["boolean",()=>false],phone_number_public:["boolean",()=>false],access_group:"number",misc:"string",picture:c=>c?m.Url(c):"",profile:c=>c?m.Url(c):"",family_name:"string",given_name:"string",middle_name:"string",nickname:"string",website:c=>c?m.Url(c):""},n=m.Params(r||{},t,["email","password"]);await Xe.bind(this)(),e=m.Params(e||{},{email_subscription:c=>{if(typeof c!="boolean")throw new f('"option.email_subscription" should be type: <boolean>.',{code:"INVALID_PARAMETER"});if(!e?.signup_confirmation)throw new f('"option.signup_confirmation" is required for email subscription.',{code:"INVALID_PARAMETER"});return c},signup_confirmation:c=>{let d=c;if(typeof c=="string")d=m.Url(c);else if(typeof c=="boolean")d=c;else throw new f('"option.signup_confirmation" should be type: <string | boolean>.',{code:"INVALID_PARAMETER"});if(d&&!n.email)throw new f('"email" is required for signup confirmation.',{code:"INVALID_PARAMETER"});return d},login:c=>{if(typeof c=="boolean"){if(e.signup_confirmation&&c)throw new f('"login" is not allowed when "option.signup_confirmation" is true.',{code:"INVALID_PARAMETER"});return c}throw new f('"option.login" should be type: boolean.',{code:"INVALID_PARAMETER"})},template:c=>{if(typeof c!="object"||c===null)throw new f('"option.template" should be type: <object>.',{code:"INVALID_PARAMETER"});if(c.signup_confirmation!==void 0){if(typeof c.signup_confirmation!="string"||!c.signup_confirmation)throw new f('"option.template.signup_confirmation" should be a non-empty <string> (template message_id).',{code:"INVALID_PARAMETER"});if(!e?.signup_confirmation)throw new f('"option.signup_confirmation" is required when "option.template.signup_confirmation" is set.',{code:"INVALID_PARAMETER"})}if(c.welcome!==void 0&&(typeof c.welcome!="string"||!c.welcome))throw new f('"option.template.welcome" should be a non-empty <string> (template message_id).',{code:"INVALID_PARAMETER"});return c}});let i=e?.login||false;if(n.signup_confirmation=e?.signup_confirmation||false,n.email_subscription=e?.email_subscription||false,n.email_public&&!n.signup_confirmation)throw new f('"option.signup_confirmation" should be true if "email_public" is set to true.',{code:"INVALID_PARAMETER"});n.service=this.service,n.owner=this.owner;let s=W.bind(this)().createCognitoUser(n.username||n.email);for(let c of ["email_public","address_public","gender_public","birthdate_public","phone_number_public"])n[c]=n[c]?"1":"0";n.access_group&&(n.access_group=n.access_group.toString());let o=(await v.bind(this)("signupkey",{username:s.cognitoUsername,signup_confirmation:typeof n.signup_confirmation=="boolean"?JSON.stringify(n.signup_confirmation):n.signup_confirmation,email_subscription:n.email_subscription,template_confirmation:e?.template?.signup_confirmation||"",template_welcome:e?.template?.welcome||""})).split(":"),a=o.slice(1).join(":"),u=[new ce({Name:"custom:signup",Value:o[0]}),new ce({Name:"locale",Value:a.split("#")[1]}),new ce({Name:"custom:signup_ticket",Value:a})];for(let c in t){let d=["email_public","address_public","gender_public","birthdate_public","phone_number_public","misc","service","owner"];n[c]!==""&&(c==="username"||c==="password"||c==="access_group"||(d.includes(c)?u.push(new ce({Name:"custom:"+c,Value:n[c]})):u.push(new ce({Name:c,Value:n[c]}))));}return await W.bind(this)().signup(s.cognitoUsername,n.password,u),n.signup_confirmation?(O=s.cognitoUser,this.__request_signup_confirmation=s.cognitoUsername,"SUCCESS: The account has been created. User's signup confirmation is required."):i?vr.bind(this)({email:n.username||n.email,password:n.password}):"SUCCESS: The account has been created."}async function oi(){await this.__connection;let r=await v.bind(this)("remove-account",{disable:this.__user.user_id},{auth:true});return await Xe.bind(this)(),r}async function ai(r){await this.__connection;let e=m.Params(r,{email:i=>m.Email(i),code:["number","string"],new_password:i=>m.Password(i)},["email","code","new_password"]),t=e.code,n=e.new_password;return typeof t=="number"&&(t=t.toString()),new Promise(async(i,s)=>{W.bind(this)().createCognitoUser(e.email).cognitoUser.confirmPassword(t,n,{onSuccess:a=>{i("SUCCESS: New password has been set.");},onFailure:a=>{s(new f(a?.message||"Failed to reset password.",{code:a?.code||"ERROR",cause:a}));}});})}async function ui(r,e,t){await this.__connection;let n;if(!O)throw new f("The user has to be logged in.",{code:"INVALID_REQUEST"});if(r==="email"||r==="phone_number"){if(!this.__user.hasOwnProperty(r))throw new f(`No ${r==="email"?"e-mail":"phone number"} to verify`,{code:"INVALID_REQUEST"});if(this.__user?.[`${r}_verified`])return `SUCCESS: "${r}" is verified.`;n=(e?m.Params(e,{code:"string"}):{}).code||"";}else return;let i,s=t?.template?.verification;if(s!==void 0){if(typeof s!="string"||!s)throw new f('"template.verification" should be a non-empty <string> (template message_id).',{code:"INVALID_PARAMETER"});i={template_verification:s};}return new Promise((o,a)=>{let u={onSuccess:c=>{n?W.bind(this)().getSession({refreshToken:true}).then(()=>{this.__user&&(this.__user[r+"_verified"]=true),o(`SUCCESS: "${r}" is verified.`);}).catch(d=>{a(d);}):o("SUCCESS: Verification code has been sent.");},onFailure:c=>{a(new f(c.message||"Failed to request verification code.",{code:c?.code}));}};n?O?.verifyAttribute(r,n,u):(u.inputVerificationCode=null,O?.getAttributeVerificationCode(r,u,i));})}function ci(r,e){return ui.bind(this)("phone_number",r,e)}function li(r,e){return ui.bind(this)("email",r,e)}async function di(r,e){await this.__connection;let t=m.Params(r,{email:s=>m.Email(s)},["email"]),n,i=e?.template?.verification;if(i!==void 0){if(typeof i!="string"||!i)throw new f('"template.verification" should be a non-empty <string> (template message_id).',{code:"INVALID_PARAMETER"});n={template_verification:i};}return new Promise(async(s,o)=>{W.bind(this)().createCognitoUser(t.email).cognitoUser.forgotPassword({onSuccess:u=>{s("SUCCESS: Verification code has been sent.");},onFailure:u=>{let{parsed:c,code:d}=xt(u),l={UserNotFoundException:"NOT_EXISTS",InvalidParameterException:"INVALID_PARAMETER",NotAuthorizedException:"INVALID_REQUEST",LimitExceededException:"REQUEST_EXCEED",TooManyRequestsException:"REQUEST_EXCEED",CodeDeliveryFailureException:"CODE_DELIVERY_FAILURE"}[d]||c.code||d||"ERROR";o(new f(c.message,{code:l,cause:u}));}},n);})}async function fi(r){if(await this.__connection,!this.session)throw new f("User login is required.",{code:"INVALID_REQUEST"});let e=m.Params(r,{current_password:"string",new_password:"string"});if(!e?.current_password)throw new f('"current_password" is required to change password.',{code:"INVALID_PARAMETER"});if(!e?.new_password)throw new f('"new_password" is required to change password.',{code:"INVALID_PARAMETER"});return m.Password(e.current_password),m.Password(e.new_password),new Promise((t,n)=>{O.changePassword(e.current_password,e.new_password,(i,s)=>{if(i){if(i?.code==="InvalidParameterException")n(new f("Invalid password parameter.",{code:"INVALID_PARAMETER"}));else if(i?.code==="NotAuthorizedException")n(new f("Incorrect password.",{code:"INVALID_REQUEST"}));else if(i?.code==="TooManyRequestsException"||i?.code==="LimitExceededException")n(new f("Too many attempts. Please try again later.",{code:"REQUEST_EXCEED"}));else {let{parsed:o}=xt(i);n(o);}return}t("SUCCESS: Password has been changed.");});})}async function hi(r){if(await this.__connection,!this.session)throw new f("User login is required.",{code:"INVALID_REQUEST"});let e=m.Params(r||{},{user_id:i=>m.UserId(i),email:i=>m.Email(i),address:i=>{if(!i)return "";if(typeof i=="string")return i;if(typeof i=="object")return JSON.stringify(i)},name:"string",gender:"string",birthdate:i=>i?m.Birthdate(i):"",phone_number:i=>i?m.PhoneNumber(i):"",email_public:"boolean",phone_number_public:"boolean",address_public:"boolean",gender_public:"boolean",birthdate_public:"boolean",misc:"string",picture:i=>i?m.Url(i):"",profile:i=>i?m.Url(i):"",family_name:"string",given_name:"string",middle_name:"string",nickname:"string",website:i=>i?m.Url(i):""});if(e&&typeof e=="object"&&!Object.keys(e).length)return this.user;e.email&&(e.preferred_username=this.service+"-"+Q.hash(e.email));let t=[["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 i of t)if(e[i[0]]&&!this.__user[i[1]])throw new f(`${i[2]} "${i[0]}" to true.`,{code:"INVALID_REQUEST"})}let n=[];for(let i in e){if(e[i]===this.user[i]){n.push(i);continue}if(["email_public","phone_number_public","address_public","gender_public","birthdate_public","misc"].includes(i)){let o=e[i];typeof o=="boolean"&&(o=o?"1":"0"),e["custom:"+i]=o,n.push(i);}}for(let i of n)delete e[i];if(e.user_id)if(e.user_id===this.user.user_id)delete e.user_id;else return v.bind(this)("admin-edit-profile",{attributes:e},{auth:true});if(e&&typeof e=="object"&&Object.keys(e).length){let i=[];for(let s in e)i.push(new ce({Name:s,Value:e[s]}));return await new Promise((s,o)=>{O?.updateAttributes(i,(a,u)=>{a&&o([a?.code||a?.name,a?.message||"Failed to update user settings."]),s(u);});}),await W.bind(this)().getSession({refreshToken:true}),this.user}return this.user}async function gi(r,e){r=L(r).data,r||(r={searchFor:"timestamp",condition:">",value:0},e||(e={}),e.ascending=false),await this.__connection;let t={user_id:i=>Array.isArray(i)?i.map(s=>m.UserId(s)):m.UserId(i),email:"string",phone_number:"string",locale:i=>{if(typeof i!="string"||typeof i=="string"&&i.length>5)throw new f('Value of "locale" should be a country code.',{code:"INVALID_PARAMETER"});return i},name:"string",address:"string",gender:"string",birthdate:i=>m.Birthdate(i),subscribers:"number",timestamp:"number",access_group:"number",approved:"string"},n=["searchFor","value"];if(r=m.Params(r,{searchFor:["user_id","name","email","phone_number","address","gender","birthdate","locale","subscribers","timestamp","access_group","approved"],condition:[">",">=","=","<","<=","gt","gte","eq","lt","lte",()=>"="],value:i=>{let s=t[r.searchFor];if(typeof s=="function")return s(i);if(typeof i!==s)throw new f(`Value does not match the type of "${r.searchFor}" index.`,{code:"INVALID_PARAMETER"});return i},range:i=>{let s=t[r.searchFor];if(typeof s=="function")return s(i);if(typeof i!==s)throw new f(`Range does not match the type of "${r.searchFor}" index.`,{code:"INVALID_PARAMETER"});return i}},n),r?.condition&&r?.condition!=="="&&r.hasOwnProperty("range"))throw new f("Conditions does not apply on range search.",{code:"INVALID_PARAMETER"});if(r.searchFor==="user_id"&&(r.condition!=="="||r.range))throw new f(`Conditions are not allowed on "${r.searchFor}"`,{code:"INVALID_PARAMETER"});if(typeof r?.value=="string"&&!r?.value)throw new f("Value should not be an empty string.",{code:"INVALID_PARAMETER"});if(typeof r?.searchFor=="string"&&!r?.searchFor)throw new f('"searchFor" should not be an empty string.',{code:"INVALID_PARAMETER"});return v.bind(this)("get-users",r,{auth:true,fetchOptions:e})}async function pi(r){await this.__connection;let e=await v.bind(this)("last-verified-email",r,{auth:true});return e.includes("SUCCESS")?(await W.bind(this)().getSession({refreshToken:true}),this.user):e}async function mi(r){return await this.__connection,r=m.Params(r,{username:m.Email,redirect:m.Url},["username"]),await v.bind(this)("request-username-change",r,{auth:true})}var Uu="1.1.0",Cu=class{constructor(r){fe(this,"version",Uu);fe(this,"items",[]);fe(this,"breakWhenError",false);fe(this,"batchSize",1);fe(this,"onProgress");fe(this,"activeCount",0);fe(this,"currentCycleCompleted",[]);fe(this,"stopProcessing",false);if(this.breakWhenError=!!r?.breakWhenError,this.batchSize=r?.batchSize??1,typeof this.batchSize!="number"||this.batchSize<1)throw new Error("batchSize must be at least 1");if(r?.onProgress)if(typeof r.onProgress=="function")this.onProgress=r.onProgress;else throw new Error("onProgress must be a function")}get batchToProcess(){return Math.ceil(this.items.length/this.batchSize)}add(r){let e=Array.isArray(r)?r:[r];for(let t of e){if(typeof t!="function")throw new Error("Each job must be a function that returns a Promise");this.items.push(t);}this.processNext();}processNext(){if(this.stopProcessing||this.items.length===0||this.activeCount>0)return;let r=this.items.splice(0,this.batchSize);this.activeCount=r.length,this.currentCycleCompleted=new Array(r.length),r.forEach((e,t)=>{Promise.resolve().then(()=>e()).then(n=>(this.finalizeJob(t,n,false),n)).catch(n=>(this.finalizeJob(t,n,true),n));});}finalizeJob(r,e,t){if(this.currentCycleCompleted[r]=e,this.activeCount-=1,t&&this.breakWhenError&&(this.stopProcessing=true,this.items=[]),this.activeCount!==0)return;let n=this.currentCycleCompleted.slice();this.currentCycleCompleted=[],this.onProgress&&this.onProgress({batchToProcess:this.batchToProcess,itemsToProcess:this.items.length,completed:n}),this.processNext();}terminate(){this.items=[];}},_i=Cu;var Ke=null,yi=typeof SubmitEvent<"u",Du=typeof HTMLFormElement<"u",et=z(),Tr=0;function wi(r){if(!r)return null;let e=Number(r);if(Number.isFinite(e))return Math.max(0,e*1e3);let t=Date.parse(r);return Number.isNaN(t)?null:Math.max(0,t-Date.now())}function Rr(r,e){return e>0?r/e*100:0}var bi=r=>{let{auth:e,type:t,endpoints:n}=r,i=n[0],s=n[1];if(Tr++,t==="admin"){let o=Object.entries(i).filter(([a,u])=>a.includes(e?"_private":"_public")&&a!=="get_users_private"&&a!=="service_public"&&typeof u=="string").map(([,a])=>a);if(!o.length)throw new f("No available admin gateways.",{code:"INVALID_REQUEST"});return o[Tr%o.length]}if(t==="record"){let o=Object.entries(s).filter(([a,u])=>a.includes(e?"record_private":"record_public")&&typeof u=="string").map(([,a])=>a);if(!o.length)throw new f("No available record gateways.",{code:"INVALID_REQUEST"});return o[Tr%o.length]}throw new f("Invalid gateway type.",{code:"INVALID_REQUEST"})};async function ku(r,e){let t=await Promise.all([this.admin_endpoint,this.record_endpoint]),n=t[0],i=t[1],s=r.split("?"),o=s.length>1?"?"+s[1]:"";switch(r=s[0],r){case "get-users":return n.get_users_private+r+o;case "service":return n.service_public+r+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":case "csr-poll":return bi.bind(this)({auth:e,type:"admin",endpoints:t})+r+o;case "post-record":return (e?i.post_private:i.post_public)+r+o;case "get-records":return (e?i.get_private:i.get_public)+r+o;case "del-files":case "del-records":return i.del_private+r+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 bi.bind(this)({auth:e,type:"record",endpoints:t})+r+o;default:return m.Url(r)+o}}var Ze={};function Ai(){Ke&&(Ke.terminate(),Ke=null);}async function v(r,e=null,t,n){this.log("request",{url:r,data:e,options:t,_etc:n||{}}),t=t||{};let{auth:i=false,method:s="post",bypassAwaitConnection:o=false}=t;s=s.toUpperCase();let a=null,u=e?.service||this.service,c=e?.owner||this.owner,d=null,l=await ku.bind(this)(r,!!i);if(!o&&(a=await this.__connection,!a))throw new f("Invalid connection. The service could have been disabled, or has a restricted CORS.",{code:"INVALID_REQUEST"});let g=t?.tokenHeaders?.idToken===true;(i||g)&&(d=await je.bind(this)());let p={},{fetchMore:h=false,progress:b}=t?.fetchOptions||{};if(t?.fetchOptions&&Object.keys(t.fetchOptions).length){for(let P of ["limit","startKey","ascending"])if(t.fetchOptions.hasOwnProperty(P)){if(P==="startKey"&&t.fetchOptions[P]===null)continue;p[P]=t.fetchOptions[P];}p=m.Params(p,{limit:P=>{if(typeof P!="number")throw new f("Fetch limit should be a number.",{code:"INVALID_REQUEST"});if(P>1e3)throw new f("Fetch limit should be below 1000.",{code:"INVALID_REQUEST"});return P},startKey:P=>P,ascending:"boolean"});}let w=n?.ignoreService?{}:{service:u,owner:c};Object.assign(w,p),e=L(e).data,e?e&&typeof e=="object"&&(e=Object.assign(w,e)):e=w;let _=`${s}:${i?"auth":"public"}:${r}`,R=(()=>{if(e&&typeof e=="object"&&Object.keys(e).length&&!(et&&e instanceof FormData)){let P=function(D){return typeof D=="object"&&D!==null?Object.keys(D).sort().reduce((N,F)=>(typeof D[F]=="object"&&D[F]!==null?N[F]=P(D[F]):N[F]=D[F],N),{}):D};return Q.hash(_+"/"+JSON.stringify(P(e)))}return Q.hash(_+"/"+u)})(),{requestKey:C,requestKeyWithStartKey:I}=Nu.bind(this)({params:e,url:r,fetchMore:h,hashedParams:R});if(!C||C&&typeof C=="object")return C;if(this.log("requestKey",I),typeof I=="string"&&Ze[I]instanceof Promise)return this.log("request:returning pending",I),Ze[I];let k={Accept:"*/*"};if(Object.prototype.hasOwnProperty.call(t,"contentType")&&t.contentType!==void 0){let P=t.contentType===null?"application/x-www-form-urlencoded":t.contentType;P&&(k["Content-Type"]=P);}else k["Content-Type"]="application/json";if(d&&(k.Authorization=d),t?.tokenHeaders){let P=(F,Ce)=>typeof F=="string"?F:F===true?Ce:null,D=P(t.tokenHeaders.accessToken,this.session?.accessToken?.jwtToken||null),N=P(t.tokenHeaders.idToken,this.bearerToken||this.session?.idToken?.jwtToken||d||null);D&&(k["X-Access-Token"]=D),N&&(k["X-Id-Token"]=N);}let ve={public_identifier:this.__public_identifier,service:u,owner:c};k["Content-Meta"]=JSON.stringify(ve);let V={headers:k};if(t?.responseType&&(V.responseType=t.responseType),s==="GET"){if(e){let P=[];if(et&&e instanceof FormData?P=Array.from(e.entries()).map(([D,N])=>{let F=typeof N=="string"?N:N.name;return encodeURIComponent(D)+"="+encodeURIComponent(F)}):P=Object.keys(e).map(D=>{let N=e[D];return typeof N!="string"&&(N=JSON.stringify(N)),encodeURIComponent(D)+"="+encodeURIComponent(N)}),P.length){let D=l.includes("?")?l.endsWith("?")||l.endsWith("&")?"":"&":"?";l+=D+P.join("&");}}V.body=null;}else if(et&&e instanceof FormData)V.body=e;else if(k["Content-Type"]==="application/x-www-form-urlencoded"&&e&&typeof e=="object"){let P=new URLSearchParams;for(let D of Object.keys(e)){let N=e[D];P.append(D,typeof N=="string"?N:JSON.stringify(N));}V.body=P.toString();}else typeof e=="string"?V.body=e:V.body=e?JSON.stringify(e):null;if(V.method=s,Ke===null){let P={batchSize:this.requestBatchSize,breakWhenError:false,onProgress:D=>{this.onBatchProcess.forEach(N=>N(D));}};Ke=new _i(P);}return this.log("request-opt",V),new Promise((P,D)=>{Ke.add([async()=>{let N=Ei.bind(this)(l,V,b);Ze[I]=N;try{let F=Fu.bind(this)({hashedParam:C,requestKeyWithStartKey:I,url:r,fetched:await N});return delete Ze[I],this.log("request:end",F),P(F),F}catch(F){throw delete Ze[I],this.log("request:err",F),D(F),F}}]);})}function Nu(r){let{params:e={},url:t,fetchMore:n=false,hashedParams:i}=r||{};if(e.startKey){if(!(typeof e.startKey=="object"&&Object.keys(e.startKey).length)&&e.startKey!=="start"&&e.startKey!=="end")throw new f(`"${e.startKey}" is invalid startKey key.`,{code:"INVALID_PARAMETER"});e.startKey==="start"&&(n=false,delete e.startKey);}if(!n){if(this.__cached_requests?.[t]?.[i]&&delete this.__cached_requests[t][i],this.__startKeyHistory?.[t]?.[i]){if(Array.isArray(this.__startKeyHistory[t][i])&&this.__startKeyHistory[t][i].length)for(let u of this.__startKeyHistory[t][i]){let c=i+Q.hash(u);this.__cached_requests?.[t]&&this.__cached_requests?.[t]?.[c]&&delete this.__cached_requests[t][c];}delete this.__startKeyHistory[t][i];}return {requestKeyWithStartKey:i,requestKey:i}}if(!Array.isArray(this.__startKeyHistory?.[t]?.[i]))return {requestKeyWithStartKey:i,requestKey:i};let s=this.__startKeyHistory[t][i],o=s[s.length-1],a=i;if(o){if(o==="end")return {requestKey:{list:[],startKey:"end",endOfList:true,startKeyHistory:s},requestKeyWithStartKey:a};a+=Q.hash(o),e.startKey=JSON.parse(o);}return this.__cached_requests?.[t]?.[a]?{requestKey:this.__cached_requests[t][a],requestKeyWithStartKey:a}:{requestKeyWithStartKey:a,requestKey:i}}function Ei(r,e,t){return new Promise((n,i)=>{let s=new XMLHttpRequest;s.open(e.method||"GET",r);for(var o in e.headers||{})s.setRequestHeader(o,e.headers[o]);e.responseType&&(s.responseType=e.responseType),s.onload=()=>{if(s.status<400)if(e.responseType=="json"||e.responseType=="blob")n(s.response);else {let a=s.responseText;try{a=JSON.parse(a);}catch{}n(a);}else if(s.status===429){let a=s.getResponseHeader("Retry-After"),u=wi(a);u!==null?setTimeout(()=>{Ei(r,e,t).then(n,i);},u):i("Too many requests");}else {let a=s.status,u=["INVALID_CORS","INVALID_REQUEST","SERVICE_DISABLED","INVALID_PARAMETER","ERROR","EXISTS","NOT_EXISTS"],c=e.responseType=="blob"?s.response:s.responseText;try{c=JSON.parse(c);}catch{}if(typeof c=="string"){let d=c.split(":"),l=d.splice(0,1)[0].trim(),g=d.join(":").trim();i(new f(g||c,{code:u.includes(l)?l:"ERROR"}));}else if(typeof c=="object"&&c?.message){let d=c?.code||(a?a.toString():null)||"ERROR",l=c.message,g=c?.cause;typeof l=="string"&&(l=l.trim()),i(new f(l,{cause:g,code:d}));}else i(c);}},s.onerror=()=>i("Network error"),s.onabort=()=>i("Aborted"),s.ontimeout=()=>i("Timeout"),typeof t=="function"&&(s.onprogress=a=>{t({status:"download",progress:Rr(a.loaded,a.total),loaded:a.loaded,total:a.total,abort:()=>s.abort()});},s.upload&&(s.upload.onprogress=a=>{t({status:"upload",progress:Rr(a.loaded,a.total),loaded:a.loaded,total:a.total,abort:()=>s.abort()});})),s.send(e.body);})}function Fu(r){let{hashedParam:e,requestKeyWithStartKey:t,url:n,fetched:i}=r;if(!i?.startKey)return i;this.__startKeyHistory.hasOwnProperty(n)||(this.__startKeyHistory[n]={}),this.__startKeyHistory[n].hasOwnProperty(e)||(this.__startKeyHistory[n][e]=[]);let s=i.startKey==="end"?"end":JSON.stringify(i.startKey);return this.__startKeyHistory[n][e].includes(s)||this.__startKeyHistory[n][e].push(s),this.__cached_requests?.[n]||(this.__cached_requests[n]={}),this.__cached_requests[n][t]=i,Object.assign({startKeyHistory:this.__startKeyHistory[n][e]},i)}async function Ct(r,e){await this.__connection;let{record_id:t,service:n=this.service,progress:i}=e;if(!t)throw new f('"record_id" is required.',{code:"INVALID_PARAMETER"});if(yi&&r instanceof SubmitEvent&&(r=r.target),Du&&r instanceof HTMLFormElement&&(r=new FormData(r)),!et||!(r instanceof FormData))throw new f('"fileList" should be a FormData or HTMLFormElement.',{code:"INVALID_PARAMETER"});let o={reserved_key:Qe(),service:n,request:"post"};e?.record_id&&(o.id=e.record_id);let a,u=(p,h,b)=>new Promise((w,_)=>{a=new XMLHttpRequest,a.open("POST",p),a.onload=()=>{let R=a.responseText;try{R=JSON.parse(R);}catch{}if(a.status>=200&&a.status<300)w(R);else if(a.status===429){let C=a.getResponseHeader("Retry-After"),I=wi(C);I!==null?setTimeout(()=>{u(p,h,b).then(w,_);},I):_("Too many requests");}else _(R);},a.onerror=()=>_("Network error"),a.onabort=()=>_("Aborted"),a.ontimeout=()=>_("Timeout"),a.upload&&typeof b=="function"&&(a.upload.onprogress=b),a.send(h);});function c(p){let h="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";if(p===0)return h[0];let b="";for(;p>0;)b=h[p%62]+b,p=Math.floor(p/62);return b}let d=[],l=[],g=[];for(let[p,h]of r.entries()){if(!(h instanceof File))continue;let b=Object.assign({key:p+"/"+h.name,sizeKey:c(h.size),contentType:h.type||null},o),{fields:w=null,url:_,cdn:R}=await v.bind(this)("get-signed-url",b,{auth:!!this.__user});g.push(R);let C=new FormData;for(let I in w)C.append(I,w[I]);C.append("file",h);try{await u(_,C,typeof i=="function"?I=>i({status:"upload",progress:Rr(I.loaded,I.total),currentFile:h,completed:d,failed:l,loaded:I.loaded,total:I.total,abort:()=>a.abort()}):null),d.push(h);}catch{l.push(h);}}return {completed:d,failed:l,bin_endpoints:g}}var Ut={};function T(r){let{preventMultipleCalls:e=false}=r||{};return function(t,n,i){let s=i.value;i.value=function(...o){let a=o[0],u=true,c=null,d="",l={},g=false;if(yi&&a instanceof SubmitEvent){a.preventDefault();let _=window.location.href;c=a.target;let R=new URL(c.action);d=R.href;let C=d?d.match(/(?<=\{).*?(?=\})/g):"";if(C)for(let I of C){if(!I)continue;let k=c.querySelector(`[name="${I}"]`);if(k)if(k.type==="file")for(let K=0;K<=k.files.length-1;K++)k.files[K]&&(l[I]||(l[I]=[]),l[I].push(new Promise((ve,V)=>{let P=new FileReader;P.onload=function(){ve(P.result);},P.readAsDataURL(k.files[K]),P.onerror=V;})));else d=d.replace(`{${I}}`,k.value);}c.getAttribute("action")===null?u=false:g=R.href===_;}let p=async _=>{if(d)for(let R in l)l[R].length&&(d=d.replace(`{${R}}`,(await Promise.all(l[R])).join(",")));return c&&u&&(window.sessionStorage.setItem(`${this.service}:${Q.hash(d)}`,JSON.stringify(_)),g?window.location.replace(d):window.location.href=d),_},h,b=_=>{throw _ instanceof f?_.name=n+"()":_=_ instanceof Error?_:new f(_,{name:n+"()"}),_},w=async()=>{try{if(h=s.bind(this)(...o),h instanceof Promise){let _=await h;return p(_)}return p(h)}catch(_){throw b(_)}};if(e){let _=`${n}:${this?.__public_identifier||""}:${this?.service||""}:${this?.owner||""}`;return Ut?.[_]||(Ut[_]=w().finally(()=>{delete Ut[_];})),Ut[_]}return w()};}}async function Si(){await this.__connection;let r=`${this.service}:${Q.hash(window.location.href.split("?")[0])}`,e=window.sessionStorage.getItem(r);if(window.sessionStorage.removeItem(r),e!==null){try{e=JSON.parse(e);}catch{}return e}return null}var Lu=128,Ou=64,Mu=128,Vu=256,qu="\u{10FFFF}",Bu=/[\u0000-\u001F\u007F]|\u{10FFFF}/u,$u=/[\/!*#]/,ju={"/":"%2F","!":"%21","*":"%2A","#":"%23"},Ku={"%2F":"/","%21":"!","%2A":"*","%23":"#"};function Hu(r){return r.replace(/%/g,"%25").replace(/[\/!*#]/g,t=>ju[t]||t)}function ie(r){return typeof r!="string"?r:r.replace(/%(2F|21|2A|23)/gi,t=>{let n=t.toUpperCase();return Ku[n]||t}).replace(/%25/gi,"%")}function Ae(r,e,t={}){let{allowEmpty:n=false,maxLength:i,blockKeyDelimiters:s=false,disallowLeadingDollar:o=false,onlyAlphanumeric:a=false}=t;if(typeof r!="string")throw new f(`"${e}" should be type: <string>.`,{code:"INVALID_PARAMETER"});if(a&&/[^a-zA-Z0-9]/.test(r))throw new f(`"${e}" should only contain alphanumeric characters.`,{code:"INVALID_PARAMETER"});if(!n&&r.length===0)throw new f(`"${e}" is required.`,{code:"INVALID_PARAMETER"});if(i&&r.length>i)throw new f(`"${e}" should be <= ${i} characters.`,{code:"INVALID_PARAMETER"});if(Bu.test(r)||r.includes(qu))throw new f(`"${e}" cannot include control characters or unsupported sentinel characters.`,{code:"INVALID_PARAMETER"});if(s&&$u.test(r)&&(r=Hu(r)),o&&r.startsWith("$"))throw new f(`"${e}" cannot start with "$".`,{code:"INVALID_PARAMETER"});return r}function Ir(r,e="table.name"){return Ae(r,e,{allowEmpty:false,maxLength:Lu,blockKeyDelimiters:true})}function Pr(r,e="tag"){return Ae(r,e,{allowEmpty:false,maxLength:Ou,blockKeyDelimiters:true})}function tt(r,e="index.name"){return Ae(r,e,{allowEmpty:false,maxLength:Mu,blockKeyDelimiters:true,disallowLeadingDollar:true})}function vi(r,e="index.value"){return Ae(r,e,{allowEmpty:true,maxLength:Vu})}function Ti(r){if(!r.record_id&&!r.unique_id)return null;let e={};return r?.service&&(e.service=r.service),r?.owner&&(e.owner=r.owner),r?.record_id?e.record_id=Ae(r.record_id,"record_id",{allowEmpty:false,onlyAlphanumeric:true}):r?.unique_id&&(e.unique_id=r.unique_id),e}function xr(r){if(r===void 0)return 0;if(typeof r=="number"){if(r>99||r<0)throw new f('"table.access_group" value should be within a range of 0 ~ 99.',{code:"INVALID_REQUEST"})}else if(typeof r=="string"){if(r={private:"private",public:0,authorized:1,admin:99}[r],r===void 0)throw new f('"table.access_group" is invalid.',{code:"INVALID_PARAMETER"})}else throw new f('"table.access_group" should be type: <number | string>.',{code:"INVALID_PARAMETER"});if(!this.__user&&r)throw new f("Unsigned users have no access to records with access group.",{code:"INVALID_REQUEST"});return r}var Dt=4503599627370496;function kt(r){if(typeof r=="number"){if(r>Dt||r<-Dt)throw new f(`Number value should be within range -${Dt} ~ +${Dt}`,{code:"INVALID_PARAMETER"});return r}if(typeof r=="boolean")return r;if(typeof r=="string")return vi(r,"index.value");throw new f('"index.value" should be type: <number | boolean | string>.',{code:"INVALID_PARAMETER"})}function Ri(r,e){if(!e.index||!("value"in e.index))throw new f('"index.value" is required.',{code:"INVALID_PARAMETER"});if(e.index.name==="$record_id")throw new f(`Cannot do "index.range" on ${e.index.name}`,{code:"INVALID_PARAMETER"});if(typeof e.index.value!=typeof r)throw new f('"index.range" type should match the type of "index.value".',{code:"INVALID_PARAMETER"});return typeof r=="string"?vi(r,"index.range"):r}var Nt={};async function He(r,e){let t={user_id:"",record_id:"",updated:0,uploaded:0,readonly:false,table:{name:"",access_group:0,subscription:{is_subscription_record:false,upload_to_feed:false,notify_subscribers:false,feed_referencing_records:false,notify_referencing_records:false}},referenced_count:0,source:{referencing_limit:null,prevent_multiple_referencing:false,can_remove_referencing_records:false,only_granted_can_reference:false},ip:"",bin:{}},n=false;function i(o){let a=o=="**"?"private":parseInt(o);return a=a==0?"public":a==1?"authorized":a==99?"admin":a,a}let s={ip:o=>{let a=o.split("#"),u=a[0];a.length>1&&(t.unique_id=a[1]),u.slice(-1)==="R"?(t.readonly=true,u=u.slice(0,-1)):t.readonly=false,/^\d{1,3}-\d{1,3}-\d{1,3}-\d{1,3}$/.test(u)&&(u=u.split("-").join("."),n=true),t.ip=u;},rec:o=>{if(!o)return;t.record_id=o;let a=o.substring(0,o.length-9),u=ne(a);t.uploaded=u;},usr:o=>{t.user_id=o;},tbl:o=>{if(o&&!t.table.name){let a=o.split("/");t.table.name=ie(a[0]),t.table.access_group=i(a[2]),a?.[3]&&(t.table.subscription.is_subscription_record=true);}},usr_tbl:o=>{let a=o.split("/");t.user_id||(t.user_id=a[0]),t.table.name||(t.table.name=ie(a[1]),t.table.access_group=i(a[3]),a?.[4]&&(t.table.subscription.is_subscription_record=true));},idx:o=>{if(!o)return;let a=o.split("!"),u=ie(a.splice(0,1)[0]),c=Wu("!"+a.join("!"));typeof c=="string"&&(c=ie(c)),t.index={name:u,value:c};},ref:o=>{o&&(t.reference=o.split("/")[0]);},tags:o=>{t.tags=Array.isArray(o)?o.map(a=>ie(a)):o;},upd:o=>{t.updated=o;},acpt_mrf:o=>{t.source.prevent_multiple_referencing=!o;},ref_limt:o=>{t.source.referencing_limit=o;},rfd:o=>{t.referenced_count=o;},bin:async o=>{let a={},u=t?.reference||null;if(Array.isArray(o)){let c=await Promise.all(o.map(async d=>{try{let l=d.split("/").slice(3).join("/"),g=l.split("/");if(g.length<12)return null;let p=decodeURIComponent(g[g.length-1]),h=decodeURIComponent(g[10]),b=g[9],w=g[8],_=i(g[6]),R=d;if(_!=="public")try{R=await Ft.bind(this)(d,{dataType:"endpoint",_ref:u});}catch(I){console.error("Error getting signed url for private file:",I),R=d;}let C={access_group:_,filename:p,url:R,path:l,size:ne(b),uploaded:ne(w),getFile:(I,k)=>{let K={dataType:I||"download",progress:k,_ref:u,_update:C};return Ft.bind(this)(R,K)}};return {pathKey:h,obj:C}}catch{return null}}));for(let d of c)if(d){if(a[d.pathKey]){a[d.pathKey].push(d.obj);continue}a[d.pathKey]=[d.obj];}}t.bin=a;},prv_acs:o=>{for(let a in o)["notify_subscribers","upload_to_feed","feed_referencing_records","notify_referencing_records"].includes(a)?t.table.subscription[a]=o[a]:t.source[a]=o[a];},data:o=>{let a=o;o==="!D%{}"?a={}:o==="!L%[]"&&(a=[]),t.data=a;}};if(r.record_id)return r;for(let o in s)if(r.hasOwnProperty(o)){let a=s[o](r[o]);a instanceof Promise&&await a;}return n&&(t.user_id="anonymous:"+t.user_id),t}function Wu(r){let e=r.substring(3);switch(r.substring(0,3)){case "!S%":return e;case "!N%":let n=e.split("."),i=Number(n[0])-4503599627370496;return n.length===1?i:parseFloat(i.toString()+"."+n[1]);case "!B%":return e==="1";case "!L%":case "!D%":try{return JSON.parse(e)}catch{throw new f("Value parse error.",{code:"PARSE_ERROR"})}default:return r}}async function Ii(r){let{endpoints:e}=r;if(typeof e=="string"&&(e=[e]),!Array.isArray(e))throw new f('"endpoints" should be type: array | string.',{code:"INVALID_PARAMETER"});let t=await v.bind(this)("del-files",{endpoints:e,storage:"records"},{auth:true,method:"post"}),n=[];for(let i in t)n.push(He.bind(this)(t[i]));return Promise.all(n)}async function Ft(r,e){if(typeof r!="string")throw new f('"url" should be type: string.',{code:"INVALID_PARAMETER"});let t=r.split("?"),n=t.shift()||"",i=t.length?"?"+t.join("?"):"",s=m.Url(n);r=s+i;let o=false,a=s.split("/"),c=a[2].split("."),d=null;c.length===3&&c[1]==="skapi"&&(d=c[0],o=true);let l=a.slice(3),g=false;if(!o&&(l[0]==="auth"||l[0]==="publ"))try{m.UserId(l[2]),m.UserId(l[3]),g=l[0]=="auth",o=!0;}catch{throw new f("Invalid file url.",{code:"INVALID_PARAMETER"})}let p=d?null:l[1];if(e=m.Params(e,{expires:["number",()=>0],dataType:["base64","blob","endpoint","text","info",()=>"download"],progress:"function",_ref:[null,"string"],_update:_=>_}),e?.dataType==="info")return {url:r,filename:l[l.length-1],fileKey:l[l.length-2],access_group:l[6]==="**"?"private":l[6]==="01"?"authorized":l[6]==="00"?"public":parseInt(l[6]),uploader:l[3],record_id:l[4]==="records"?l[5]:"N/A",filesize:ne(l[9]),uploaded:ne(l[8])};let h=r.split("/").slice(-1)[0],b=e.expires;if(b){if(!o)throw new f("Expires option can only be used on skapi cdn endpoints.",{code:"INVALID_PARAMETER"});if(b<0)throw new f('"config.expires" should be > 0. (seconds)',{code:"INVALID_PARAMETER"});let _={request:d?"get-host":"get",id:d||l[5],key:r,expires:b};p&&(_.service=p),r=(await v.bind(this)("get-signed-url",_,{auth:true})).url;}else if(g){let _=Math.floor(Date.now()/1e3);if(!this.bearerToken&&(!this.session?.idToken?.payload?.exp||this.session.idToken.payload.exp<_)){this.log("getFile:requesting new token",null);try{await W.bind(this)().getSession({refreshToken:!0}),this.log("getFile:received new tokens",{exp:this.session?.idToken?.payload?.exp,currTime:_,expiresIn:this.session?.idToken?.payload?.exp-_,token:this.session?.accessToken?.jwtToken,refreshToken:this.session?.refreshToken?.token});}catch(k){throw this.log("getFile:new token error",k),new f("User login is required.",{code:"INVALID_REQUEST"})}}let R=this.bearerToken||this.session?.idToken?.jwtToken;if(!R||!this.user?.user_id)throw new f("User login is required.",{code:"INVALID_REQUEST"});r+=`${r.includes("?")?"&":"?"}t=${encodeURIComponent(R)}`;let C=l[6]==="**"?"**":parseInt(l[6]),I=this.user?.access_group??-1;if(this.user.user_id!==l[3]&&(C==="**"||I<C)){let k=l[5];if(this.__private_access_key[k]&&typeof this.__private_access_key[k]=="string")r+=`&p=${encodeURIComponent(this.__private_access_key[k])}`;else if(this.owner!==this.host)try{let K=await this.requestPrivateRecordAccessKey({record_id:k,reference_id:e?._ref});r+=`&p=${encodeURIComponent(K)}`;}catch{}}}if(e?.dataType==="endpoint")return e._update&&(e._update.url=r),r;if(e?.dataType==="download"){let _=document.createElement("a");return _.href=r,document.body.appendChild(_),_.setAttribute("download",h),_.target="_blank",_.click(),document.body.removeChild(_),null}return new Promise(async(_,R)=>{try{let C=await v.bind(this)(r,null,{method:"get",contentType:null,responseType:e?.dataType==="text"?"text":"blob",fetchOptions:{progress:e?.progress}},{ignoreService:!0});if(e?.dataType==="base64"){let I=new FileReader;I.onloadend=()=>_(I.result),I.readAsDataURL(C);}else _(C);}catch(C){R(C);}})}async function Pi(r,e=false){r=L(r,{ignoreEmpty:true}).data||{};let t="",n=Ti(r);if(n)r=n,t=r.record_id||r.unique_id,typeof t=="string"&&(typeof this.__private_access_key?.[t]=="string"&&(r.private_key=this.__private_access_key?.[t]||void 0),this.__my_unique_ids[t]&&(e?delete this.__my_unique_ids[t]:r.record_id=this.__my_unique_ids[t]));else {let i=await J.bind(this)(),s=r?.reference,o=false;typeof s=="object"&&Object.keys(s).length&&(s?.record_id||s?.unique_id?(t=s.record_id||s.unique_id,t&&typeof this.__private_access_key?.[t]=="string"&&(r.private_key=this.__private_access_key?.[t]||void 0),r.reference=t):s?.user_id&&(o=s.user_id===this.user?.user_id,r.reference=s.user_id)),typeof r?.table=="string"&&(r.table={name:r.table,access_group:0}),r.index&&r.index.hasOwnProperty("range")&&r.index.hasOwnProperty("condition")&&delete r.index.range;let a=u=>({table:{name:c=>Ir(c,"table.name"),access_group:xr.bind(this),subscription:c=>m.UserId(c,'User ID in "subscription"')},reference:"string",index:{name:["$updated","$uploaded","$referenced_count","$user_id",c=>tt(c,"index.name")],value:c=>{let d={$updated:"number",$uploaded:"number",$referenced_count:"number",$user_id:m.UserId};if(d.hasOwnProperty(u.index.name)){let l=d[u.index.name];if(typeof l=="function")return l(c);if(l!==typeof c)throw new f(`"index.value" should be type: ${l}.`,{code:"INVALID_PARAMETER"});return c}return typeof c=="string"&&!c?"":kt(c)},condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq"],range:c=>Ri(c,u)},tag:c=>{if(c==null)return c;if(typeof c=="string")return Pr(c,"tag");throw new f('"tag" should be type: string.',{code:"INVALID_PARAMETER"})},private_key:"string"});r=m.Params(r||{},a(r),o||i?[]:["table"],{ignoreEmpty:true});}return {query:r,is_reference_fetch:t}}async function xi(r,e){await this.__connection;let t=await Pi.bind(this)(r),n=t.is_reference_fetch,i=await v.bind(this)("get-records",t.query,{fetchOptions:e,auth:!!this.__user,method:this.__user?"post":"get"});n&&i?.reference_private_key&&typeof i.reference_private_key=="string"&&(this.__private_access_key[n]=i.reference_private_key);let s=[];for(let o in i.list)s.push(He.bind(this)(i.list[o]));return i.list=await Promise.all(s),i}function Ui(r){let e="",t=[],n=m.Params(r||{},{record_id:s=>Ae(s,"record_id",{allowEmpty:false,onlyAlphanumeric:true}),unique_id:["string",null],readonly:"boolean",table:{name:s=>Ir(s,"table.name"),subscription:[null,{is_subscription_record:"boolean",upload_to_feed:"boolean",notify_subscribers:"boolean",feed_referencing_records:"boolean",notify_referencing_records:"boolean"}],access_group:xr.bind(this)},source:{referencing_limit:s=>{if(s===null)return null;if(typeof s=="number"){if(0>s)throw new f('"reference_limit" should be >= 0',{code:"INVALID_PARAMETER"});if(s>4503599627370546)throw new f('"reference_limit" should be <= 4503599627370546',{code:"INVALID_PARAMETER"});return s}throw new f('"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:s=>{if(s===void 0)return;if(!s||Array.isArray(s)&&!s.length)return null;let o={name:u=>tt(u,'"name" in "index_restrictions"'),value:u=>kt(u),condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne",()=>null],range:u=>{if(u!==null&&typeof s.value!=typeof u)throw new f('Index restriction "range" type should match the type of "value".',{code:"INVALID_PARAMETER"});if(!s.hasOwnProperty("value"))throw new f('Index restriction "value" is required.',{code:"INVALID_PARAMETER"});return u}};Array.isArray(s)||(s=[s]);let a=s.map(u=>m.Params(u,o,["name"]));if(a.length)for(let u of a)u.condition&&u.hasOwnProperty("range")&&delete u.range;return a}},reference:s=>{if(s===null)return {record_id:null};if(s){if(typeof s=="string")return e=s,this.__my_unique_ids[s]?this.__my_unique_ids[s]:s;if(typeof s!="object")throw new f('"reference" should be type: <string | object>.',{code:"INVALID_PARAMETER"});return m.Params(s,{unique_id:"string",record_id:o=>o==null?o:(e=o,typeof this.__private_access_key?.[o]=="string"&&(r.reference_private_key=this.__private_access_key[o]||void 0),Ae(o,"reference.record_id",{allowEmpty:false,onlyAlphanumeric:true}))})}},index:[null,{name:s=>tt(s,"index.name"),value:s=>kt(s)}],tags:s=>{if(s==null)return s;if(typeof s=="string"&&(s=s.split(",").map(o=>o.trim())),!Array.isArray(s))throw new f('"tag" should be type: <string | string[]>.',{code:"INVALID_PARAMETER"});return s.map(o=>Pr(o,"tag"))},remove_bin:s=>{if(!s)return null;let o=[];if(Array.isArray(s))for(let a of s)if(typeof a=="string")o.push(decodeURIComponent(a.split("?")[0]));else if(a.url&&a.size&&a.filename){let c=a.url.split("/").slice(0,3).join("/")+"/"+a.path;o.push(c);}else throw new f('"remove_bin" should be type: <string[] | BinaryFile[] | null>',{code:"INVALID_PARAMETER"});else throw new f('"remove_bin" should be type: <string[] | BinaryFile[] | null>',{code:"INVALID_PARAMETER"});return o},progress:"function",data:s=>s},[],{precall:s=>{let o=s?.data||{};if(!o?.record_id&&!o.table)throw new f('"table.name" is required.',{code:"INVALID_PARAMETER"});typeof o.table=="string"&&(o.table={name:o.table,access_group:0}),s.files&&(t=s.files);}}),i=r.progress||null;if(delete n.progress,!this.__user){let s=!!(n.table?.subscription?.is_subscription_record||n.table?.subscription?.upload_to_feed||n.table?.subscription?.notify_subscribers||n.table?.subscription?.feed_referencing_records||n.table?.subscription?.notify_referencing_records);if(n.record_id)throw new f("Public users cannot update existing records.",{code:"INVALID_REQUEST"});if(n.table.access_group!=="public"&&n.table.access_group!==0)throw new f("Public users can only post records to public tables.",{code:"INVALID_REQUEST"});if(s)throw new f("Public users cannot post subscription records.",{code:"INVALID_REQUEST"});if(n.remove_bin)throw new f("Public users cannot remove files from records.",{code:"INVALID_REQUEST"});if(n.unique_id)throw new f("Public users cannot set unique_id for records.",{code:"INVALID_REQUEST"})}return {config:n,progress:i,is_reference_post:e,files:t}}async function Ci(r){if(await this.__connection,!Array.isArray(r)||!r.length)throw new f('"params" should be a non-empty array.',{code:"INVALID_PARAMETER"});let e=[],t,n,i=null,o={_is_bulk_:r.map((l,g)=>{if(!l||typeof l!="object"||Array.isArray(l))throw new f(`"params[${g}]" should be type: <object>.`,{code:"INVALID_PARAMETER"});let p=Ui.bind(this)(l),h=p.config;if(p.is_reference_post&&e.push(p.is_reference_post),typeof h.progress=="function"&&i===null&&(i=h.progress),h.service!==void 0){if(t===void 0)t=h.service;else if(t!==h.service)throw new f('All bulk params should share the same "service" value.',{code:"INVALID_PARAMETER"})}if(h.owner!==void 0){if(n===void 0)n=h.owner;else if(n!==h.owner)throw new f('All bulk params should share the same "owner" value.',{code:"INVALID_PARAMETER"})}return delete h.progress,delete h.service,delete h.owner,h}),service:"",owner:""};t!==void 0&&(o.service=t),n!==void 0&&(o.owner=n);let a={auth:!!this.__user,method:"post"},u={};Object.keys(u).length&&Object.assign(a,{fetchOptions:u});let c=await v.bind(this)("post-record",o,a),d=await Promise.all(c.map(l=>He.bind(this)(l,"called from postRecord")));for(let l=0;l<c.length;l++){let g=c[l],p=d[l];if(typeof g?.reference_private_key=="string")for(let h of e)this.__private_access_key[h]=g.reference_private_key;p?.unique_id&&(this.__my_unique_ids[p.unique_id]=p.record_id);}return d}async function Di(r,e,t){if(await this.__connection,!e)throw new f('"config" argument is required.',{code:"INVALID_PARAMETER"});let n=Ui.bind(this)(e),i=n.config,s=n.progress,o=n.is_reference_post,a={auth:!!this.__user,method:"post"},u=[],c=L(r);t&&Array.isArray(t)&&t.length&&(u=u.concat(t)),c.files&&Array.isArray(c.files)&&c.files.length&&(u=u.concat(c.files));let d=null;d=Object.assign({data:c.data},i);let l={};typeof s=="function"&&(l.progress=s),Object.keys(l).length&&Object.assign(a,{fetchOptions:l});let g=await v.bind(this)("post-record",d,a);if(z()&&u.length){let h=new FormData;for(let _ of u)h.append(_.name,_.file,_.file.name);let b={record_id:g.rec,progress:s};i.hasOwnProperty("service")&&(b.service=i.service);let{bin_endpoints:w}=await Ct.bind(this)(h,b);g.bin?g.bin.push(...w):g.bin=w;}o&&typeof g?.reference_private_key=="string"&&(this.__private_access_key[o]=g.reference_private_key);let p=await He.bind(this)(g,"called from postRecord");return p.unique_id&&(this.__my_unique_ids[p.unique_id]=p.record_id,z()&&window.sessionStorage.setItem(`${this.service}:uniqueids`,JSON.stringify(this.__my_unique_ids))),p}async function ki(r,e){let t=await v.bind(this)("get-table",m.Params(r||{},{table:"string",condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}),Object.assign({auth:!!this.__user},{fetchOptions:e})),n={cnt_rec:"number_of_records",tbl:"table",srvc:"service",grp_:"number_of_records_in_access_group_"};if(Array.isArray(t?.list))for(let i of t.list){for(let s in n){if(s==="grp_"){for(let o in i)if(o.startsWith("grp_")){let a=o.substring(4);a==="pv"?a="private":a==="00"?a="public":a==="01"?a="authorized":a==="99"&&(a="admin"),i[`number_of_records_in_access_group_${a}`]=i[o],delete i[o];}}i.hasOwnProperty(s)&&(i[n[s]]=i[s],delete i[s]);}typeof i.table=="string"&&(i.table=ie(i.table));}return t}async function Ni(r,e){if(!r?.table)throw new f('"table" is required.',{code:"INVALID_PARAMETER"});let t=m.Params(r||{},{table:"string",index:s=>tt(s,"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(t.hasOwnProperty("order")){if(!t.order?.by)throw new f('"order.by" is required.',{code:"INVALID_PARAMETER"});if(t.order.hasOwnProperty("condition")&&!t.order.hasOwnProperty("value"))throw new f('"value" is required for "condition".',{code:"INVALID_PARAMETER"});if(t.hasOwnProperty("index")&&t.index.substring(t.index.length-1)!==".")throw new f('"index" should be a parent index name of the compound index when using "order.by"',{code:"INVALID_PARAMETER"})}let n=await v.bind(this)("get-index",t,Object.assign({auth:!!this.__user},{fetchOptions:e})),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(n?.list)&&(n.list=n.list.map(s=>{let o=s.idx.split("/"),a={table:ie(o[1]),index:ie(o[2]),number_of_records:s.cnt_rec};for(let u in i)Object.prototype.hasOwnProperty.call(s,u)&&(a[i[u]]=s[u]);return a})),n}async function Fi(r,e){let t=await v.bind(this)("get-tag",m.Params(r||{},{table:"string",tag:"string",condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}),Object.assign({auth:!!this.__user},{fetchOptions:e}));return Array.isArray(t?.list)&&(t.list=t.list.map(n=>{let i=n.tag.split("/");return {table:ie(i[1]),tag:ie(i[0]),number_of_records:n.cnt_rec}})),t}async function Li(r,e){let t=await v.bind(this)("get-uniqueid",m.Params(r||{},{unique_id:"string",condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}),Object.assign({auth:!!this.__user},{fetchOptions:e}));if(Array.isArray(t?.list))for(let n in t.list){let i=t.list[n];t.list[n]={unique_id:i.unq,record_id:i.rec};}return t}async function Oi(r,e){await this.__connection;let t=await Pi.bind(this)(r,true),n=t.is_reference_fetch,i=await v.bind(this)("del-records",t.query,{auth:true,fetchOptions:e});return n&&typeof i?.reference_private_key=="string"&&(this.__private_access_key[n]=i.reference_private_key),i?.message||i}function Mi(r){return $i.bind(this)({record_id:r.record_id,user_id:r.user_id,execute:"add"})}function Vi(r){return $i.bind(this)({record_id:r.record_id,user_id:r.user_id||null,execute:"remove"})}async function qi(r,e){let t={record_id:r.record_id||void 0,user_id:r.user_id||void 0,execute:"list"};if(!t.record_id&&!t.user_id)throw new f("Either record_id or user_id must be provided.",{code:"INVALID_PARAMETER"});if(t.user_id)if(typeof t.user_id=="string")m.UserId(t.user_id),t.user_id=[t.user_id];else if(Array.isArray(t.user_id))for(let s of t.user_id)m.UserId(s);else throw new f("user_id should be type: <string | string[]>",{code:"INVALID_PARAMETER"});let n=s=>(s.rec_usr?(s.record_id=s.rec_usr.split("/")[0],s.user_id=s.rec_usr.split("/")[1]):s.usr_rec&&(s.user_id=s.usr_rec.split("/")[0],s.record_id=s.usr_rec.split("/")[1]),s),i=await v.bind(this)("grant-private-access",t,{auth:true,fetchOptions:e});return i.list=i.list.map(n),i}function Bi(r){let e=r.record_id,t=r.reference_id||void 0;if(!e)throw new f("Record ID is required.",{code:"INVALID_PARAMETER"});if(typeof e!="string")throw new f("Record ID should be type: <string | string[]>",{code:"INVALID_PARAMETER"});if(t&&typeof t!="string")throw new f("Reference ID should be type: <string>",{code:"INVALID_PARAMETER"});if(typeof this.__private_access_key[e]=="string")return Promise.resolve(this.__private_access_key[e]);if(Nt[e])return Nt[e];let n=v.bind(this)("request-private-access-key",{record_id:e,reference_id:t},{auth:true}).then(i=>{let s=typeof i=="string"?i:i?.private_key;if(typeof s!="string")throw new f("Invalid private access key response.",{code:"ERROR"});return this.__private_access_key[e]=s,s}).finally(()=>{delete Nt[e];});return Nt[e]=n,n}function $i(r){r.execute;let t=m.Params(r,{record_id:"string",user_id:n=>{if(!n)throw new f("User ID is required.",{code:"INVALID_PARAMETER"});let i=n;if(typeof i=="string"&&(i=[i]),i.length>100)throw new f("Cannot process more than 100 users at once.",{code:"INVALID_REQUEST"});for(let s of i)m.UserId(s,'User ID in "user_id"');return i},execute:["add","remove"]},["execute","record_id","user_id"]);return t.user_id||(t.user_id=null),v.bind(this)("grant-private-access",t,{auth:true})}var x={},$={},se={},de={},le={},Lt={},Ot={};function ji(r,e,t){r[e]||(r[e]=[]),r[e].push(t);}async function Mt(r,e,t){let n=[];if(r[e]){for(let i of r[e])if(i){let s=t(i);s instanceof Promise&&(s=await s),n.push(s);}delete r[e];}return n}async function Cr(r,e){if(!this?.session?.accessToken?.jwtToken)throw new f("Access token is required.",{code:"INVALID_PARAMETER"});let t=await this.__socket;async function n(i,s,o){this.log("answerSdpOffer from",s),await x[s].setRemoteDescription(new RTCSessionDescription(i));let a=await x[s].createAnswer();await x[s].setLocalDescription(a),o.send(JSON.stringify({action:"rtc",uid:s,content:{sdpanswer:a},token:this.session.accessToken.jwtToken}));}x?.[e]?r?(await Mt(Ot,e,i=>n.bind(this)(i,e,t)),await n.bind(this)(r,e,t)):await Mt(Ot,e,i=>n.bind(this)(i,e,t)):r&&ji(Ot,e,r);}async function Dr(r,e){if(this.log("receiveIceCandidate",r),x?.[e]&&x[e]?.remoteDescription&&x[e]?.remoteDescription?.type){if(!r)return Mt(Lt,e,t=>x[e].addIceCandidate(t));await Mt(Lt,e,t=>x[e].addIceCandidate(t)),await x[e].addIceCandidate(r);}else ji(Lt,e,r);}async function oe(r){if(typeof window>"u"||window._runningInNodeJS)throw new f("WebRTC is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});m.Params(r,{cid:s=>{if(typeof s!="string")throw new f('"cid" should be type: <string>.',{code:"INVALID_PARAMETER"});if(s&&s.slice(0,4)!=="cid:")throw new f('"cid" should be a valid connection id.',{code:"INVALID_PARAMETER"});return s},close:"boolean"});let e=await this.__socket,{cid:t,close_all:n=false}=r||{};if(!n&&!t)throw new f('"cid" is required.',{code:"INVALID_PARAMETER"});let i=s=>{if(!s)throw new f('"cid" is required.',{code:"INVALID_PARAMETER"});if(delete Ot[s],delete Lt[s],$[s]&&Object.values($[s]).forEach(o=>{o.readyState!=="closed"&&o.close();}),delete $[s],x?.[s]){x[s].connectionState!=="closed"&&(x[s].close(),e.send(JSON.stringify({action:"rtc",uid:s,content:{hungup:this.user.user_id},token:this.session.accessToken.jwtToken})));let o={type:"connectionstatechange",target:x[s],timestamp:new Date().toISOString(),state:x[s].connectionState,iceState:x[s].iceConnectionState,signalingState:x[s].signalingState};le[s]&&le[s](o),this.log("closeRTC",o);}delete le[s],delete de[s],delete se[s],delete x[s];};if(n)for(let s in x)i(s);else i(t);this.log("Cleaning up media stream..."),this.__mediaStream&&(this.__mediaStream.getTracks().forEach(s=>{s.stop();}),this.__mediaStream=null);}async function Ki(r){if(r instanceof MediaStream)return r;if(!r.video&&!r.audio){let e=new MediaStream,t=document.createElement("canvas");t.width=1,t.height=1;let i=t.captureStream().getVideoTracks()[0];return e.addTrack(i),e}return window.navigator.mediaDevices.getUserMedia(r)}async function Hi(r,e){if(typeof window>"u"||window._runningInNodeJS)throw new f("WebRTC is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(typeof e!="function")throw new f("Callback is required.",{code:"INVALID_PARAMETER"});if(!this?.session?.accessToken?.jwtToken)throw new f("Access token is required.",{code:"INVALID_PARAMETER"});r=m.Params(r,{cid:o=>{if(typeof o!="string")throw new f('"cid" should be type: <string>.',{code:"INVALID_PARAMETER"});if(o&&o.slice(0,4)!=="cid:")throw new f('"cid" should be a valid connection id.',{code:"INVALID_PARAMETER"});return o},ice:["string",()=>"stun:stun.skapi.com:3468"],media:o=>o,channels:["text-chat","file-transfer","video-chat","voice-chat","gaming",{ordered:"boolean",maxPacketLifeTime:"number",maxRetransmits:"number",protocol:"string"},()=>[{ordered:true,maxPacketLifeTime:10,protocol:"default"}]]},["cid"]);let{cid:t,ice:n}=r;if(!(r?.media instanceof MediaStream)&&(r?.media?.video||r?.media?.audio)&&window.location.hostname!=="localhost"&&window.location.protocol!=="https:")throw new f("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 f("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});if(i.readyState!==1)throw new f("Realtime connection is not ready.",{code:"INVALID_REQUEST"});let s={iceServers:[{urls:n}]};x?.[t]||(x[t]=new RTCPeerConnection(s)),r?.media&&(this.__mediaStream=await Ki(r.media),this.__mediaStream.getTracks().forEach(o=>{x[t].addTrack(o,this.__mediaStream);})),le[t]=e,$[t]||($[t]={});for(let o=0;o<r.channels.length;o++){let a=r.channels[o];if(typeof a=="string")switch(a){case "text-chat":a={ordered:true,maxRetransmits:10,protocol:"text-chat"};break;case "file-transfer":a={ordered:false,maxPacketLifeTime:3e3,protocol:"file-transfer"};break;case "video-chat":a={ordered:true,maxRetransmits:10,protocol:"video-chat"};break;case "voice-chat":a={ordered:true,maxRetransmits:10,protocol:"voice-chat"};break;case "gaming":a={ordered:false,maxPacketLifeTime:100,protocol:"gaming"};break;default:a={ordered:true,maxRetransmits:10,protocol:"default"};break}let u=a.protocol||"default";if(Object.keys($[t]).includes(u))throw new f(`Data channel with the protocol "${u}" already exists.`,{code:"INVALID_REQUEST"});let c=x[t].createDataChannel(u,a);$[t][u]=c;}for(let o in $[t]){let a=$[t][o];Gi.bind(this)(t,a);}return Ji.bind(this)(t,["onnegotiationneeded"]),await Ur.bind(this)(t),{hangup:()=>se[t]&&se[t](false),connection:new Promise(o=>{se[t]=(a=>{if(this.log("receiver picked up the call",t),!a)return oe.bind(this)({cid:t}),null;x[t].onnegotiationneeded=()=>{this.log("onnegotiationneeded",`sending offer to "${t}".`),Ur.bind(this)(t),le[t]&&le[t]({type:"negotiationneeded",target:x[t],timestamp:new Date().toISOString(),signalingState:x[t].signalingState,connectionState:x[t].iceConnectionState,gatheringState:x[t].iceGatheringState});},o({target:x[t],channels:$[t],hangup:()=>oe.bind(this)({cid:t}),media:this.__mediaStream});}).bind(this);})}}function Wi(r){return async(e,t)=>{e=e||{},e=L(e).data;let n=r.sender_cid,i=await this.__socket;if(!de[n])return null;if(typeof t!="function")throw new f("Callback is required.",{code:"INVALID_PARAMETER"});if(!(e?.media instanceof MediaStream)&&(e?.media?.video||e?.media?.audio)&&window.location.hostname!=="localhost"&&window.location.protocol!=="https:")throw new f("Media stream is only supported on either localhost or https.",{code:"INVALID_REQUEST"});let{ice:s="stun:stun.skapi.com:3468"}=e;return x?.[n]||(x[n]=new RTCPeerConnection({iceServers:[{urls:s}]})),e?.media&&(this.__mediaStream=await Ki(e.media),this.__mediaStream.getTracks().forEach(o=>{x[n].addTrack(o,this.__mediaStream);})),delete de[n],le[n]=t,$[n]||($[n]={}),x[n].ondatachannel=o=>{this.log("ondatachannel",`received data channel "${o.channel.label}".`);let a=o.channel;$[n][a.label]=a,Gi.bind(this)(n,a);},Ji.bind(this)(n,["onnegotiationneeded"]),await Cr.bind(this)(null,n),await Dr.bind(this)(null,n),i.send(JSON.stringify({action:"rtc",uid:n,content:{pickup:this.user.user_id},token:this.session.accessToken.jwtToken})),{target:x[n],channels:$[n],hangup:()=>oe.bind(this)({cid:n}),media:this.__mediaStream}}}async function Ur(r){if(!this?.session?.accessToken?.jwtToken)throw new f("Access token is required.",{code:"INVALID_PARAMETER"});this.log("sendOffer",r);let e=await this.__socket,t=await x[r].createOffer();await x[r].setLocalDescription(t);let n=x[r].localDescription;this.log("rtcSdpOffer to",n),e.send(JSON.stringify({action:"rtc",uid:r,content:{sdpoffer:n},token:this.session.accessToken.jwtToken}));}async function Ju(r,e){if(!this?.session?.accessToken?.jwtToken)throw new f("Access token is required.",{code:"INVALID_PARAMETER"});this.log("sendIceCandidate to",e);let t=await this.__socket;if(!r.candidate){this.log("candidate-end","all ice candidates have been sent");return}let n=le[e]||(()=>{}),i=r.candidate;this.log("ice gathering state set to",x[e].iceGatheringState),n({type:"icecandidate",target:x[e],timestamp:new Date().toISOString(),candidate:r.candidate.candidate,sdpMid:r.candidate.sdpMid,sdpMLineIndex:r.candidate.sdpMLineIndex,usernameFragment:r.candidate.usernameFragment,protocol:r.candidate.protocol,gatheringState:x[e].iceGatheringState,connectionState:x[e].iceConnectionState}),t.send(JSON.stringify({action:"rtc",uid:e,content:{candidate:i},token:this.session.accessToken.jwtToken}));}function Ji(r,e){let t=new Set(e),n=le[r]||(o=>{}),i=x[r],s={ontrack:o=>{n({type:"track",target:i,timeStamp:o.timeStamp,streams:o.streams,track:o.track});},onicecandidate:o=>{Ju.bind(this)(o,r),o.candidate?n({type:"icecandidate",target:i,timestamp:new Date().toISOString(),candidate:o.candidate.candidate,sdpMid:o.candidate.sdpMid,sdpMLineIndex:o.candidate.sdpMLineIndex,usernameFragment:o.candidate.usernameFragment,protocol:o.candidate.protocol,gatheringState:i.iceGatheringState,connectionState:i.iceConnectionState}):n({type:"icecandidateend",target:i,timestamp:new Date().toISOString()});},onicecandidateerror:o=>{n({type:"icecandidateerror",target:i,timestamp:new Date().toISOString(),errorCode:o.errorCode,errorText:o.errorText,url:o.url,hostCandidate:o.hostCandidate,gatheringState:i.iceGatheringState,connectionState:i.iceConnectionState});},oniceconnectionstatechange:()=>{n({type:"iceconnectionstatechange",target:i,timestamp:new Date().toISOString(),state:i.iceConnectionState,gatheringState:i.iceGatheringState,signalingState:i.signalingState});},onicegatheringstatechange:()=>{n({type:"icegatheringstatechange",target:i,timestamp:new Date().toISOString(),state:i.iceGatheringState,connectionState:i.iceConnectionState,signalingState:i.signalingState});},onsignalingstatechange:()=>{n({type:"signalingstatechange",target:i,timestamp:new Date().toISOString(),state:i.signalingState,connectionState:i.iceConnectionState,gatheringState:i.iceGatheringState});},onnegotiationneeded:()=>{Ur.bind(this)(r),n({type:"negotiationneeded",target:i,timestamp:new Date().toISOString(),signalingState:i.signalingState,connectionState:i.iceConnectionState,gatheringState:i.iceGatheringState});},onconnectionstatechange:()=>{n({type:"connectionstatechange",target:i,timestamp:new Date().toISOString(),state:i.connectionState,iceState:i.iceConnectionState,signalingState:i.signalingState});let o=i.connectionState;(o==="disconnected"||o==="failed"||o==="closed")&&oe.bind(this)({cid:r});}};for(let[o,a]of Object.entries(s))t.has(o)||(i[o]=a);}function Gi(r,e,t){let n=new Set(t),i=le[r]||(o=>{}),s={onmessage:o=>{let a={type:o.type,target:e,timeStamp:o.timeStamp,data:o.data,lastEventId:o.lastEventId,origin:o.origin,readyState:e.readyState,bufferedAmount:e.bufferedAmount};this.log(`${e.label}: message`,o.data),i(a);},onerror:o=>{let a={type:o.type,target:e,timeStamp:o.timeStamp,error:o.error.message,errorCode:o.error.errorDetail,readyState:e.readyState,label:e.label};this.log(`${e.label}: error`,o.error.message),i(a);},onclose:o=>{let a={type:o.type,target:e,timeStamp:o.timeStamp,readyState:e.readyState,label:e.label,id:e.id};this.log(`${e.label}: closed`,null),i(a),$[r]&&(delete $[r][e.label],Object.keys($[r]).length===0&&oe.bind(this)({cid:r}));},onbufferedamountlow:o=>{let a={target:e,bufferedAmount:e.bufferedAmount,bufferedAmountLowThreshold:e.bufferedAmountLowThreshold,type:o.type,timeStamp:o.timeStamp};this.log(`${e.label}: bufferedamountlow`,e.bufferedAmount),i(a);},onopen:o=>{this.log("dataChannel",`data channel: "${e.label}" is open and ready to send messages.`);let a={type:o.type,target:e,timeStamp:o.timeStamp,readyState:e.readyState,label:e.label,id:e.id,ordered:e.ordered,maxRetransmits:e.maxRetransmits,protocol:e.protocol};i(a);}};for(let[o,a]of Object.entries(s))n.has(o)||(e[o]=a);}var Se,Ee=null,rt=true,We=0;async function Gu(){if(typeof window>"u"||window._runningInNodeJS)throw new f("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.getProfile(),!this.session)throw new f("No access.",{code:"INVALID_REQUEST"});let r=await this.record_endpoint;return new WebSocket(r.websocket_private+"?token="+this.session.accessToken.jwtToken)}var kr=null;async function Qi(){if(typeof window>"u"||window._runningInNodeJS)throw new f("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});rt=true;let r=this.__socket?await this.__socket:this.__socket;oe.bind(this)({close_all:true}),Se&&Nr.bind(this)({group:null}),We=0,Ee&&(Ee.terminate(),Ee=null);try{r&&r.close();}catch{}return window.removeEventListener("visibilitychange",kr),this.__socket=null,null}async function Vt(r,e=50,t){if(typeof window>"u"||window._runningInNodeJS)throw new f("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(typeof r!="function")throw new f("Callback must be a function.",{code:"INVALID_REQUEST"});if(t==="reconnect"){if(this.__socket instanceof Promise){let n=await this.__socket;if(n.readyState!==WebSocket.CLOSED&&n.readyState!==WebSocket.CLOSING)return this.__socket}}else if(rt&&(kr=()=>{!document.hidden&&!rt&&Vt.bind(this)(r,0,"reconnect");},this.__socket instanceof Promise))return this.__socket;Ee&&(Ee.terminate(),Ee=null),this.__socket=new Promise(async n=>{await je.bind(this)(),setTimeout(async()=>{let i=await Gu.bind(this)();i.onopen=()=>{rt=false,We=0,t!=="reconnect"&&window.addEventListener("visibilitychange",kr),this.log("realtime onopen","Connected to WebSocket server."),r({type:"success",message:"Connected to WebSocket server."}),Se&&i.send(JSON.stringify({action:"joinRoom",rid:Se,token:this.session.accessToken.jwtToken}));let s=`
208
208
  let interval = 15000; // Set interval time 15 seconds
209
209
 
210
210
  function runInterval() {
@@ -213,9 +213,9 @@ var Ds=Object.create;var De=Object.defineProperty;var Or=Object.getOwnPropertyDe
213
213
  }
214
214
 
215
215
  runInterval(); // Start interval
216
- `,o=new Blob([s],{type:"application/javascript"});Se=new Worker(URL.createObjectURL(o)),Se.onmessage=a=>{i.readyState===1&&i.send(JSON.stringify({action:"keepAlive"}));},n(i);},i.onmessage=async s=>{let o="";try{o=JSON.parse(decodeURI(s.data)),this.log("socket onmessage",o);}catch{return}let a;switch(true){case !!o?.["#message"]:a="message";break;case !!o?.["#private"]:a="private";break;case !!o?.["#notice"]:a="notice";break;case !!o?.["#rtc"]:a="rtc";break;case !!o?.["#error"]:a="error";break}if(!a)return;let u={type:a,message:o?.["#rtc"]||o?.["#message"]||o?.["#private"]||o?.["#notice"]||o?.["#error"]||null,sender:o?.["#user_id"]||null,sender_cid:o?.["#scid"]?"cid:"+o["#scid"]:null,sender_rid:o?.["#srid"]||null,code:o?.["#code"]||null};if(a==="notice")r(u);else if(a==="rtc"){if(u.sender!==this.user.user_id){let c=u.message;if(c.hungup){se[u.sender_cid]&&(se[u.sender_cid](false),delete se[u.sender_cid]),de[u.sender_cid]&&delete de[u.sender_cid],x?.[u.sender_cid]&&oe.bind(this)({cid:u.sender_cid}),u.type="rtc:closed",r(u);return}if(c.candidate&&Dr.bind(this)(c.candidate,u.sender_cid),c.sdpoffer&&(Cr.bind(this)(c.sdpoffer,u.sender_cid),de[u.sender_cid]||(de[u.sender_cid]=u.sender_cid,delete u.message,u.connectRTC=Wi.bind(this)(u),u.type="rtc:incoming",u.hangup=(()=>{x[u.sender_cid]?oe.bind(this)({cid:u.sender_cid}):de[u.sender_cid]&&(delete de[u.sender_cid],i.send(JSON.stringify({action:"rtc",uid:u.sender_cid,content:{hungup:this.user.user_id},token:this.session.accessToken.jwtToken})));}).bind(this),r(u))),c.pickup&&se[u.sender_cid]&&(se[u.sender_cid](true),delete se[u.sender_cid]),c.sdpanswer&&x[u.sender_cid])if(x[u.sender_cid].signalingState==="have-local-offer")await x[u.sender_cid].setRemoteDescription(new RTCSessionDescription(c.sdpanswer));else throw new f("Invalid signaling state.",{code:"INVALID_REQUEST"})}}else r(u);},i.onclose=()=>{rt?(this.log("realtime onclose","WebSocket connection closed."),r({type:"close",message:"WebSocket connection closed."})):(this.log("realtime onclose","WebSocket unexpected close."),r({type:"error",message:"Skapi: WebSocket unexpected close."}),We++,We<3?(this.log("realtime onclose","Reconnecting to WebSocket server..."+We),r({type:"reconnect",message:"Reconnecting to WebSocket server..."+We}),Vt.bind(this)(r,3e3,"reconnect")):(this.log("realtime onclose","Max reconnection attempts reached."),r({type:"error",message:"Skapi: Max reconnection attempts reached."})));},i.onerror=()=>{this.log("realtime onerror","WebSocket connection error."),r({type:"error",message:"Skapi: WebSocket connection error."});};},e);});}async function zi(r,e,t){if(typeof window>"u"||window._runningInNodeJS)throw new f("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});let n=this.__socket?await this.__socket:this.__socket;if(!n)throw new f("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});if(!e)throw new f("No recipient.",{code:"INVALID_REQUEST"});await je.bind(this)(),r=L(r).data;let i="";if(t&&(t=m.Params(t,{config:{always:"boolean"},title:"string",body:"string"},["title","body"]),i=JSON.stringify({title:t.title,body:t.body}),new Blob([i]).size>3072))throw new f("Notification size exceeds 3kb.",{code:"INVALID_PARAMETER"});if(n.readyState===1){try{m.UserId(e),n.send(JSON.stringify({action:"sendMessage",uid:e,content:r,notification:i,notificationConfig:t?.config||{},token:`IdT:${this.service}:${this.owner}:`+(this.bearerToken||this.session?.idToken?.jwtToken||"null")}));}catch(s){if(this.log("postRealtime:err",{err:s}),Ee!==e)throw new f(`User has not joined to the recipient group. Run joinRealtime({ group: "${e}" })`,{code:"INVALID_REQUEST"});n.send(JSON.stringify({action:"broadcast",rid:e,content:r,notification:i,notificationConfig:t?.config||{},token:`IdT:${this.service}:${this.owner}:`+(this.bearerToken||this.session?.idToken?.jwtToken||"null")}));}return {type:"success",message:"Message sent."}}throw new f("Realtime connection is not open. Try reconnecting with connectRealtime().",{code:"INVALID_REQUEST"})}async function Nr(r){if(typeof window>"u"||window._runningInNodeJS)throw new f("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});let e=this.__socket?await this.__socket:this.__socket;if(!e)throw new f("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});await je.bind(this)(),r=L(r,{nullIfEmpty:true}).data;let{group:t=null}=r;if(!t&&!Ee)return {type:"success",message:"Left realtime message group."};if(t!==null&&typeof t!="string")throw new f('"group" must be a string | null.',{code:"INVALID_PARAMETER"});return e.send(JSON.stringify({action:"joinRoom",rid:t,token:this.session.accessToken.jwtToken})),Ee=t,{type:"success",message:t?`Joined realtime message group: "${t}".`:"Left realtime message group."}}async function Yi(r,e){r=m.Params(r,{user_id:n=>m.UserId(n,'User ID in "user_id"'),group:["string",()=>{if(!Ee)throw new f('No group has been joined. Otherwise "group" is required.',{code:"INVALID_REQUEST"});return Ee}]});let t=await v.bind(this)("get-ws-group",r,{fetchOptions:e,auth:true,method:"post"});return t.list=t.list.map(n=>({user_id:n.uid.split("#")[1],cid:"cid:"+n.cid})),t}async function Xi(r,e){if(await this.__connection,r||(r={searchFor:"group",value:" ",condition:">"}),r=m.Params(r,{searchFor:["group","number_of_users",()=>"group"],value:["string","number",()=>r?.searchFor&&r?.searchFor==="number_of_users"?0:" "],condition:[">",">=","=","<","<=","!=","gt","gte","eq","lt","lte","ne"],range:["string","number"]}),r.condition||(r.value===" "||!r.value?r.condition=">":r.condition="="),r.range&&r.condition&&delete r.condition,r.searchFor==="number_of_users"&&typeof r.value!="number")throw new f('"value" must be a number.',{code:"INVALID_PARAMETER"});if(r.searchFor==="group"&&typeof r.value!="string")throw new f('"value" must be a string.',{code:"INVALID_PARAMETER"});if(r.hasOwnProperty("range")&&typeof r.range!=typeof r.value)throw new f(`"range" must be a ${typeof r.value}.`,{code:"INVALID_PARAMETER"});let t=await v.bind(this)("get-ws-group",r,{fetchOptions:e,auth:true,method:"post"});return t.list=t.list.map(n=>({group:n.rid.split("#")[1],number_of_users:n.cnt})),t}var Qu=typeof FormData<"u",zu=typeof HTMLFormElement<"u",Yu=typeof SubmitEvent<"u";function Zi({id:r,auth:e,service:t,owner:n,latency:i=1e3}){return new Promise((s,o)=>{let a=setInterval(async()=>{try{let u=await v.bind(this)("csr-poll",{id:r,service:t,owner:n},{auth:e});if(u.status==="pending")return;clearInterval(a),s(u);}catch(u){clearInterval(a),o(u);}},i);})}async function es(r){let e=false,t=typeof r.poll=="number"?r.poll:0;r.poll=!!r.poll;let n=s=>{for(let o in s)if(typeof s[o]=="string"&&s[o].includes("$CLIENT_SECRET")){e=true;break}};if(r=m.Params(r,{url:s=>{if(!s||typeof s!="string")throw new f('"url" should be type: <string>.',{code:"INVALID_PARAMETER"});return m.Url(s),s.includes("$CLIENT_SECRET")&&(e=true),s},clientSecretName:"string",method:s=>{if(s&&typeof s!="string")throw new f('"method" should be either "GET" or "POST" or "DELETE" or "PUT".',{code:"INVALID_PARAMETER"});let o=s.toLowerCase();if(o!=="get"&&o!=="post"&&o!=="delete"&&o!=="put")throw new f('"method" should be either "GET" or "POST" or "DELETE" or "PUT".',{code:"INVALID_PARAMETER"});return o},headers:s=>{if(s&&typeof s!="object")throw new f('"headers" should be type: <object>.',{code:"INVALID_PARAMETER"});return n(s),s},data:s=>{if(s&&typeof s!="object")throw new f('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return n(s),s},params:s=>{if(s&&typeof s!="object")throw new f('"params" should be type: <object>.',{code:"INVALID_PARAMETER"});return n(s),s},poll:"boolean",expires:"number",queue:"string"},["clientSecretName","method","url"]),!e)throw new f(`At least one parameter value should include "$CLIENT_SECRET" in ${r.method.toLowerCase()==="post"?'"data"':'"params"'} or "headers".`,{code:"INVALID_PARAMETER"});await this.__connection;let i=!!this.__user;return v.bind(this)("csr",r,{auth:i,tokenHeaders:{accessToken:!!i}}).then(s=>{if(t&&s.id&&s.status==="pending"){let o=`[${r.method.toUpperCase()}]${r.url.toLowerCase()}`;r.queue&&(o+="#"+r.queue);let a=o+":"+s.id;return Zi.call(this,{id:a,auth:i,service:r.service,owner:r.owner,latency:t})}else return s})}async function ts(r,e){await this.__connection;let t=!!r.poll,n=typeof r.poll=="number"?r.poll:1e3;r=m.Params(r,{url:"string",method:["GET","POST","DELETE","PUT"],queue:"string"},["url","method"]);let i=!!this.__user,s=`[${r.method.toUpperCase()}]${r.url.toLowerCase()}`;r.queue&&(s+="#"+r.queue),s+=":";let o=await v.bind(this)("csr-poll",{id:s,service:r.service,owner:r.owner},{auth:i,fetchOptions:e}),a=[];return o.list=o.list.map(u=>{let c={id:u.id,status_code:u.rslv?.status_code||null,response_body:u.rslv?.body||u.rslv?.truncated||null,error:u.err,updated:u.utmp,request_body:u.reqbdy,expires:u.stts!=="pending"?u.expt:null,status:u.stts||null};return t&&c.status==="pending"&&typeof c.id=="string"&&a.push(c.id),c}),t&&(o.pending=a.map(u=>Zi.call(this,{id:s+u,auth:i,service:r.service,owner:r.owner,latency:n}).then(c=>({...c})).catch(c=>({error:c,id:u})))),o}async function rs(r){await this.__connection;let e={name:"string",email:t=>(m.Email(t),t),subject:"string",message:"string"};return r=m.Params(r,e,["name","email","subject","message"]),await v.bind(this)("send-inquiry",r),"SUCCESS: Inquiry has been sent."}async function ns(r,e){if(await this.__connection,Qu&&r instanceof FormData||zu&&r instanceof HTMLFormElement||Yu&&r instanceof SubmitEvent){if(!e)throw new f("Url string as a second argument is required when form is passed.",{code:"INVALID_PARAMETER"});let n=L(r);r={url:e,data:n.data,sync:true};}let t={url:n=>m.Url(n),data:n=>n,sync:["boolean",()=>true]};if(Array.isArray(r))for(let n of r)n=m.Params(n,t);else r=m.Params(r,t);return v.bind(this)("post-secure",r,{auth:true})}async function is(r,e){await this.__connection;let{auth:t=false,method:n="POST",bypassAwaitConnection:i=false,responseType:s,contentType:o,tokenHeaders:a,progress:u}=e||{};if(e=Object.assign({auth:t,method:n,bypassAwaitConnection:i,responseType:s,contentType:o,tokenHeaders:a},{fetchOptions:{progress:u}}),typeof r!="object"&&(o==="application/json"||o===void 0))throw new f('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return v.bind(this)("mock",r,e)}async function ss(r,e){await this.__connection,r=m.Params(r||{},{access_group:n=>{if(n==="authorized"&&(n=1),n==="public"&&(n=0),typeof n!="number")throw new f('"access_group" should be type number.',{code:"INVALID_PARAMETER"});if(n<0)throw new f('"access_group" should be zero or a positive number.',{code:"INVALID_PARAMETER"});if(n>this.__user.access_group)throw new f("User has no access.",{code:"INVALID_REQUEST"});return n}});let t=await v.bind(this)("get-feed",r,{auth:true,fetchOptions:e});for(let n in t.list)t.list[n]=await He.bind(this)(t.list[n]);return t}function nt(r){if(r===this.__user.user_id)throw new f(`"user_id" cannot be the user's own ID.`,{code:"INVALID_PARAMETER"});return m.UserId(r,'"user_id"')}async function os(r,e){if(r=L(r,{ignoreEmpty:true}).data,r=m.Params(r,{subscriber:n=>m.UserId(n,'User ID in "subscriber"'),subscription:nt.bind(this),blocked:"boolean"}),!r.subscriber&&!r.subscription)throw new f('At least either "subscriber" or "subscription" should have a value.',{code:"INVALID_PARAMETER"});let t=await v.bind(this)("get-subscription",r,Object.assign({auth:true},{fetchOptions:e}));return t.list=t.list.map((n=>{let i={};if(n.sub){let s=n.sub.split("#");i.subscriber=s[2],i.subscription=s[0];}else i.subscriber=n.subscriber,i.subscription=n.subscription;return i.timestamp=n?.timestamp||n.stmp,i.blocked=n?.blocked||n.grp.substring(0,1)==="N",Object.assign(i,n.opt),i})),t}async function as(r){await this.__connection,r=m.Params(r,{user_id:nt.bind(this),get_feed:["boolean",()=>false],get_notified:["boolean",()=>false],get_email:n=>{if(n&&!this.__user.email||!this.__user.email_verified)throw new f("User has no verified email address.",{code:"INVALID_REQUEST"});return !!n}},["user_id"]);let e=await v.bind(this)("subscription",{subscribe:r.user_id,option:{get_feed:r.get_feed,get_notified:r.get_notified,get_email:r.get_email||false}},{auth:true}),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||e.grp.substring(0,1)==="N",Object.assign(t,e.opt),t}async function us(r){await this.__connection;let{user_id:e}=m.Params(r,{user_id:nt.bind(this)},["user_id"]);return await v.bind(this)("subscription",{unsubscribe:e},{auth:true})}async function cs(r){await this.__connection;let{user_id:e}=m.Params(r,{user_id:nt.bind(this)},["user_id"]);return await v.bind(this)("subscription",{block:e},{auth:true})}async function ls(r){await this.__connection;let{user_id:e}=m.Params(r,{user_id:nt.bind(this)},["user_id"]);return await v.bind(this)("subscription",{unblock:e},{auth:true})}async function ds(r,e){await this.__connection;let t=await J.bind(this)();r=m.Params(r,{user_id:o=>{if(o!==this.__user.user_id&&!t)throw new f("No access.",{code:"INVALID_REQUEST"});return o},group:o=>{if(o==="public"&&(o=0),o==="authorized"&&(o=1),typeof o!="number")throw new f('"group" should be type number | "public" | "authorized".',{code:"INVALID_PARAMETER"});return o}});let n=await v.bind(this)("get-newsletter-subscription",r,{auth:true,fetchOptions:e||null}),i=n?.list||n,s=[];Array.isArray(i)||(i=[]);for(let o of i){let a=o.subt.split("#"),u=true;a[0].charAt(0)==="@"&&(u=false,a[0]=a[0].substring(1));let c=parseInt(a[0]);s.push({timestamp:o.stmp,group:c,subscribed_email:a[1],active:u});}return n?.list?(n.list=s,n):s}async function fs(r){await this.__connection;let e=m.Params(r||{},{email:t=>Array.isArray(t)&&t.length>0?t.length===1?m.Email(t[0]):t.map(n=>m.Email(n)):m.Email(t),group:["number","public","authorized","admin",t=>{if(typeof t!="string"||t.length>20||!/^[a-zA-Z0-9]+$/.test(t))throw new f('"group" should be an alphanumeric string without spaces and less than 20 characters.',{code:"INVALID_PARAMETER"});return t}],redirect:t=>m.Url(t)},this.__user?["group"]:["email","group"]);return v.bind(this)(`subscribe-${this.__user?"":"public-"}newsletter`,e,{auth:!!this.__user})}async function hs(r){await this.__connection,r=m.Params(r,{group:["number","public","authorized","admin"]},["group"]);let e=Object.assign({action:"unsubscribe"},r);return v.bind(this)("subscribe-newsletter",e,{auth:true})}async function gs(r,e){let t=await J.bind(this)(),n={message_id:"string",timestamp:"number",read:"number",complaint:"number",subject:"string",bounced:"number"};r||(e=Object.assign({ascending:false},e||{})),r=L(r).data,r=r||{searchFor:"timestamp",value:Date.now(),condition:"<",group:"public"},r=m.Params(r,{searchFor:["message_id","timestamp","subject","complaint","read","bounced"],value:u=>{if(typeof u!==n[r.searchFor])throw new f(`"value" type does not match the type of "${r.searchFor}" index.`,{code:"INVALID_PARAMETER"});if(typeof u=="string"&&!u)throw new f('"value" should not be empty string.',{code:"INVALID_PARAMETER"});return u},range:u=>{if(!r.hasOwnProperty("value")||typeof u!=typeof r.value)throw new f('"range" should match type of "value".',{code:"INVALID_PARAMETER"});return u},condition:[">",">=","=","<","<=","gt","gte","eq","lt","lte",()=>"="],group:u=>{if(u==="public")return 0;if(!this.session)throw new f("User should be logged in.",{code:"INVALID_REQUEST"});if(u==="authorized")return 1;if(typeof u=="number"){if(!t&&u>parseInt(this.user?.access_group||this.session?.idToken?.payload?.access_group))throw new f("User has no access.",{code:"INVALID_REQUEST"});return u}throw new f('"group" should be type: number | "public" | "authorized".',{code:"INVALID_PARAMETER"})}},["searchFor","value","group"]);let i=r.group===0?"get-public-newsletters":"get-newsletters",s=await v.bind(this)(i,r,Object.assign({method:"get",auth:i==="get-public-newsletters"?!!this.__user:true},{fetchOptions:e})),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(u=>{let c={};for(let d in o)c[d]=u[o[d]]||a[d];return c.bounced=String(c.bounced),c}),s}async function ps(r){let e=m.Params(r,{user_id:n=>m.UserId(n,'"user_id"')},["user_id"]);if(e?.service&&e?.owner?e={service:e?.service,owner:e?.owner,block:e.user_id}:e={block:e.user_id},!await J.bind(this)()){if(!this.__user)throw new f("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new f("Invalid access.",{code:"INVALID_REQUEST"})}return await v.bind(this)("block-account",e,{auth:true})}async function ms(r){let e=m.Params(r,{user_id:n=>m.UserId(n,'"user_id"')},["user_id"]);if(e?.service&&e?.owner?e={service:e?.service,owner:e?.owner,unblock:e.user_id}:e={unblock:e.user_id},!await J.bind(this)()){if(!this.__user)throw new f("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new f("Invalid access.",{code:"INVALID_REQUEST"})}return await v.bind(this)("block-account",e,{auth:true})}async function _s(r){let e=m.Params(r,{user_id:n=>m.UserId(n,'"user_id"')},["user_id"]);if(e?.service&&e?.owner?e={service:e?.service,owner:e?.owner,delete:e.user_id}:e={delete:e.user_id},!await J.bind(this)()){if(!this.__user)throw new f("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new f("Invalid access.",{code:"INVALID_REQUEST"})}return await v.bind(this)("remove-account",e,{auth:true})}async function bs(r,e){let t={email:s=>m.Email(s),password:s=>m.Password(s),name:"string",username:"string",gender:"string",address:s=>{if(!s)return "";if(typeof s=="string")return s;if(typeof s=="object")return JSON.stringify(s)},birthdate:s=>m.Birthdate(s),phone_number:s=>m.PhoneNumber(s),picture:s=>{if(s)return m.Url(s)},profile:s=>{if(s)return m.Url(s)},website:s=>{if(s)return m.Url(s)},nickname:"string",misc:"string",email_public:["boolean",()=>false],gender_public:["boolean",()=>false],address_public:["boolean",()=>false],birthdate_public:["boolean",()=>false],phone_number_public:["boolean",()=>false],openid_id:"string",access_group:s=>{try{typeof s=="string"&&(s=s==="admin"?99:parseInt(s));}catch{throw new f('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof s!="number"||s<1||s>100)throw new f('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"});return s}},n=m.Params(r,t,["email"]);if(e=m.Params(e,{confirmation_url:s=>{let o=s;if(typeof s=="string")o=m.Url(s);else throw new f('"options.confirmation_url" should be type: <string>.',{code:"INVALID_PARAMETER"});if(o&&!n.email)throw new f('"email" is required for signup confirmation.',{code:"INVALID_PARAMETER"});return o},email_subscription:s=>{if(typeof s!="boolean")throw new f('"options.email_subscription" should be type: <boolean>.',{code:"INVALID_PARAMETER"});if(!e?.confirmation_url)throw new f('"options.confirmation_url" is required for email subscription.',{code:"INVALID_PARAMETER"});return s},template:s=>{if(typeof s!="object"||!s.url||!s.subject)throw new f('"options.template" should be type: <object> with "url" and "subject".',{code:"INVALID_PARAMETER"});return {url:m.Url(s.url),subject:s.subject}}}),n.signup_confirmation=e?.confirmation_url||true,n.email_subscription=e?.email_subscription||false,n.template=e?.template||{},!await J.bind(this)()){if(!this.__user)throw new f("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new f("Invalid access.",{code:"INVALID_REQUEST"})}return await v.bind(this)("admin-signup",n,{auth:true})}async function ys(r){let e={email:s=>m.Email(s),password:s=>m.Password(s),openid_id:"string",name:"string",username:"string",gender:"string",address:s=>{if(!s)return "";if(typeof s=="string")return s;if(typeof s=="object")return JSON.stringify(s)},birthdate:s=>m.Birthdate(s),phone_number:s=>m.PhoneNumber(s),picture:s=>s?m.Url(s):"",profile:s=>s?m.Url(s):"",website:s=>s?m.Url(s):"",nickname:"string",misc:"string",email_public:["boolean",()=>false],gender_public:["boolean",()=>false],address_public:["boolean",()=>false],birthdate_public:["boolean",()=>false],phone_number_public:["boolean",()=>false],access_group:s=>{try{typeof s=="string"&&(s=parseInt(s));}catch{throw new f('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof s!="number"||s<1||s>100)throw new f('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"});return s}},t=["email","password"],n=m.Params(r,e,t);if(!await J.bind(this)()){if(!this.__user)throw new f("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new f("Invalid access.",{code:"INVALID_REQUEST"})}return await v.bind(this)("admin-signup",n,{auth:true})}async function ws(r){if(r=m.Params(r,{user_id:t=>m.UserId(t,'"user_id"'),access_group:t=>{try{typeof t=="string"&&(t=parseInt(t));}catch{throw new f('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof t=="number"&&t>0&&t<100)return t;throw new f('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"})}},["user_id","access_group"]),!await J.bind(this)()){if(!this.__user)throw new f("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new f("Invalid access.",{code:"INVALID_REQUEST"})}return await v.bind(this)("grant-access",r,{auth:true})}async function As(r,e){if(r=m.Params(r,{email:"string"}),!await J.bind(this)()){if(!this.__user)throw new f("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new f("Invalid access.",{code:"INVALID_REQUEST"})}let n=await v.bind(this)("invitation-list",Object.assign({mode:"search"},r),{fetchOptions:e,auth:true});return n.list=n.list.map(i=>ze(i.user)),n}async function Ss(r){if(r=m.Params(r,{email:t=>m.Email(t)},["email"]),!await J.bind(this)()){if(!this.__user)throw new f("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new f("Invalid access.",{code:"INVALID_REQUEST"})}return await v.bind(this)("invitation-list",Object.assign({mode:"cancel"},r),{auth:true})}async function Es(r){if(r=m.Params(r,{email:t=>m.Email(t)},["email"]),!await J.bind(this)()){if(!this.__user)throw new f("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new f("Invalid access.",{code:"INVALID_REQUEST"})}return await v.bind(this)("invitation-list",Object.assign({mode:"resend"},r),{auth:true})}async function vs(r){if(typeof window>"u"||window._runningInNodeJS)throw new f("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.__connection,!r.endpoint)throw new f("Missing parameter: endpoint",{code:"INVALID_PARAMETER"});if(!r.keys||!r.keys.p256dh||!r.keys.auth)throw new f("Missing parameter: keys.p256dh or keys.auth",{code:"INVALID_PARAMETER"});return await v.bind(this)("store-subscription",{endpoint:r.endpoint,keys:r.keys},{auth:true}),"SUCCESS: Subscribed to receive notifications."}async function Ts(r){if(typeof window>"u"||window._runningInNodeJS)throw new f("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.__connection,!r.endpoint)throw new f("Missing parameter: endpoint",{code:"INVALID_PARAMETER"});if(!r.keys||!r.keys.p256dh||!r.keys.auth)throw new f("Missing parameter: keys.p256dh or keys.auth",{code:"INVALID_PARAMETER"});return await v.bind(this)("delete-subscription",{endpoint:r.endpoint,keys:r.keys},{auth:true}),"SUCCESS: Unsubscribed from notifications."}async function Rs(){if(typeof window>"u"||window._runningInNodeJS)throw new f("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});return await this.__connection,{VAPIDPublicKey:await v.bind(this)("get-vapid-public-key",null,{auth:true})}}async function Is(r,e){if(typeof window>"u"||window._runningInNodeJS)throw new f("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});await this.__connection;let{title:t,body:n}=L(r||{},{nullIfEmpty:true}).data;if(!t)throw new f("Missing parameter: message title",{code:"INVALID_PARAMETER"});if(!n)throw new f("Missing parameter: message body",{code:"INVALID_PARAMETER"});let i={title:t,body:n};return e?(typeof e=="string"&&(e=[e]),i.user_ids=e):i.user_ids="all_users",await v.bind(this)("push-notification",i,{auth:true}),"SUCCESS: Notification sent."}async function Ps(r){await this.__connection,r=m.Params(r,{spell:"string",name:"string",magic:t=>t},["spell","name"]);await v.bind(this)("castspell",r);return `The spell "${r.spell}" has been cast.`}async function xs(r){return await this.__connection,r=m.Params(r||{},{search:["spell","name",()=>"spell"],value:"string"}),await v.bind(this)("getspell",r)}async function Us(r){await this.__connection,r=m.Params(r,{message:"string",name:"string"},["message","name"]);let e=await v.bind(this)("dopamine",r,{auth:true}),t=e?.previous_message?.message,n=e?.previous_message?.name;if(z())t&&n&&window.alert(`${n} said: ${t}`),window.location.href=e.video;else return t&&n?`${n} said: ${t}
216
+ `,o=new Blob([s],{type:"application/javascript"});Ee=new Worker(URL.createObjectURL(o)),Ee.onmessage=a=>{i.readyState===1&&i.send(JSON.stringify({action:"keepAlive"}));},n(i);},i.onmessage=async s=>{let o="";try{o=JSON.parse(decodeURI(s.data)),this.log("socket onmessage",o);}catch{return}let a;switch(true){case !!o?.["#message"]:a="message";break;case !!o?.["#private"]:a="private";break;case !!o?.["#notice"]:a="notice";break;case !!o?.["#rtc"]:a="rtc";break;case !!o?.["#error"]:a="error";break}if(!a)return;let u={type:a,message:o?.["#rtc"]||o?.["#message"]||o?.["#private"]||o?.["#notice"]||o?.["#error"]||null,sender:o?.["#user_id"]||null,sender_cid:o?.["#scid"]?"cid:"+o["#scid"]:null,sender_rid:o?.["#srid"]||null,code:o?.["#code"]||null};if(a==="notice")r(u);else if(a==="rtc"){if(u.sender!==this.user.user_id){let c=u.message;if(c.hungup){se[u.sender_cid]&&(se[u.sender_cid](false),delete se[u.sender_cid]),de[u.sender_cid]&&delete de[u.sender_cid],x?.[u.sender_cid]&&oe.bind(this)({cid:u.sender_cid}),u.type="rtc:closed",r(u);return}if(c.candidate&&Dr.bind(this)(c.candidate,u.sender_cid),c.sdpoffer&&(Cr.bind(this)(c.sdpoffer,u.sender_cid),de[u.sender_cid]||(de[u.sender_cid]=u.sender_cid,delete u.message,u.connectRTC=Wi.bind(this)(u),u.type="rtc:incoming",u.hangup=(()=>{x[u.sender_cid]?oe.bind(this)({cid:u.sender_cid}):de[u.sender_cid]&&(delete de[u.sender_cid],i.send(JSON.stringify({action:"rtc",uid:u.sender_cid,content:{hungup:this.user.user_id},token:this.session.accessToken.jwtToken})));}).bind(this),r(u))),c.pickup&&se[u.sender_cid]&&(se[u.sender_cid](true),delete se[u.sender_cid]),c.sdpanswer&&x[u.sender_cid])if(x[u.sender_cid].signalingState==="have-local-offer")await x[u.sender_cid].setRemoteDescription(new RTCSessionDescription(c.sdpanswer));else throw new f("Invalid signaling state.",{code:"INVALID_REQUEST"})}}else r(u);},i.onclose=()=>{rt?(this.log("realtime onclose","WebSocket connection closed."),r({type:"close",message:"WebSocket connection closed."})):(this.log("realtime onclose","WebSocket unexpected close."),r({type:"error",message:"Skapi: WebSocket unexpected close."}),We++,We<3?(this.log("realtime onclose","Reconnecting to WebSocket server..."+We),r({type:"reconnect",message:"Reconnecting to WebSocket server..."+We}),Vt.bind(this)(r,3e3,"reconnect")):(this.log("realtime onclose","Max reconnection attempts reached."),r({type:"error",message:"Skapi: Max reconnection attempts reached."})));},i.onerror=()=>{this.log("realtime onerror","WebSocket connection error."),r({type:"error",message:"Skapi: WebSocket connection error."});};},e);});}async function zi(r,e,t){if(typeof window>"u"||window._runningInNodeJS)throw new f("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});let n=this.__socket?await this.__socket:this.__socket;if(!n)throw new f("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});if(!e)throw new f("No recipient.",{code:"INVALID_REQUEST"});await je.bind(this)(),r=L(r).data;let i="";if(t&&(t=m.Params(t,{config:{always:"boolean"},title:"string",body:"string"},["title","body"]),i=JSON.stringify({title:t.title,body:t.body}),new Blob([i]).size>3072))throw new f("Notification size exceeds 3kb.",{code:"INVALID_PARAMETER"});if(n.readyState===1){try{m.UserId(e),n.send(JSON.stringify({action:"sendMessage",uid:e,content:r,notification:i,notificationConfig:t?.config||{},token:`IdT:${this.service}:${this.owner}:`+(this.bearerToken||this.session?.idToken?.jwtToken||"null")}));}catch(s){if(this.log("postRealtime:err",{err:s}),Se!==e)throw new f(`User has not joined to the recipient group. Run joinRealtime({ group: "${e}" })`,{code:"INVALID_REQUEST"});n.send(JSON.stringify({action:"broadcast",rid:e,content:r,notification:i,notificationConfig:t?.config||{},token:`IdT:${this.service}:${this.owner}:`+(this.bearerToken||this.session?.idToken?.jwtToken||"null")}));}return {type:"success",message:"Message sent."}}throw new f("Realtime connection is not open. Try reconnecting with connectRealtime().",{code:"INVALID_REQUEST"})}async function Nr(r){if(typeof window>"u"||window._runningInNodeJS)throw new f("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});let e=this.__socket?await this.__socket:this.__socket;if(!e)throw new f("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});await je.bind(this)(),r=L(r,{nullIfEmpty:true}).data;let{group:t=null}=r;if(!t&&!Se)return {type:"success",message:"Left realtime message group."};if(t!==null&&typeof t!="string")throw new f('"group" must be a string | null.',{code:"INVALID_PARAMETER"});return e.send(JSON.stringify({action:"joinRoom",rid:t,token:this.session.accessToken.jwtToken})),Se=t,{type:"success",message:t?`Joined realtime message group: "${t}".`:"Left realtime message group."}}async function Yi(r,e){r=m.Params(r,{user_id:n=>m.UserId(n,'User ID in "user_id"'),group:["string",()=>{if(!Se)throw new f('No group has been joined. Otherwise "group" is required.',{code:"INVALID_REQUEST"});return Se}]});let t=await v.bind(this)("get-ws-group",r,{fetchOptions:e,auth:true,method:"post"});return t.list=t.list.map(n=>({user_id:n.uid.split("#")[1],cid:"cid:"+n.cid})),t}async function Xi(r,e){if(await this.__connection,r||(r={searchFor:"group",value:" ",condition:">"}),r=m.Params(r,{searchFor:["group","number_of_users",()=>"group"],value:["string","number",()=>r?.searchFor&&r?.searchFor==="number_of_users"?0:" "],condition:[">",">=","=","<","<=","!=","gt","gte","eq","lt","lte","ne"],range:["string","number"]}),r.condition||(r.value===" "||!r.value?r.condition=">":r.condition="="),r.range&&r.condition&&delete r.condition,r.searchFor==="number_of_users"&&typeof r.value!="number")throw new f('"value" must be a number.',{code:"INVALID_PARAMETER"});if(r.searchFor==="group"&&typeof r.value!="string")throw new f('"value" must be a string.',{code:"INVALID_PARAMETER"});if(r.hasOwnProperty("range")&&typeof r.range!=typeof r.value)throw new f(`"range" must be a ${typeof r.value}.`,{code:"INVALID_PARAMETER"});let t=await v.bind(this)("get-ws-group",r,{fetchOptions:e,auth:true,method:"post"});return t.list=t.list.map(n=>({group:n.rid.split("#")[1],number_of_users:n.cnt})),t}var Qu=typeof FormData<"u",zu=typeof HTMLFormElement<"u",Yu=typeof SubmitEvent<"u";function Zi({id:r,auth:e,service:t,owner:n,latency:i=1e3}){return new Promise((s,o)=>{let a=setInterval(async()=>{try{let u=await v.bind(this)("csr-poll",{id:r,service:t,owner:n},{auth:e});if(u.status==="pending")return;clearInterval(a),s(u);}catch(u){clearInterval(a),o(u);}},i);})}async function es(r){let e=false,t=typeof r.poll=="number"?r.poll:0;r.poll=!!r.poll;let n=s=>{for(let o in s)if(typeof s[o]=="string"&&s[o].includes("$CLIENT_SECRET")){e=true;break}};if(r=m.Params(r,{url:s=>{if(!s||typeof s!="string")throw new f('"url" should be type: <string>.',{code:"INVALID_PARAMETER"});return m.Url(s),s.includes("$CLIENT_SECRET")&&(e=true),s},clientSecretName:"string",method:s=>{if(s&&typeof s!="string")throw new f('"method" should be either "GET" or "POST" or "DELETE" or "PUT".',{code:"INVALID_PARAMETER"});let o=s.toLowerCase();if(o!=="get"&&o!=="post"&&o!=="delete"&&o!=="put")throw new f('"method" should be either "GET" or "POST" or "DELETE" or "PUT".',{code:"INVALID_PARAMETER"});return o},headers:s=>{if(s&&typeof s!="object")throw new f('"headers" should be type: <object>.',{code:"INVALID_PARAMETER"});return n(s),s},data:s=>{if(s&&typeof s!="object")throw new f('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return n(s),s},params:s=>{if(s&&typeof s!="object")throw new f('"params" should be type: <object>.',{code:"INVALID_PARAMETER"});return n(s),s},poll:"boolean",expires:"number",queue:"string"},["clientSecretName","method","url"]),!e)throw new f(`At least one parameter value should include "$CLIENT_SECRET" in ${r.method.toLowerCase()==="post"?'"data"':'"params"'} or "headers".`,{code:"INVALID_PARAMETER"});await this.__connection;let i=!!this.__user;return v.bind(this)("csr",r,{auth:i,tokenHeaders:{accessToken:!!i}}).then(s=>{if(t&&s.id&&s.status==="pending"){let o=`[${r.method.toUpperCase()}]${r.url.toLowerCase()}`;r.queue&&(o+="#"+r.queue);let a=o+":"+s.id;return Zi.call(this,{id:a,auth:i,service:r.service,owner:r.owner,latency:t})}else return s})}async function ts(r,e){await this.__connection;let t=!!r.poll,n=typeof r.poll=="number"?r.poll:1e3;r=m.Params(r,{url:"string",method:["GET","POST","DELETE","PUT"],queue:"string"},["url","method"]);let i=!!this.__user,s=`[${r.method.toUpperCase()}]${r.url.toLowerCase()}`;r.queue&&(s+="#"+r.queue),s+=":";let o=await v.bind(this)("csr-poll",{id:s,service:r.service,owner:r.owner},{auth:i,fetchOptions:e}),a=[];return o.list=o.list.map(u=>{let c={id:u.id,status_code:u.rslv?.status_code||null,response_body:u.rslv?.body||u.rslv?.truncated||null,error:u.err,updated:u.utmp,request_body:u.reqbdy,expires:u.stts!=="pending"?u.expt:null,status:u.stts||null};return t&&c.status==="pending"&&typeof c.id=="string"&&a.push(c.id),c}),t&&(o.pending=a.map(u=>Zi.call(this,{id:s+u,auth:i,service:r.service,owner:r.owner,latency:n}).then(c=>({...c})).catch(c=>({error:c,id:u})))),o}async function rs(r){await this.__connection;let e={name:"string",email:t=>(m.Email(t),t),subject:"string",message:"string"};return r=m.Params(r,e,["name","email","subject","message"]),await v.bind(this)("send-inquiry",r),"SUCCESS: Inquiry has been sent."}async function ns(r,e){if(await this.__connection,Qu&&r instanceof FormData||zu&&r instanceof HTMLFormElement||Yu&&r instanceof SubmitEvent){if(!e)throw new f("Url string as a second argument is required when form is passed.",{code:"INVALID_PARAMETER"});let n=L(r);r={url:e,data:n.data,sync:true};}let t={url:n=>m.Url(n),data:n=>n,sync:["boolean",()=>true]};if(Array.isArray(r))for(let n of r)n=m.Params(n,t);else r=m.Params(r,t);return v.bind(this)("post-secure",r,{auth:true})}async function is(r,e){await this.__connection;let{auth:t=false,method:n="POST",bypassAwaitConnection:i=false,responseType:s,contentType:o,tokenHeaders:a,progress:u}=e||{};if(e=Object.assign({auth:t,method:n,bypassAwaitConnection:i,responseType:s,contentType:o,tokenHeaders:a},{fetchOptions:{progress:u}}),typeof r!="object"&&(o==="application/json"||o===void 0))throw new f('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return v.bind(this)("mock",r,e)}async function ss(r,e){await this.__connection,r=m.Params(r||{},{access_group:n=>{if(n==="authorized"&&(n=1),n==="public"&&(n=0),typeof n!="number")throw new f('"access_group" should be type number.',{code:"INVALID_PARAMETER"});if(n<0)throw new f('"access_group" should be zero or a positive number.',{code:"INVALID_PARAMETER"});if(n>this.__user.access_group)throw new f("User has no access.",{code:"INVALID_REQUEST"});return n}});let t=await v.bind(this)("get-feed",r,{auth:true,fetchOptions:e});for(let n in t.list)t.list[n]=await He.bind(this)(t.list[n]);return t}function nt(r){if(r===this.__user.user_id)throw new f(`"user_id" cannot be the user's own ID.`,{code:"INVALID_PARAMETER"});return m.UserId(r,'"user_id"')}async function os(r,e){if(r=L(r,{ignoreEmpty:true}).data,r=m.Params(r,{subscriber:n=>m.UserId(n,'User ID in "subscriber"'),subscription:nt.bind(this),blocked:"boolean"}),!r.subscriber&&!r.subscription)throw new f('At least either "subscriber" or "subscription" should have a value.',{code:"INVALID_PARAMETER"});let t=await v.bind(this)("get-subscription",r,Object.assign({auth:true},{fetchOptions:e}));return t.list=t.list.map((n=>{let i={};if(n.sub){let s=n.sub.split("#");i.subscriber=s[2],i.subscription=s[0];}else i.subscriber=n.subscriber,i.subscription=n.subscription;return i.timestamp=n?.timestamp||n.stmp,i.blocked=n?.blocked||n.grp.substring(0,1)==="N",Object.assign(i,n.opt),i})),t}async function as(r){await this.__connection,r=m.Params(r,{user_id:nt.bind(this),get_feed:["boolean",()=>false],get_notified:["boolean",()=>false],get_email:n=>{if(n&&!this.__user.email||!this.__user.email_verified)throw new f("User has no verified email address.",{code:"INVALID_REQUEST"});return !!n}},["user_id"]);let e=await v.bind(this)("subscription",{subscribe:r.user_id,option:{get_feed:r.get_feed,get_notified:r.get_notified,get_email:r.get_email||false}},{auth:true}),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||e.grp.substring(0,1)==="N",Object.assign(t,e.opt),t}async function us(r){await this.__connection;let{user_id:e}=m.Params(r,{user_id:nt.bind(this)},["user_id"]);return await v.bind(this)("subscription",{unsubscribe:e},{auth:true})}async function cs(r){await this.__connection;let{user_id:e}=m.Params(r,{user_id:nt.bind(this)},["user_id"]);return await v.bind(this)("subscription",{block:e},{auth:true})}async function ls(r){await this.__connection;let{user_id:e}=m.Params(r,{user_id:nt.bind(this)},["user_id"]);return await v.bind(this)("subscription",{unblock:e},{auth:true})}async function ds(r,e){await this.__connection;let t=await J.bind(this)();r=m.Params(r,{user_id:o=>{if(o!==this.__user.user_id&&!t)throw new f("No access.",{code:"INVALID_REQUEST"});return o},group:o=>{if(o==="public"&&(o=0),o==="authorized"&&(o=1),typeof o!="number")throw new f('"group" should be type number | "public" | "authorized".',{code:"INVALID_PARAMETER"});return o}});let n=await v.bind(this)("get-newsletter-subscription",r,{auth:true,fetchOptions:e||null}),i=n?.list||n,s=[];Array.isArray(i)||(i=[]);for(let o of i){let a=o.subt.split("#"),u=true;a[0].charAt(0)==="@"&&(u=false,a[0]=a[0].substring(1));let c=parseInt(a[0]);s.push({timestamp:o.stmp,group:c,subscribed_email:a[1],active:u});}return n?.list?(n.list=s,n):s}async function fs(r){await this.__connection;let e=m.Params(r||{},{email:t=>Array.isArray(t)&&t.length>0?t.length===1?m.Email(t[0]):t.map(n=>m.Email(n)):m.Email(t),group:["number","public","authorized","admin",t=>{if(typeof t!="string"||t.length>20||!/^[a-zA-Z0-9]+$/.test(t))throw new f('"group" should be an alphanumeric string without spaces and less than 20 characters.',{code:"INVALID_PARAMETER"});return t}],redirect:t=>m.Url(t)},this.__user?["group"]:["email","group"]);return v.bind(this)(`subscribe-${this.__user?"":"public-"}newsletter`,e,{auth:!!this.__user})}async function hs(r){await this.__connection,r=m.Params(r,{group:["number","public","authorized","admin"]},["group"]);let e=Object.assign({action:"unsubscribe"},r);return v.bind(this)("subscribe-newsletter",e,{auth:true})}async function gs(r,e){let t=await J.bind(this)(),n={message_id:"string",timestamp:"number",read:"number",complaint:"number",subject:"string",bounced:"number"};r||(e=Object.assign({ascending:false},e||{})),r=L(r).data,r=r||{searchFor:"timestamp",value:Date.now(),condition:"<",group:"public"},r=m.Params(r,{searchFor:["message_id","timestamp","subject","complaint","read","bounced"],value:u=>{if(typeof u!==n[r.searchFor])throw new f(`"value" type does not match the type of "${r.searchFor}" index.`,{code:"INVALID_PARAMETER"});if(typeof u=="string"&&!u)throw new f('"value" should not be empty string.',{code:"INVALID_PARAMETER"});return u},range:u=>{if(!r.hasOwnProperty("value")||typeof u!=typeof r.value)throw new f('"range" should match type of "value".',{code:"INVALID_PARAMETER"});return u},condition:[">",">=","=","<","<=","gt","gte","eq","lt","lte",()=>"="],group:u=>{if(u==="public")return 0;if(!this.session)throw new f("User should be logged in.",{code:"INVALID_REQUEST"});if(u==="authorized")return 1;if(typeof u=="number"){if(!t&&u>parseInt(this.user?.access_group||this.session?.idToken?.payload?.access_group))throw new f("User has no access.",{code:"INVALID_REQUEST"});return u}throw new f('"group" should be type: number | "public" | "authorized".',{code:"INVALID_PARAMETER"})}},["searchFor","value","group"]);let i=r.group===0?"get-public-newsletters":"get-newsletters",s=await v.bind(this)(i,r,Object.assign({method:"get",auth:i==="get-public-newsletters"?!!this.__user:true},{fetchOptions:e})),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(u=>{let c={};for(let d in o)c[d]=u[o[d]]||a[d];return c.bounced=String(c.bounced),c}),s}async function ps(r){let e=m.Params(r,{user_id:n=>m.UserId(n,'"user_id"')},["user_id"]);if(e?.service&&e?.owner?e={service:e?.service,owner:e?.owner,block:e.user_id}:e={block:e.user_id},!await J.bind(this)()){if(!this.__user)throw new f("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new f("Invalid access.",{code:"INVALID_REQUEST"})}return await v.bind(this)("block-account",e,{auth:true})}async function ms(r){let e=m.Params(r,{user_id:n=>m.UserId(n,'"user_id"')},["user_id"]);if(e?.service&&e?.owner?e={service:e?.service,owner:e?.owner,unblock:e.user_id}:e={unblock:e.user_id},!await J.bind(this)()){if(!this.__user)throw new f("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new f("Invalid access.",{code:"INVALID_REQUEST"})}return await v.bind(this)("block-account",e,{auth:true})}async function _s(r){let e=m.Params(r,{user_id:n=>m.UserId(n,'"user_id"')},["user_id"]);if(e?.service&&e?.owner?e={service:e?.service,owner:e?.owner,delete:e.user_id}:e={delete:e.user_id},!await J.bind(this)()){if(!this.__user)throw new f("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new f("Invalid access.",{code:"INVALID_REQUEST"})}return await v.bind(this)("remove-account",e,{auth:true})}async function bs(r,e){let t={email:s=>m.Email(s),password:s=>m.Password(s),name:"string",username:"string",gender:"string",address:s=>{if(!s)return "";if(typeof s=="string")return s;if(typeof s=="object")return JSON.stringify(s)},birthdate:s=>m.Birthdate(s),phone_number:s=>m.PhoneNumber(s),picture:s=>{if(s)return m.Url(s)},profile:s=>{if(s)return m.Url(s)},website:s=>{if(s)return m.Url(s)},nickname:"string",misc:"string",email_public:["boolean",()=>false],gender_public:["boolean",()=>false],address_public:["boolean",()=>false],birthdate_public:["boolean",()=>false],phone_number_public:["boolean",()=>false],openid_id:"string",access_group:s=>{try{typeof s=="string"&&(s=s==="admin"?99:parseInt(s));}catch{throw new f('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof s!="number"||s<1||s>100)throw new f('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"});return s}},n=m.Params(r,t,["email"]);if(e=m.Params(e,{confirmation_url:s=>{let o=s;if(typeof s=="string")o=m.Url(s);else throw new f('"options.confirmation_url" should be type: <string>.',{code:"INVALID_PARAMETER"});if(o&&!n.email)throw new f('"email" is required for signup confirmation.',{code:"INVALID_PARAMETER"});return o},email_subscription:s=>{if(typeof s!="boolean")throw new f('"options.email_subscription" should be type: <boolean>.',{code:"INVALID_PARAMETER"});if(!e?.confirmation_url)throw new f('"options.confirmation_url" is required for email subscription.',{code:"INVALID_PARAMETER"});return s},template:s=>{if(typeof s!="object"||!s.url||!s.subject)throw new f('"options.template" should be type: <object> with "url" and "subject".',{code:"INVALID_PARAMETER"});return {url:m.Url(s.url),subject:s.subject}}}),n.signup_confirmation=e?.confirmation_url||true,n.email_subscription=e?.email_subscription||false,n.template=e?.template||{},!await J.bind(this)()){if(!this.__user)throw new f("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new f("Invalid access.",{code:"INVALID_REQUEST"})}return await v.bind(this)("admin-signup",n,{auth:true})}async function ys(r){let e={email:s=>m.Email(s),password:s=>m.Password(s),openid_id:"string",name:"string",username:"string",gender:"string",address:s=>{if(!s)return "";if(typeof s=="string")return s;if(typeof s=="object")return JSON.stringify(s)},birthdate:s=>m.Birthdate(s),phone_number:s=>m.PhoneNumber(s),picture:s=>s?m.Url(s):"",profile:s=>s?m.Url(s):"",website:s=>s?m.Url(s):"",nickname:"string",misc:"string",email_public:["boolean",()=>false],gender_public:["boolean",()=>false],address_public:["boolean",()=>false],birthdate_public:["boolean",()=>false],phone_number_public:["boolean",()=>false],access_group:s=>{try{typeof s=="string"&&(s=parseInt(s));}catch{throw new f('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof s!="number"||s<1||s>100)throw new f('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"});return s}},t=["email","password"],n=m.Params(r,e,t);if(!await J.bind(this)()){if(!this.__user)throw new f("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new f("Invalid access.",{code:"INVALID_REQUEST"})}return await v.bind(this)("admin-signup",n,{auth:true})}async function ws(r){if(r=m.Params(r,{user_id:t=>m.UserId(t,'"user_id"'),access_group:t=>{try{typeof t=="string"&&(t=parseInt(t));}catch{throw new f('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof t=="number"&&t>0&&t<100)return t;throw new f('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"})}},["user_id","access_group"]),!await J.bind(this)()){if(!this.__user)throw new f("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new f("Invalid access.",{code:"INVALID_REQUEST"})}return await v.bind(this)("grant-access",r,{auth:true})}async function As(r,e){if(r=m.Params(r,{email:"string"}),!await J.bind(this)()){if(!this.__user)throw new f("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new f("Invalid access.",{code:"INVALID_REQUEST"})}let n=await v.bind(this)("invitation-list",Object.assign({mode:"search"},r),{fetchOptions:e,auth:true});return n.list=n.list.map(i=>ze(i.user)),n}async function Es(r){if(r=m.Params(r,{email:t=>m.Email(t)},["email"]),!await J.bind(this)()){if(!this.__user)throw new f("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new f("Invalid access.",{code:"INVALID_REQUEST"})}return await v.bind(this)("invitation-list",Object.assign({mode:"cancel"},r),{auth:true})}async function Ss(r){if(r=m.Params(r,{email:t=>m.Email(t)},["email"]),!await J.bind(this)()){if(!this.__user)throw new f("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new f("Invalid access.",{code:"INVALID_REQUEST"})}return await v.bind(this)("invitation-list",Object.assign({mode:"resend"},r),{auth:true})}async function vs(r){if(typeof window>"u"||window._runningInNodeJS)throw new f("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.__connection,!r.endpoint)throw new f("Missing parameter: endpoint",{code:"INVALID_PARAMETER"});if(!r.keys||!r.keys.p256dh||!r.keys.auth)throw new f("Missing parameter: keys.p256dh or keys.auth",{code:"INVALID_PARAMETER"});return await v.bind(this)("store-subscription",{endpoint:r.endpoint,keys:r.keys},{auth:true}),"SUCCESS: Subscribed to receive notifications."}async function Ts(r){if(typeof window>"u"||window._runningInNodeJS)throw new f("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.__connection,!r.endpoint)throw new f("Missing parameter: endpoint",{code:"INVALID_PARAMETER"});if(!r.keys||!r.keys.p256dh||!r.keys.auth)throw new f("Missing parameter: keys.p256dh or keys.auth",{code:"INVALID_PARAMETER"});return await v.bind(this)("delete-subscription",{endpoint:r.endpoint,keys:r.keys},{auth:true}),"SUCCESS: Unsubscribed from notifications."}async function Rs(){if(typeof window>"u"||window._runningInNodeJS)throw new f("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});return await this.__connection,{VAPIDPublicKey:await v.bind(this)("get-vapid-public-key",null,{auth:true})}}async function Is(r,e){if(typeof window>"u"||window._runningInNodeJS)throw new f("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});await this.__connection;let{title:t,body:n}=L(r||{},{nullIfEmpty:true}).data;if(!t)throw new f("Missing parameter: message title",{code:"INVALID_PARAMETER"});if(!n)throw new f("Missing parameter: message body",{code:"INVALID_PARAMETER"});let i={title:t,body:n};return e?(typeof e=="string"&&(e=[e]),i.user_ids=e):i.user_ids="all_users",await v.bind(this)("push-notification",i,{auth:true}),"SUCCESS: Notification sent."}async function Ps(r){await this.__connection,r=m.Params(r,{spell:"string",name:"string",magic:t=>t},["spell","name"]);await v.bind(this)("castspell",r);return `The spell "${r.spell}" has been cast.`}async function xs(r){return await this.__connection,r=m.Params(r||{},{search:["spell","name",()=>"spell"],value:"string"}),await v.bind(this)("getspell",r)}async function Us(r){await this.__connection,r=m.Params(r,{message:"string",name:"string"},["message","name"]);let e=await v.bind(this)("dopamine",r,{auth:true}),t=e?.previous_message?.message,n=e?.previous_message?.name;if(z())t&&n&&window.alert(`${n} said: ${t}`),window.location.href=e.video;else return t&&n?`${n} said: ${t}
217
217
  Watch the video here: ${e.video}`:`Your message has been uploaded for future generations to receive.
218
- Watch the video here: ${e.video}`}var S=class{constructor(e,t,n,i){this.__version="1.5.6-beta.0";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=false;this.__user=null;this._userProfileListeners=[];this._onLoginListeners=[];this._onBatchProcessListeners=[];this.validate={userId(e){try{return m.UserId(e),!0}catch{return false}},url(e){try{return m.Url(e),!0}catch{return false}},phoneNumber(e){try{return m.PhoneNumber(e),!0}catch{return false}},birthdate(e){try{return m.Birthdate(e),!0}catch{return false}},email(e){try{return m.Email(e),!0}catch{return false}},params(e,t,n){return m.Params(e,t,n)}};this.util={MD5:Q,generateRandom:Qe,toBase62:Wn,fromBase62:ne,decodeServiceId:Sr,formatServiceId:Jn,extractFormData:L,terminatePendingRequests:Ai,request:(e,t,n)=>v.bind(this)(e,t,n,{ignoreService:true})};this.__network_logs=false;this.__endpoint_version="v1";this.__public_identifier="";this.bearerToken="";this.registerTicket=Xn.bind(this);this.unregisterTicket=Zn.bind(this);if(!e||typeof e!="string")throw this._alert("Service ID is required."),new f("Service ID is required.",{code:"INVALID_PARAMETER"});let s=e.split("-").length;if(s===2||s===7)try{let h=Sr(e);n&&typeof n=="object"&&(i=n),t&&typeof t=="object"&&(n=t),t=h.owner,e=h.service;}catch{throw this._alert("Service ID is invalid."),new f("Service ID is invalid.",{code:"INVALID_PARAMETER"})}if(!t||typeof t!="string")throw this._alert("Owner ID is invalid."),new f("Owner ID is invalid.",{code:"INVALID_PARAMETER"});if(e.toLowerCase()==="service_id")throw this._alert('Replace "service_id" with your actual Service ID.'),new f("Service ID is required.",{code:"INVALID_PARAMETER"});if(t!==this.host)try{m.UserId(t,'"owner"');}catch{throw this._alert("Owner ID is invalid."),new f("Owner ID is invalid.",{code:"INVALID_PARAMETER"})}this.service=e,this.owner=t;let u=true;if(n&&(typeof n.autoLogin=="boolean"&&(u=n.autoLogin),typeof n.requestBatchSize=="number")){if(n.requestBatchSize<1)throw new f('"requestBatchSize" must be greater than 0.',{code:"INVALID_PARAMETER"});this.requestBatchSize=n.requestBatchSize;}n?.eventListener&&typeof n.eventListener=="object"&&(n.eventListener?.onLogin&&typeof n.eventListener.onLogin=="function"&&(this.onLogin=n.eventListener.onLogin),n.eventListener?.onUserUpdate&&typeof n.eventListener.onUserUpdate=="function"&&(this.onUserUpdate=n.eventListener.onUserUpdate),n.eventListener?.onBatchProcess&&typeof n.eventListener.onBatchProcess=="function"&&(this.onBatchProcess=n.eventListener.onBatchProcess)),this.target_cdn=i?.target_cdn||this.target_cdn,this.hostDomain=i?.hostDomain||this.hostDomain,this.customApiDomain=i?.customApiDomain||this.customApiDomain,this.__network_logs=!!i?.network_logs;let c=`https://${this.target_cdn}.cloudfront.net`,d=e.substring(0,4);this.admin_endpoint=fetch(`${c}/${d}/admin-${this.__endpoint_version}.json`).then(h=>h.blob()).then(h=>new Promise((b,w)=>{let _=new FileReader;_.onloadend=()=>b(_.result),_.onerror=w,_.readAsDataURL(h);})).then(h=>{try{return typeof h=="string"?JSON.parse(atob(h.split(",")[1])):null}catch{throw new f("Service does not exist. Create your service from skapi.com",{code:"NOT_EXISTS"})}}),this.record_endpoint=fetch(`${c}/${d}/record-${this.__endpoint_version}.json`).then(h=>h.blob()).then(h=>new Promise((b,w)=>{let _=new FileReader;_.onloadend=()=>b(_.result),_.onerror=w,_.readAsDataURL(h);})).then(h=>{try{return typeof h=="string"?JSON.parse(atob(h.split(",")[1])):null}catch{throw new f("Service does not exist. Create your service from skapi.com",{code:"NOT_EXISTS"})}});let l=z();if(l&&!window.sessionStorage)throw this._alert("This browser is not supported."),new Error("This browser is not supported.");let g=l?JSON.parse(window.sessionStorage.getItem(`${e}#${t}`)||"null"):null;if(this.log("constructor:restore",g),g?.connection){for(let h in g)this[h]=g[h];g.__public_identifier||(this.__public_identifier=`${this.service}:${this.owner}:${Qe(16)}`);}this.__authConnection=(async()=>{let h=await this.admin_endpoint,b={UserPoolId:h.userpool_id,ClientId:h.userpool_client};Ar()&&(b.Storage=window.localStorage),this.userPool=new br(b);try{this.user||await W.bind(this)().getSession({skipUserUpdateEventTrigger:!0}),this.user&&(!g?.connection&&!u?be.bind(this)():(this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user)));}catch{}})();let p=l?window.sessionStorage.getItem(`${this.service}:uniqueids`):null;if(p)try{this.__my_unique_ids=JSON.parse(p);}catch{this.__my_unique_ids={};}this.__connection=(async()=>{let h=null;await this.record_endpoint,g?.connection||(h=this._updateConnection());let b=()=>{if(this.__class_properties_has_been_cached)return;let w=()=>{let _={},R=["__startKeyHistory","__disabledAccount","__cached_requests","__request_signup_confirmation","__public_identifier","connection"];if(this.connection){for(let C of R)_[C]=this[C];l&&window.sessionStorage.setItem(`${e}#${t}`,JSON.stringify(_)),this.__class_properties_has_been_cached=true;}};return h instanceof Promise?h.then(()=>w()):w()};return l&&(window.addEventListener("beforeunload",()=>{this.closeRealtime(),b();}),window.addEventListener("visibilitychange",()=>{b();})),await h,await this.__authConnection,this.connection})(),this.__connection.then(h=>{((h?.group||0)<3||this.__network_logs)&&this.version();});}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){typeof e=="function"&&this._onLoginListeners.push(e);}get onUserUpdate(){return this._userProfileListeners}set onUserUpdate(e){typeof e=="function"&&this._userProfileListeners.push(e);}_runOnUserUpdateListeners(e){for(let t of this._userProfileListeners)typeof t=="function"&&t(e);}_runOnLoginListeners(e){for(let t of this._onLoginListeners)typeof t=="function"&&t(e);}get onBatchProcess(){return this._onBatchProcessListeners}set onBatchProcess(e){typeof e=="function"&&this._onBatchProcessListeners.push(e);}_alert(e){z()&&typeof window.alert=="function"&&window.alert(e);}async getConnectionInfo(e){e?.refresh&&(this.__connection instanceof Promise&&await this.__connection,this.__connection=this._updateConnection({refresh:true}));let n=await this.__connection,i=n?.user_agent||(z()&&typeof window.navigator?.userAgent=="string"?window.navigator.userAgent:`skapi-node/${globalThis?.process?.versions?.node||"unknown"}`);return {user_ip:n.ip,user_agent:i,user_location:n.locale,service_name:n.service_name,version:this.__version,service_description:n?.service_description||"",ai_agent:n?.ai_agent||""}}async _updateConnection(e){let t=e?.refresh||false;try{this.connection=await v.bind(this)("service",{service:this.service,owner:this.owner,refresh:t},{bypassAwaitConnection:!0,method:"get"});}catch(n){throw this.log("connection fail",n),this._alert("Service is not available: "+(n.message||n.toString())),this.connection=null,n}return this.connection}async version(){if(await this.__connection,z()){let t=`Built with:
218
+ Watch the video here: ${e.video}`}var E=class{constructor(e,t,n,i){this.__version="1.5.7-beta.1";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=false;this.__user=null;this._userProfileListeners=[];this._onLoginListeners=[];this._onBatchProcessListeners=[];this.validate={userId(e){try{return m.UserId(e),!0}catch{return false}},url(e){try{return m.Url(e),!0}catch{return false}},phoneNumber(e){try{return m.PhoneNumber(e),!0}catch{return false}},birthdate(e){try{return m.Birthdate(e),!0}catch{return false}},email(e){try{return m.Email(e),!0}catch{return false}},params(e,t,n){return m.Params(e,t,n)}};this.util={MD5:Q,generateRandom:Qe,toBase62:Wn,fromBase62:ne,decodeServiceId:Er,formatServiceId:Jn,extractFormData:L,terminatePendingRequests:Ai,request:(e,t,n)=>v.bind(this)(e,t,n,{ignoreService:true})};this.__network_logs=false;this.__endpoint_version="v1";this.__public_identifier="";this.bearerToken="";this.registerTicket=Xn.bind(this);this.unregisterTicket=Zn.bind(this);if(!e||typeof e!="string")throw this._alert("Service ID is required."),new f("Service ID is required.",{code:"INVALID_PARAMETER"});let s=e.split("-").length;if(s===2||s===7)try{let h=Er(e);n&&typeof n=="object"&&(i=n),t&&typeof t=="object"&&(n=t),t=h.owner,e=h.service;}catch{throw this._alert("Service ID is invalid."),new f("Service ID is invalid.",{code:"INVALID_PARAMETER"})}if(!t||typeof t!="string")throw this._alert("Owner ID is invalid."),new f("Owner ID is invalid.",{code:"INVALID_PARAMETER"});if(e.toLowerCase()==="service_id")throw this._alert('Replace "service_id" with your actual Service ID.'),new f("Service ID is required.",{code:"INVALID_PARAMETER"});if(t!==this.host)try{m.UserId(t,'"owner"');}catch{throw this._alert("Owner ID is invalid."),new f("Owner ID is invalid.",{code:"INVALID_PARAMETER"})}this.service=e,this.owner=t;let u=true;if(n&&(typeof n.autoLogin=="boolean"&&(u=n.autoLogin),typeof n.requestBatchSize=="number")){if(n.requestBatchSize<1)throw new f('"requestBatchSize" must be greater than 0.',{code:"INVALID_PARAMETER"});this.requestBatchSize=n.requestBatchSize;}n?.eventListener&&typeof n.eventListener=="object"&&(n.eventListener?.onLogin&&typeof n.eventListener.onLogin=="function"&&(this.onLogin=n.eventListener.onLogin),n.eventListener?.onUserUpdate&&typeof n.eventListener.onUserUpdate=="function"&&(this.onUserUpdate=n.eventListener.onUserUpdate),n.eventListener?.onBatchProcess&&typeof n.eventListener.onBatchProcess=="function"&&(this.onBatchProcess=n.eventListener.onBatchProcess)),this.target_cdn=i?.target_cdn||this.target_cdn,this.hostDomain=i?.hostDomain||this.hostDomain,this.customApiDomain=i?.customApiDomain||this.customApiDomain,this.__network_logs=!!i?.network_logs;let c=`https://${this.target_cdn}.cloudfront.net`,d=e.substring(0,4);this.admin_endpoint=fetch(`${c}/${d}/admin-${this.__endpoint_version}.json`).then(h=>h.blob()).then(h=>new Promise((b,w)=>{let _=new FileReader;_.onloadend=()=>b(_.result),_.onerror=w,_.readAsDataURL(h);})).then(h=>{try{return typeof h=="string"?JSON.parse(atob(h.split(",")[1])):null}catch{throw new f("Service does not exist. Create your service from skapi.com",{code:"NOT_EXISTS"})}}),this.record_endpoint=fetch(`${c}/${d}/record-${this.__endpoint_version}.json`).then(h=>h.blob()).then(h=>new Promise((b,w)=>{let _=new FileReader;_.onloadend=()=>b(_.result),_.onerror=w,_.readAsDataURL(h);})).then(h=>{try{return typeof h=="string"?JSON.parse(atob(h.split(",")[1])):null}catch{throw new f("Service does not exist. Create your service from skapi.com",{code:"NOT_EXISTS"})}});let l=z();if(l&&!window.sessionStorage)throw this._alert("This browser is not supported."),new Error("This browser is not supported.");let g=l?JSON.parse(window.sessionStorage.getItem(`${e}#${t}`)||"null"):null;if(this.log("constructor:restore",g),g?.connection){for(let h in g)this[h]=g[h];g.__public_identifier||(this.__public_identifier=`${this.service}:${this.owner}:${Qe(16)}`);}this.__authConnection=(async()=>{let h=await this.admin_endpoint,b={UserPoolId:h.userpool_id,ClientId:h.userpool_client};Ar()&&(b.Storage=window.localStorage),this.userPool=new br(b);try{this.user||await W.bind(this)().getSession({skipUserUpdateEventTrigger:!0}),this.user&&(!g?.connection&&!u?be.bind(this)():(this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user)));}catch{}})();let p=l?window.sessionStorage.getItem(`${this.service}:uniqueids`):null;if(p)try{this.__my_unique_ids=JSON.parse(p);}catch{this.__my_unique_ids={};}this.__connection=(async()=>{let h=null;await this.record_endpoint,g?.connection||(h=this._updateConnection());let b=()=>{if(this.__class_properties_has_been_cached)return;let w=()=>{let _={},R=["__startKeyHistory","__disabledAccount","__cached_requests","__request_signup_confirmation","__public_identifier","connection"];if(this.connection){for(let C of R)_[C]=this[C];l&&window.sessionStorage.setItem(`${e}#${t}`,JSON.stringify(_)),this.__class_properties_has_been_cached=true;}};return h instanceof Promise?h.then(()=>w()):w()};return l&&(window.addEventListener("beforeunload",()=>{this.closeRealtime(),b();}),window.addEventListener("visibilitychange",()=>{b();})),await h,await this.__authConnection,this.connection})(),this.__connection.then(h=>{((h?.group||0)<3||this.__network_logs)&&this.version();});}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){typeof e=="function"&&this._onLoginListeners.push(e);}get onUserUpdate(){return this._userProfileListeners}set onUserUpdate(e){typeof e=="function"&&this._userProfileListeners.push(e);}_runOnUserUpdateListeners(e){for(let t of this._userProfileListeners)typeof t=="function"&&t(e);}_runOnLoginListeners(e){for(let t of this._onLoginListeners)typeof t=="function"&&t(e);}get onBatchProcess(){return this._onBatchProcessListeners}set onBatchProcess(e){typeof e=="function"&&this._onBatchProcessListeners.push(e);}_alert(e){z()&&typeof window.alert=="function"&&window.alert(e);}async getConnectionInfo(e){e?.refresh&&(this.__connection instanceof Promise&&await this.__connection,this.__connection=this._updateConnection({refresh:true}));let n=await this.__connection,i=n?.user_agent||(z()&&typeof window.navigator?.userAgent=="string"?window.navigator.userAgent:`skapi-node/${globalThis?.process?.versions?.node||"unknown"}`);return {user_ip:n.ip,user_agent:i,user_location:n.locale,service_name:n.service_name,version:this.__version,service_description:n?.service_description||"",ai_agent:n?.ai_agent||""}}async _updateConnection(e){let t=e?.refresh||false;try{this.connection=await v.bind(this)("service",{service:this.service,owner:this.owner,refresh:t},{bypassAwaitConnection:!0,method:"get"});}catch(n){throw this.log("connection fail",n),this._alert("Service is not available: "+(n.message||n.toString())),this.connection=null,n}return this.connection}async version(){if(await this.__connection,z()){let t=`Built with:
219
219
  %c\r
220
220
  $$\\ $$\\ \r
221
221
  $$ | \\__|\r
@@ -230,7 +230,7 @@ $$$$$$$ |$$ | \\$$\\\\$$$$$$$ |$$$$$$$ |$$ |\r
230
230
  \\__| \r
231
231
  Version: ${this.__version}
232
232
 
233
- Full Documentation: https://docs.skapi.com/skapi.md`;console.log(t,"font-family: monospace; color:blue;"),this.connection.group===1&&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(t!==null&&typeof t=="object")try{z()?t=JSON.parse(JSON.stringify(t)):t=JSON.stringify(t,null,2);}catch{t=String(t);}else typeof t=="string"&&t.length>100&&(t=t.substring(0,100)+"...");console.log(`%c${e}:`,"color: blue;",t);}}getFeed(e,t){return ss.bind(this)(e,t)}closeRTC(e){return oe.bind(this)(e)}connectRTC(e,t){return Hi.bind(this)(e,t)}connectRealtime(e){return Vt.bind(this)(e)}spellcast(e){return Ps.bind(this)(e)}getspell(e){return xs.bind(this)(e)}dopamine(e){return Us.bind(this)(e)}getUniqueId(e,t){return Li.bind(this)(e,t)}resendInvitation(e){return Es.bind(this)(e)}cancelInvitation(e){return Ss.bind(this)(e)}getInvitations(e,t){return As.bind(this)(e,t)}openIdLogin(e){return ti.bind(this)(e)}loginWithToken(e){return ri.bind(this)(e)}clientSecretRequest(e){return es.bind(this)(e)}clientSecretRequestHistory(e,t){return ts.bind(this)(e,t)}consumeTicket(e){return Qn.bind(this)(e)}getConsumedTickets(e,t){return Yn.bind(this)(e,t)}getTickets(e,t){return zn.bind(this)(e,t)}closeRealtime(){return Qi.bind(this)()}getRealtimeUsers(e,t){return Yi.bind(this)(e,t)}sendInquiry(e){return rs.bind(this)(e)}blockAccount(e){return ps.bind(this)(e)}unblockAccount(e){return ms.bind(this)(e)}deleteAccount(e){return _s.bind(this)(e)}inviteUser(e,t){return bs.bind(this)(e,t)}createAccount(e){return ys.bind(this)(e)}grantAccess(e){return ws.bind(this)(e)}getRealtimeGroups(e,t){return Xi.bind(this)(e,t)}postRealtime(e,t,n){return zi.bind(this)(e,t,n)}joinRealtime(e){return Nr.bind(this)(e)}getProfile(e){return ei.bind(this)(e)}getFile(e,t){return Ft.bind(this)(e,t)}secureRequest(e,t){return ns.bind(this)(e,t)}getFormResponse(){return Ei.bind(this)()}getRecords(e,t){return xi.bind(this)(e,t)}getTables(e,t){return ki.bind(this)(e,t)}getIndexes(e,t){return Ni.bind(this)(e,t)}getTags(e,t){return Fi.bind(this)(e,t)}deleteRecords(e,t){return Oi.bind(this)(e,t)}resendSignupConfirmation(){return ni.bind(this)()}recoverAccount(e=false){return ii.bind(this)(e)}getUsers(e,t){return gi.bind(this)(e,t)}disableAccount(){return oi.bind(this)()}lastVerifiedEmail(e){return pi.bind(this)(e)}unsubscribeNewsletter(e){return hs.bind(this)(e)}subscribeNotification(e,t){return vs.bind(this)({endpoint:e,keys:t})}unsubscribeNotification(e,t){return Ts.bind(this)({endpoint:e,keys:t})}vapidPublicKey(){return Rs.bind(this)()}pushNotification(e,t){return Is.bind(this)(e,t)}getNewsletters(e,t){return gs.bind(this)(e,t)}getNewsletterSubscription(e,t){return ds.bind(this)(e,t)}requestUsernameChange(e){return mi.bind(this)(e)}grantPrivateRecordAccess(e){return Mi.bind(this)(e)}removePrivateRecordAccess(e){return Vi.bind(this)(e)}listPrivateRecordAccess(e){return qi.bind(this)(e)}requestPrivateRecordAccessKey(e){return Bi.bind(this)(e)}deleteFiles(e){return Ii.bind(this)(e)}uploadFiles(e,t){return Ct.bind(this)(e,t)}mock(e,t){return is.bind(this)(e,t)}login(e){return vr.bind(this)(e)}logout(e){return Xe.bind(this)(e)}signup(e,t){return si.bind(this)(e,t)}resetPassword(e){return ai.bind(this)(e)}verifyEmail(e){return li.bind(this)(e)}verifyPhoneNumber(e){return ci.bind(this)(e)}forgotPassword(e){return di.bind(this)(e)}changePassword(e){return fi.bind(this)(e)}updateProfile(e){return hi.bind(this)(e)}postRecord(e,t,n){return Di.bind(this)(e,t,n)}getSubscriptions(e,t){return os.bind(this)(e,t)}subscribe(e){return as.bind(this)(e)}unsubscribe(e){return us.bind(this)(e)}blockSubscriber(e){return cs.bind(this)(e)}unblockSubscriber(e){return ls.bind(this)(e)}subscribeNewsletter(e){return fs.bind(this)(e)}bulkPostRecords(e){return Ci.bind(this)(e)}};E([T()],S.prototype,"getFeed"),E([T()],S.prototype,"closeRTC"),E([T()],S.prototype,"connectRTC"),E([T()],S.prototype,"spellcast"),E([T()],S.prototype,"getspell"),E([T()],S.prototype,"dopamine"),E([T()],S.prototype,"getUniqueId"),E([T()],S.prototype,"resendInvitation"),E([T()],S.prototype,"cancelInvitation"),E([T()],S.prototype,"getInvitations"),E([T()],S.prototype,"openIdLogin"),E([T()],S.prototype,"loginWithToken"),E([T()],S.prototype,"clientSecretRequest"),E([T()],S.prototype,"clientSecretRequestHistory"),E([T()],S.prototype,"consumeTicket"),E([T()],S.prototype,"getConsumedTickets"),E([T()],S.prototype,"getTickets"),E([T()],S.prototype,"getRealtimeUsers"),E([T()],S.prototype,"sendInquiry"),E([T()],S.prototype,"blockAccount"),E([T()],S.prototype,"unblockAccount"),E([T()],S.prototype,"deleteAccount"),E([T()],S.prototype,"inviteUser"),E([T()],S.prototype,"createAccount"),E([T()],S.prototype,"grantAccess"),E([T()],S.prototype,"getRealtimeGroups"),E([T()],S.prototype,"postRealtime"),E([T()],S.prototype,"joinRealtime"),E([T()],S.prototype,"getProfile"),E([T()],S.prototype,"getFile"),E([T()],S.prototype,"secureRequest"),E([T()],S.prototype,"getFormResponse"),E([T()],S.prototype,"getRecords"),E([T()],S.prototype,"getTables"),E([T()],S.prototype,"getIndexes"),E([T()],S.prototype,"getTags"),E([T()],S.prototype,"deleteRecords"),E([T()],S.prototype,"resendSignupConfirmation"),E([T()],S.prototype,"recoverAccount"),E([T()],S.prototype,"getUsers"),E([T()],S.prototype,"disableAccount"),E([T()],S.prototype,"lastVerifiedEmail"),E([T()],S.prototype,"unsubscribeNewsletter"),E([T()],S.prototype,"subscribeNotification"),E([T()],S.prototype,"unsubscribeNotification"),E([T()],S.prototype,"vapidPublicKey"),E([T()],S.prototype,"pushNotification"),E([T()],S.prototype,"getNewsletters"),E([T()],S.prototype,"getNewsletterSubscription"),E([T()],S.prototype,"requestUsernameChange"),E([T()],S.prototype,"grantPrivateRecordAccess"),E([T()],S.prototype,"removePrivateRecordAccess"),E([T()],S.prototype,"listPrivateRecordAccess"),E([T()],S.prototype,"requestPrivateRecordAccessKey"),E([T()],S.prototype,"deleteFiles"),E([T()],S.prototype,"uploadFiles"),E([T()],S.prototype,"mock"),E([T({preventMultipleCalls:true})],S.prototype,"login"),E([T()],S.prototype,"logout"),E([T({preventMultipleCalls:true})],S.prototype,"signup"),E([T({preventMultipleCalls:true})],S.prototype,"resetPassword"),E([T({preventMultipleCalls:true})],S.prototype,"verifyEmail"),E([T({preventMultipleCalls:true})],S.prototype,"verifyPhoneNumber"),E([T({preventMultipleCalls:true})],S.prototype,"forgotPassword"),E([T({preventMultipleCalls:true})],S.prototype,"changePassword"),E([T({preventMultipleCalls:true})],S.prototype,"updateProfile"),E([T()],S.prototype,"postRecord"),E([T()],S.prototype,"getSubscriptions"),E([T()],S.prototype,"subscribe"),E([T()],S.prototype,"unsubscribe"),E([T()],S.prototype,"blockSubscriber"),E([T()],S.prototype,"unblockSubscriber"),E([T()],S.prototype,"subscribeNewsletter");var Fr={};var qt=typeof globalThis<"u"?globalThis:void 0;qt&&(qt.Skapi=S,qt.SkapiError=f,qt.SkapiTypes=Fr);/*! Bundled license information:
233
+ Full Documentation: https://docs.skapi.com/skapi.md`;console.log(t,"font-family: monospace; color:blue;"),this.connection.group===1&&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(t!==null&&typeof t=="object")try{z()?t=JSON.parse(JSON.stringify(t)):t=JSON.stringify(t,null,2);}catch{t=String(t);}else typeof t=="string"&&t.length>100&&(t=t.substring(0,100)+"...");console.log(`%c${e}:`,"color: blue;",t);}}getFeed(e,t){return ss.bind(this)(e,t)}closeRTC(e){return oe.bind(this)(e)}connectRTC(e,t){return Hi.bind(this)(e,t)}connectRealtime(e){return Vt.bind(this)(e)}spellcast(e){return Ps.bind(this)(e)}getspell(e){return xs.bind(this)(e)}dopamine(e){return Us.bind(this)(e)}getUniqueId(e,t){return Li.bind(this)(e,t)}resendInvitation(e){return Ss.bind(this)(e)}cancelInvitation(e){return Es.bind(this)(e)}getInvitations(e,t){return As.bind(this)(e,t)}openIdLogin(e){return ti.bind(this)(e)}loginWithToken(e){return ri.bind(this)(e)}clientSecretRequest(e){return es.bind(this)(e)}clientSecretRequestHistory(e,t){return ts.bind(this)(e,t)}consumeTicket(e){return Qn.bind(this)(e)}getConsumedTickets(e,t){return Yn.bind(this)(e,t)}getTickets(e,t){return zn.bind(this)(e,t)}closeRealtime(){return Qi.bind(this)()}getRealtimeUsers(e,t){return Yi.bind(this)(e,t)}sendInquiry(e){return rs.bind(this)(e)}blockAccount(e){return ps.bind(this)(e)}unblockAccount(e){return ms.bind(this)(e)}deleteAccount(e){return _s.bind(this)(e)}inviteUser(e,t){return bs.bind(this)(e,t)}createAccount(e){return ys.bind(this)(e)}grantAccess(e){return ws.bind(this)(e)}getRealtimeGroups(e,t){return Xi.bind(this)(e,t)}postRealtime(e,t,n){return zi.bind(this)(e,t,n)}joinRealtime(e){return Nr.bind(this)(e)}getProfile(e){return ei.bind(this)(e)}getFile(e,t){return Ft.bind(this)(e,t)}secureRequest(e,t){return ns.bind(this)(e,t)}getFormResponse(){return Si.bind(this)()}getRecords(e,t){return xi.bind(this)(e,t)}getTables(e,t){return ki.bind(this)(e,t)}getIndexes(e,t){return Ni.bind(this)(e,t)}getTags(e,t){return Fi.bind(this)(e,t)}deleteRecords(e,t){return Oi.bind(this)(e,t)}resendSignupConfirmation(){return ni.bind(this)()}recoverAccount(e=false){return ii.bind(this)(e)}getUsers(e,t){return gi.bind(this)(e,t)}disableAccount(){return oi.bind(this)()}lastVerifiedEmail(e){return pi.bind(this)(e)}unsubscribeNewsletter(e){return hs.bind(this)(e)}subscribeNotification(e,t){return vs.bind(this)({endpoint:e,keys:t})}unsubscribeNotification(e,t){return Ts.bind(this)({endpoint:e,keys:t})}vapidPublicKey(){return Rs.bind(this)()}pushNotification(e,t){return Is.bind(this)(e,t)}getNewsletters(e,t){return gs.bind(this)(e,t)}getNewsletterSubscription(e,t){return ds.bind(this)(e,t)}requestUsernameChange(e){return mi.bind(this)(e)}grantPrivateRecordAccess(e){return Mi.bind(this)(e)}removePrivateRecordAccess(e){return Vi.bind(this)(e)}listPrivateRecordAccess(e){return qi.bind(this)(e)}requestPrivateRecordAccessKey(e){return Bi.bind(this)(e)}deleteFiles(e){return Ii.bind(this)(e)}uploadFiles(e,t){return Ct.bind(this)(e,t)}mock(e,t){return is.bind(this)(e,t)}login(e){return vr.bind(this)(e)}logout(e){return Xe.bind(this)(e)}signup(e,t){return si.bind(this)(e,t)}resetPassword(e){return ai.bind(this)(e)}verifyEmail(e,t){return li.bind(this)(e,t)}verifyPhoneNumber(e,t){return ci.bind(this)(e,t)}forgotPassword(e,t){return di.bind(this)(e,t)}changePassword(e){return fi.bind(this)(e)}updateProfile(e){return hi.bind(this)(e)}postRecord(e,t,n){return Di.bind(this)(e,t,n)}getSubscriptions(e,t){return os.bind(this)(e,t)}subscribe(e){return as.bind(this)(e)}unsubscribe(e){return us.bind(this)(e)}blockSubscriber(e){return cs.bind(this)(e)}unblockSubscriber(e){return ls.bind(this)(e)}subscribeNewsletter(e){return fs.bind(this)(e)}bulkPostRecords(e){return Ci.bind(this)(e)}};S([T()],E.prototype,"getFeed"),S([T()],E.prototype,"closeRTC"),S([T()],E.prototype,"connectRTC"),S([T()],E.prototype,"spellcast"),S([T()],E.prototype,"getspell"),S([T()],E.prototype,"dopamine"),S([T()],E.prototype,"getUniqueId"),S([T()],E.prototype,"resendInvitation"),S([T()],E.prototype,"cancelInvitation"),S([T()],E.prototype,"getInvitations"),S([T()],E.prototype,"openIdLogin"),S([T()],E.prototype,"loginWithToken"),S([T()],E.prototype,"clientSecretRequest"),S([T()],E.prototype,"clientSecretRequestHistory"),S([T()],E.prototype,"consumeTicket"),S([T()],E.prototype,"getConsumedTickets"),S([T()],E.prototype,"getTickets"),S([T()],E.prototype,"getRealtimeUsers"),S([T()],E.prototype,"sendInquiry"),S([T()],E.prototype,"blockAccount"),S([T()],E.prototype,"unblockAccount"),S([T()],E.prototype,"deleteAccount"),S([T()],E.prototype,"inviteUser"),S([T()],E.prototype,"createAccount"),S([T()],E.prototype,"grantAccess"),S([T()],E.prototype,"getRealtimeGroups"),S([T()],E.prototype,"postRealtime"),S([T()],E.prototype,"joinRealtime"),S([T()],E.prototype,"getProfile"),S([T()],E.prototype,"getFile"),S([T()],E.prototype,"secureRequest"),S([T()],E.prototype,"getFormResponse"),S([T()],E.prototype,"getRecords"),S([T()],E.prototype,"getTables"),S([T()],E.prototype,"getIndexes"),S([T()],E.prototype,"getTags"),S([T()],E.prototype,"deleteRecords"),S([T()],E.prototype,"resendSignupConfirmation"),S([T()],E.prototype,"recoverAccount"),S([T()],E.prototype,"getUsers"),S([T()],E.prototype,"disableAccount"),S([T()],E.prototype,"lastVerifiedEmail"),S([T()],E.prototype,"unsubscribeNewsletter"),S([T()],E.prototype,"subscribeNotification"),S([T()],E.prototype,"unsubscribeNotification"),S([T()],E.prototype,"vapidPublicKey"),S([T()],E.prototype,"pushNotification"),S([T()],E.prototype,"getNewsletters"),S([T()],E.prototype,"getNewsletterSubscription"),S([T()],E.prototype,"requestUsernameChange"),S([T()],E.prototype,"grantPrivateRecordAccess"),S([T()],E.prototype,"removePrivateRecordAccess"),S([T()],E.prototype,"listPrivateRecordAccess"),S([T()],E.prototype,"requestPrivateRecordAccessKey"),S([T()],E.prototype,"deleteFiles"),S([T()],E.prototype,"uploadFiles"),S([T()],E.prototype,"mock"),S([T({preventMultipleCalls:true})],E.prototype,"login"),S([T()],E.prototype,"logout"),S([T({preventMultipleCalls:true})],E.prototype,"signup"),S([T({preventMultipleCalls:true})],E.prototype,"resetPassword"),S([T({preventMultipleCalls:true})],E.prototype,"verifyEmail"),S([T({preventMultipleCalls:true})],E.prototype,"verifyPhoneNumber"),S([T({preventMultipleCalls:true})],E.prototype,"forgotPassword"),S([T({preventMultipleCalls:true})],E.prototype,"changePassword"),S([T({preventMultipleCalls:true})],E.prototype,"updateProfile"),S([T()],E.prototype,"postRecord"),S([T()],E.prototype,"getSubscriptions"),S([T()],E.prototype,"subscribe"),S([T()],E.prototype,"unsubscribe"),S([T()],E.prototype,"blockSubscriber"),S([T()],E.prototype,"unblockSubscriber"),S([T()],E.prototype,"subscribeNewsletter");var Fr={};var qt=typeof globalThis<"u"?globalThis:void 0;qt&&(qt.Skapi=E,qt.SkapiError=f,qt.SkapiTypes=Fr);/*! Bundled license information:
234
234
 
235
235
  ieee754/index.js:
236
236
  (*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> *)
@@ -286,5 +286,5 @@ amazon-cognito-identity-js/es/index.js:
286
286
  * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
287
287
  * SPDX-License-Identifier: Apache-2.0
288
288
  *)
289
- */export{S as Skapi,f as SkapiError,Fr as Types};//# sourceMappingURL=skapi.browser.mjs.map
289
+ */export{E as Skapi,f as SkapiError,Fr as Types};//# sourceMappingURL=skapi.browser.mjs.map
290
290
  //# sourceMappingURL=skapi.browser.mjs.map