skapi-js 2.2.11 → 2.2.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/skapi.browser.mjs +11 -11
- package/dist/skapi.browser.mjs.map +1 -1
- package/dist/skapi.cjs +10 -10
- package/dist/skapi.cjs.map +1 -1
- package/dist/skapi.d.mts +87 -16
- package/dist/skapi.d.ts +87 -16
- package/dist/skapi.js +11 -11
- package/dist/skapi.js.map +1 -1
- package/dist/skapi.mjs +10 -10
- package/dist/skapi.mjs.map +1 -1
- package/package.json +1 -1
package/dist/skapi.browser.mjs
CHANGED
|
@@ -203,8 +203,8 @@
|
|
|
203
203
|
limitations under the License.
|
|
204
204
|
|
|
205
205
|
*/
|
|
206
|
-
var wc=Object.create;var et=Object.defineProperty;var ji=Object.getOwnPropertyDescriptor;var Ec=Object.getOwnPropertyNames;var Ac=Object.getPrototypeOf,Rc=Object.prototype.hasOwnProperty;var Sc=(t,e,r)=>e in t?et(t,e,{enumerable:true,configurable:true,writable:true,value:r}):t[e]=r;var Be=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var tt=(t,e)=>()=>(t&&(e=t(t=0)),e);var se=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),nr=(t,e)=>{for(var r in e)et(t,r,{get:e[r],enumerable:true});},Ki=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Ec(e))!Rc.call(t,i)&&i!==r&&et(t,i,{get:()=>e[i],enumerable:!(n=ji(e,i))||n.enumerable});return t};var rt=(t,e,r)=>(r=t!=null?wc(Ac(t)):{},Ki(!t||!t.__esModule?et(r,"default",{value:t,enumerable:true}):r,t)),nt=t=>Ki(et({},"__esModule",{value:true}),t),P=(t,e,r,n)=>{for(var i=ji(e,r),s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(o(e,r,i))||i);return i&&et(e,r,i),i};var Te=(t,e,r)=>Sc(t,typeof e!="symbol"?e+"":e,r);var Gi=se(sr=>{sr.byteLength=Ic;sr.toByteArray=kc;sr.fromByteArray=Cc;var ve=[],fe=[],vc=typeof Uint8Array<"u"?Uint8Array:Array,an="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(We=0,$i=an.length;We<$i;++We)ve[We]=an[We],fe[an.charCodeAt(We)]=We;var We,$i;fe[45]=62;fe[95]=63;function Hi(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");r===-1&&(r=e);var n=r===e?0:4-r%4;return [r,n]}function Ic(t){var e=Hi(t),r=e[0],n=e[1];return (r+n)*3/4-n}function Pc(t,e,r){return (e+r)*3/4-r}function kc(t){var e,r=Hi(t),n=r[0],i=r[1],s=new vc(Pc(t,n,i)),o=0,a=i>0?n-4:n,l;for(l=0;l<a;l+=4)e=fe[t.charCodeAt(l)]<<18|fe[t.charCodeAt(l+1)]<<12|fe[t.charCodeAt(l+2)]<<6|fe[t.charCodeAt(l+3)],s[o++]=e>>16&255,s[o++]=e>>8&255,s[o++]=e&255;return i===2&&(e=fe[t.charCodeAt(l)]<<2|fe[t.charCodeAt(l+1)]>>4,s[o++]=e&255),i===1&&(e=fe[t.charCodeAt(l)]<<10|fe[t.charCodeAt(l+1)]<<4|fe[t.charCodeAt(l+2)]>>2,s[o++]=e>>8&255,s[o++]=e&255),s}function xc(t){return ve[t>>18&63]+ve[t>>12&63]+ve[t>>6&63]+ve[t&63]}function Uc(t,e,r){for(var n,i=[],s=e;s<r;s+=3)n=(t[s]<<16&16711680)+(t[s+1]<<8&65280)+(t[s+2]&255),i.push(xc(n));return i.join("")}function Cc(t){for(var e,r=t.length,n=r%3,i=[],s=16383,o=0,a=r-n;o<a;o+=s)i.push(Uc(t,o,o+s>a?a:o+s));return n===1?(e=t[r-1],i.push(ve[e>>2]+ve[e<<4&63]+"==")):n===2&&(e=(t[r-2]<<8)+t[r-1],i.push(ve[e>>10]+ve[e>>4&63]+ve[e<<2&63]+"=")),i.join("")}});var Wi=se(ln=>{ln.read=function(t,e,r,n,i){var s,o,a=i*8-n-1,l=(1<<a)-1,c=l>>1,d=-7,h=r?i-1:0,u=r?-1:1,g=t[e+h];for(h+=u,s=g&(1<<-d)-1,g>>=-d,d+=a;d>0;s=s*256+t[e+h],h+=u,d-=8);for(o=s&(1<<-d)-1,s>>=-d,d+=n;d>0;o=o*256+t[e+h],h+=u,d-=8);if(s===0)s=1-c;else {if(s===l)return o?NaN:(g?-1:1)*(1/0);o=o+Math.pow(2,n),s=s-c;}return (g?-1:1)*o*Math.pow(2,s-n)};ln.write=function(t,e,r,n,i,s){var o,a,l,c=s*8-i-1,d=(1<<c)-1,h=d>>1,u=i===23?Math.pow(2,-24)-Math.pow(2,-77):0,g=n?0:s-1,p=n?1:-1,m=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*(l=Math.pow(2,-o))<1&&(o--,l*=2),o+h>=1?e+=u/l:e+=u*Math.pow(2,1-h),e*l>=2&&(o++,l/=2),o+h>=d?(a=0,o=d):o+h>=1?(a=(e*l-1)*Math.pow(2,i),o=o+h):(a=e*Math.pow(2,h-1)*Math.pow(2,i),o=0));i>=8;t[r+g]=a&255,g+=p,a/=256,i-=8);for(o=o<<i|a,c+=i;c>0;t[r+g]=o&255,g+=p,o/=256,c-=8);t[r+g-p]|=m*128;};});var Ji=se((Gh,zi)=>{var Dc={}.toString;zi.exports=Array.isArray||function(t){return Dc.call(t)=="[object Array]"};});var dr=se(ot=>{var cn=Gi(),st=Wi(),Xi=Ji();ot.Buffer=E;ot.SlowBuffer=qc;ot.INSPECT_MAX_BYTES=50;E.TYPED_ARRAY_SUPPORT=globalThis.TYPED_ARRAY_SUPPORT!==void 0?globalThis.TYPED_ARRAY_SUPPORT:Nc();ot.kMaxLength=or();function Nc(){try{var t=new Uint8Array(1);return t.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},t.foo()===42&&typeof t.subarray=="function"&&t.subarray(1,1).byteLength===0}catch{return false}}function or(){return E.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function Ne(t,e){if(or()<e)throw new RangeError("Invalid typed array length");return E.TYPED_ARRAY_SUPPORT?(t=new Uint8Array(e),t.__proto__=E.prototype):(t===null&&(t=new E(e)),t.length=e),t}function E(t,e,r){if(!E.TYPED_ARRAY_SUPPORT&&!(this instanceof E))return new E(t,e,r);if(typeof t=="number"){if(typeof e=="string")throw new Error("If encoding is specified then the first argument must be a string");return dn(this,t)}return Zi(this,t,e,r)}E.poolSize=8192;E._augment=function(t){return t.__proto__=E.prototype,t};function Zi(t,e,r,n){if(typeof e=="number")throw new TypeError('"value" argument must not be a number');return typeof ArrayBuffer<"u"&&e instanceof ArrayBuffer?Lc(t,e,r,n):typeof e=="string"?Fc(t,e,r):Mc(t,e)}E.from=function(t,e,r){return Zi(null,t,e,r)};E.TYPED_ARRAY_SUPPORT&&(E.prototype.__proto__=Uint8Array.prototype,E.__proto__=Uint8Array,typeof Symbol<"u"&&Symbol.species&&E[Symbol.species]===E&&Object.defineProperty(E,Symbol.species,{value:null,configurable:true}));function es(t){if(typeof t!="number")throw new TypeError('"size" argument must be a number');if(t<0)throw new RangeError('"size" argument must not be negative')}function Oc(t,e,r,n){return es(e),e<=0?Ne(t,e):r!==void 0?typeof n=="string"?Ne(t,e).fill(r,n):Ne(t,e).fill(r):Ne(t,e)}E.alloc=function(t,e,r){return Oc(null,t,e,r)};function dn(t,e){if(es(e),t=Ne(t,e<0?0:fn(e)|0),!E.TYPED_ARRAY_SUPPORT)for(var r=0;r<e;++r)t[r]=0;return t}E.allocUnsafe=function(t){return dn(null,t)};E.allocUnsafeSlow=function(t){return dn(null,t)};function Fc(t,e,r){if((typeof r!="string"||r==="")&&(r="utf8"),!E.isEncoding(r))throw new TypeError('"encoding" must be a valid string encoding');var n=ts(e,r)|0;t=Ne(t,n);var i=t.write(e,r);return i!==n&&(t=t.slice(0,i)),t}function un(t,e){var r=e.length<0?0:fn(e.length)|0;t=Ne(t,r);for(var n=0;n<r;n+=1)t[n]=e[n]&255;return t}function Lc(t,e,r,n){if(e.byteLength,r<0||e.byteLength<r)throw new RangeError("'offset' is out of bounds");if(e.byteLength<r+(n||0))throw new RangeError("'length' is out of bounds");return r===void 0&&n===void 0?e=new Uint8Array(e):n===void 0?e=new Uint8Array(e,r):e=new Uint8Array(e,r,n),E.TYPED_ARRAY_SUPPORT?(t=e,t.__proto__=E.prototype):t=un(t,e),t}function Mc(t,e){if(E.isBuffer(e)){var r=fn(e.length)|0;return t=Ne(t,r),t.length===0||e.copy(t,0,0,r),t}if(e){if(typeof ArrayBuffer<"u"&&e.buffer instanceof ArrayBuffer||"length"in e)return typeof e.length!="number"||iu(e.length)?Ne(t,0):un(t,e);if(e.type==="Buffer"&&Xi(e.data))return un(t,e.data)}throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")}function fn(t){if(t>=or())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+or().toString(16)+" bytes");return t|0}function qc(t){return +t!=t&&(t=0),E.alloc(+t)}E.isBuffer=function(e){return !!(e!=null&&e._isBuffer)};E.compare=function(e,r){if(!E.isBuffer(e)||!E.isBuffer(r))throw new TypeError("Arguments must be Buffers");if(e===r)return 0;for(var n=e.length,i=r.length,s=0,o=Math.min(n,i);s<o;++s)if(e[s]!==r[s]){n=e[s],i=r[s];break}return n<i?-1:i<n?1:0};E.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}};E.concat=function(e,r){if(!Xi(e))throw new TypeError('"list" argument must be an Array of Buffers');if(e.length===0)return E.alloc(0);var n;if(r===void 0)for(r=0,n=0;n<e.length;++n)r+=e[n].length;var i=E.allocUnsafe(r),s=0;for(n=0;n<e.length;++n){var o=e[n];if(!E.isBuffer(o))throw new TypeError('"list" argument must be an Array of Buffers');o.copy(i,s),s+=o.length;}return i};function ts(t,e){if(E.isBuffer(t))return t.length;if(typeof ArrayBuffer<"u"&&typeof ArrayBuffer.isView=="function"&&(ArrayBuffer.isView(t)||t instanceof ArrayBuffer))return t.byteLength;typeof t!="string"&&(t=""+t);var r=t.length;if(r===0)return 0;for(var n=false;;)switch(e){case "ascii":case "latin1":case "binary":return r;case "utf8":case "utf-8":case void 0:return ar(t).length;case "ucs2":case "ucs-2":case "utf16le":case "utf-16le":return r*2;case "hex":return r>>>1;case "base64":return ls(t).length;default:if(n)return ar(t).length;e=(""+e).toLowerCase(),n=true;}}E.byteLength=ts;function Vc(t,e,r){var n=false;if((e===void 0||e<0)&&(e=0),e>this.length||((r===void 0||r>this.length)&&(r=this.length),r<=0)||(r>>>=0,e>>>=0,r<=e))return "";for(t||(t="utf8");;)switch(t){case "hex":return Yc(this,e,r);case "utf8":case "utf-8":return is(this,e,r);case "ascii":return zc(this,e,r);case "latin1":case "binary":return Jc(this,e,r);case "base64":return Gc(this,e,r);case "ucs2":case "ucs-2":case "utf16le":case "utf-16le":return Qc(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=true;}}E.prototype._isBuffer=true;function ze(t,e,r){var n=t[e];t[e]=t[r],t[r]=n;}E.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 r=0;r<e;r+=2)ze(this,r,r+1);return this};E.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 r=0;r<e;r+=4)ze(this,r,r+3),ze(this,r+1,r+2);return this};E.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 r=0;r<e;r+=8)ze(this,r,r+7),ze(this,r+1,r+6),ze(this,r+2,r+5),ze(this,r+3,r+4);return this};E.prototype.toString=function(){var e=this.length|0;return e===0?"":arguments.length===0?is(this,0,e):Vc.apply(this,arguments)};E.prototype.equals=function(e){if(!E.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e?true:E.compare(this,e)===0};E.prototype.inspect=function(){var e="",r=ot.INSPECT_MAX_BYTES;return this.length>0&&(e=this.toString("hex",0,r).match(/.{2}/g).join(" "),this.length>r&&(e+=" ... ")),"<Buffer "+e+">"};E.prototype.compare=function(e,r,n,i,s){if(!E.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(r===void 0&&(r=0),n===void 0&&(n=e?e.length:0),i===void 0&&(i=0),s===void 0&&(s=this.length),r<0||n>e.length||i<0||s>this.length)throw new RangeError("out of range index");if(i>=s&&r>=n)return 0;if(i>=s)return -1;if(r>=n)return 1;if(r>>>=0,n>>>=0,i>>>=0,s>>>=0,this===e)return 0;for(var o=s-i,a=n-r,l=Math.min(o,a),c=this.slice(i,s),d=e.slice(r,n),h=0;h<l;++h)if(c[h]!==d[h]){o=c[h],a=d[h];break}return o<a?-1:a<o?1:0};function rs(t,e,r,n,i){if(t.length===0)return -1;if(typeof r=="string"?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,isNaN(r)&&(r=i?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(i)return -1;r=t.length-1;}else if(r<0)if(i)r=0;else return -1;if(typeof e=="string"&&(e=E.from(e,n)),E.isBuffer(e))return e.length===0?-1:Yi(t,e,r,n,i);if(typeof e=="number")return e=e&255,E.TYPED_ARRAY_SUPPORT&&typeof Uint8Array.prototype.indexOf=="function"?i?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):Yi(t,[e],r,n,i);throw new TypeError("val must be string, number or Buffer")}function Yi(t,e,r,n,i){var s=1,o=t.length,a=e.length;if(n!==void 0&&(n=String(n).toLowerCase(),n==="ucs2"||n==="ucs-2"||n==="utf16le"||n==="utf-16le")){if(t.length<2||e.length<2)return -1;s=2,o/=2,a/=2,r/=2;}function l(g,p){return s===1?g[p]:g.readUInt16BE(p*s)}var c;if(i){var d=-1;for(c=r;c<o;c++)if(l(t,c)===l(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(r+a>o&&(r=o-a),c=r;c>=0;c--){for(var h=true,u=0;u<a;u++)if(l(t,c+u)!==l(e,u)){h=false;break}if(h)return c}return -1}E.prototype.includes=function(e,r,n){return this.indexOf(e,r,n)!==-1};E.prototype.indexOf=function(e,r,n){return rs(this,e,r,n,true)};E.prototype.lastIndexOf=function(e,r,n){return rs(this,e,r,n,false)};function Bc(t,e,r,n){r=Number(r)||0;var i=t.length-r;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;t[r+o]=a;}return o}function jc(t,e,r,n){return ur(ar(e,t.length-r),t,r,n)}function ns(t,e,r,n){return ur(ru(e),t,r,n)}function Kc(t,e,r,n){return ns(t,e,r,n)}function $c(t,e,r,n){return ur(ls(e),t,r,n)}function Hc(t,e,r,n){return ur(nu(e,t.length-r),t,r,n)}E.prototype.write=function(e,r,n,i){if(r===void 0)i="utf8",n=this.length,r=0;else if(n===void 0&&typeof r=="string")i=r,n=this.length,r=0;else if(isFinite(r))r=r|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-r;if((n===void 0||n>s)&&(n=s),e.length>0&&(n<0||r<0)||r>this.length)throw new RangeError("Attempt to write outside buffer bounds");i||(i="utf8");for(var o=false;;)switch(i){case "hex":return Bc(this,e,r,n);case "utf8":case "utf-8":return jc(this,e,r,n);case "ascii":return ns(this,e,r,n);case "latin1":case "binary":return Kc(this,e,r,n);case "base64":return $c(this,e,r,n);case "ucs2":case "ucs-2":case "utf16le":case "utf-16le":return Hc(this,e,r,n);default:if(o)throw new TypeError("Unknown encoding: "+i);i=(""+i).toLowerCase(),o=true;}};E.prototype.toJSON=function(){return {type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function Gc(t,e,r){return e===0&&r===t.length?cn.fromByteArray(t):cn.fromByteArray(t.slice(e,r))}function is(t,e,r){r=Math.min(t.length,r);for(var n=[],i=e;i<r;){var s=t[i],o=null,a=s>239?4:s>223?3:s>191?2:1;if(i+a<=r){var l,c,d,h;switch(a){case 1:s<128&&(o=s);break;case 2:l=t[i+1],(l&192)===128&&(h=(s&31)<<6|l&63,h>127&&(o=h));break;case 3:l=t[i+1],c=t[i+2],(l&192)===128&&(c&192)===128&&(h=(s&15)<<12|(l&63)<<6|c&63,h>2047&&(h<55296||h>57343)&&(o=h));break;case 4:l=t[i+1],c=t[i+2],d=t[i+3],(l&192)===128&&(c&192)===128&&(d&192)===128&&(h=(s&15)<<18|(l&63)<<12|(c&63)<<6|d&63,h>65535&&h<1114112&&(o=h));}}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 Wc(n)}var Qi=4096;function Wc(t){var e=t.length;if(e<=Qi)return String.fromCharCode.apply(String,t);for(var r="",n=0;n<e;)r+=String.fromCharCode.apply(String,t.slice(n,n+=Qi));return r}function zc(t,e,r){var n="";r=Math.min(t.length,r);for(var i=e;i<r;++i)n+=String.fromCharCode(t[i]&127);return n}function Jc(t,e,r){var n="";r=Math.min(t.length,r);for(var i=e;i<r;++i)n+=String.fromCharCode(t[i]);return n}function Yc(t,e,r){var n=t.length;(!e||e<0)&&(e=0),(!r||r<0||r>n)&&(r=n);for(var i="",s=e;s<r;++s)i+=tu(t[s]);return i}function Qc(t,e,r){for(var n=t.slice(e,r),i="",s=0;s<n.length;s+=2)i+=String.fromCharCode(n[s]+n[s+1]*256);return i}E.prototype.slice=function(e,r){var n=this.length;e=~~e,r=r===void 0?n:~~r,e<0?(e+=n,e<0&&(e=0)):e>n&&(e=n),r<0?(r+=n,r<0&&(r=0)):r>n&&(r=n),r<e&&(r=e);var i;if(E.TYPED_ARRAY_SUPPORT)i=this.subarray(e,r),i.__proto__=E.prototype;else {var s=r-e;i=new E(s,void 0);for(var o=0;o<s;++o)i[o]=this[o+e];}return i};function z(t,e,r){if(t%1!==0||t<0)throw new RangeError("offset is not uint");if(t+e>r)throw new RangeError("Trying to access beyond buffer length")}E.prototype.readUIntLE=function(e,r,n){e=e|0,r=r|0,n||z(e,r,this.length);for(var i=this[e],s=1,o=0;++o<r&&(s*=256);)i+=this[e+o]*s;return i};E.prototype.readUIntBE=function(e,r,n){e=e|0,r=r|0,n||z(e,r,this.length);for(var i=this[e+--r],s=1;r>0&&(s*=256);)i+=this[e+--r]*s;return i};E.prototype.readUInt8=function(e,r){return r||z(e,1,this.length),this[e]};E.prototype.readUInt16LE=function(e,r){return r||z(e,2,this.length),this[e]|this[e+1]<<8};E.prototype.readUInt16BE=function(e,r){return r||z(e,2,this.length),this[e]<<8|this[e+1]};E.prototype.readUInt32LE=function(e,r){return r||z(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+this[e+3]*16777216};E.prototype.readUInt32BE=function(e,r){return r||z(e,4,this.length),this[e]*16777216+(this[e+1]<<16|this[e+2]<<8|this[e+3])};E.prototype.readIntLE=function(e,r,n){e=e|0,r=r|0,n||z(e,r,this.length);for(var i=this[e],s=1,o=0;++o<r&&(s*=256);)i+=this[e+o]*s;return s*=128,i>=s&&(i-=Math.pow(2,8*r)),i};E.prototype.readIntBE=function(e,r,n){e=e|0,r=r|0,n||z(e,r,this.length);for(var i=r,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*r)),o};E.prototype.readInt8=function(e,r){return r||z(e,1,this.length),this[e]&128?(255-this[e]+1)*-1:this[e]};E.prototype.readInt16LE=function(e,r){r||z(e,2,this.length);var n=this[e]|this[e+1]<<8;return n&32768?n|4294901760:n};E.prototype.readInt16BE=function(e,r){r||z(e,2,this.length);var n=this[e+1]|this[e]<<8;return n&32768?n|4294901760:n};E.prototype.readInt32LE=function(e,r){return r||z(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24};E.prototype.readInt32BE=function(e,r){return r||z(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]};E.prototype.readFloatLE=function(e,r){return r||z(e,4,this.length),st.read(this,e,true,23,4)};E.prototype.readFloatBE=function(e,r){return r||z(e,4,this.length),st.read(this,e,false,23,4)};E.prototype.readDoubleLE=function(e,r){return r||z(e,8,this.length),st.read(this,e,true,52,8)};E.prototype.readDoubleBE=function(e,r){return r||z(e,8,this.length),st.read(this,e,false,52,8)};function oe(t,e,r,n,i,s){if(!E.isBuffer(t))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(r+n>t.length)throw new RangeError("Index out of range")}E.prototype.writeUIntLE=function(e,r,n,i){if(e=+e,r=r|0,n=n|0,!i){var s=Math.pow(2,8*n)-1;oe(this,e,r,n,s,0);}var o=1,a=0;for(this[r]=e&255;++a<n&&(o*=256);)this[r+a]=e/o&255;return r+n};E.prototype.writeUIntBE=function(e,r,n,i){if(e=+e,r=r|0,n=n|0,!i){var s=Math.pow(2,8*n)-1;oe(this,e,r,n,s,0);}var o=n-1,a=1;for(this[r+o]=e&255;--o>=0&&(a*=256);)this[r+o]=e/a&255;return r+n};E.prototype.writeUInt8=function(e,r,n){return e=+e,r=r|0,n||oe(this,e,r,1,255,0),E.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[r]=e&255,r+1};function lr(t,e,r,n){e<0&&(e=65535+e+1);for(var i=0,s=Math.min(t.length-r,2);i<s;++i)t[r+i]=(e&255<<8*(n?i:1-i))>>>(n?i:1-i)*8;}E.prototype.writeUInt16LE=function(e,r,n){return e=+e,r=r|0,n||oe(this,e,r,2,65535,0),E.TYPED_ARRAY_SUPPORT?(this[r]=e&255,this[r+1]=e>>>8):lr(this,e,r,true),r+2};E.prototype.writeUInt16BE=function(e,r,n){return e=+e,r=r|0,n||oe(this,e,r,2,65535,0),E.TYPED_ARRAY_SUPPORT?(this[r]=e>>>8,this[r+1]=e&255):lr(this,e,r,false),r+2};function cr(t,e,r,n){e<0&&(e=4294967295+e+1);for(var i=0,s=Math.min(t.length-r,4);i<s;++i)t[r+i]=e>>>(n?i:3-i)*8&255;}E.prototype.writeUInt32LE=function(e,r,n){return e=+e,r=r|0,n||oe(this,e,r,4,4294967295,0),E.TYPED_ARRAY_SUPPORT?(this[r+3]=e>>>24,this[r+2]=e>>>16,this[r+1]=e>>>8,this[r]=e&255):cr(this,e,r,true),r+4};E.prototype.writeUInt32BE=function(e,r,n){return e=+e,r=r|0,n||oe(this,e,r,4,4294967295,0),E.TYPED_ARRAY_SUPPORT?(this[r]=e>>>24,this[r+1]=e>>>16,this[r+2]=e>>>8,this[r+3]=e&255):cr(this,e,r,false),r+4};E.prototype.writeIntLE=function(e,r,n,i){if(e=+e,r=r|0,!i){var s=Math.pow(2,8*n-1);oe(this,e,r,n,s-1,-s);}var o=0,a=1,l=0;for(this[r]=e&255;++o<n&&(a*=256);)e<0&&l===0&&this[r+o-1]!==0&&(l=1),this[r+o]=(e/a>>0)-l&255;return r+n};E.prototype.writeIntBE=function(e,r,n,i){if(e=+e,r=r|0,!i){var s=Math.pow(2,8*n-1);oe(this,e,r,n,s-1,-s);}var o=n-1,a=1,l=0;for(this[r+o]=e&255;--o>=0&&(a*=256);)e<0&&l===0&&this[r+o+1]!==0&&(l=1),this[r+o]=(e/a>>0)-l&255;return r+n};E.prototype.writeInt8=function(e,r,n){return e=+e,r=r|0,n||oe(this,e,r,1,127,-128),E.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[r]=e&255,r+1};E.prototype.writeInt16LE=function(e,r,n){return e=+e,r=r|0,n||oe(this,e,r,2,32767,-32768),E.TYPED_ARRAY_SUPPORT?(this[r]=e&255,this[r+1]=e>>>8):lr(this,e,r,true),r+2};E.prototype.writeInt16BE=function(e,r,n){return e=+e,r=r|0,n||oe(this,e,r,2,32767,-32768),E.TYPED_ARRAY_SUPPORT?(this[r]=e>>>8,this[r+1]=e&255):lr(this,e,r,false),r+2};E.prototype.writeInt32LE=function(e,r,n){return e=+e,r=r|0,n||oe(this,e,r,4,2147483647,-2147483648),E.TYPED_ARRAY_SUPPORT?(this[r]=e&255,this[r+1]=e>>>8,this[r+2]=e>>>16,this[r+3]=e>>>24):cr(this,e,r,true),r+4};E.prototype.writeInt32BE=function(e,r,n){return e=+e,r=r|0,n||oe(this,e,r,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),E.TYPED_ARRAY_SUPPORT?(this[r]=e>>>24,this[r+1]=e>>>16,this[r+2]=e>>>8,this[r+3]=e&255):cr(this,e,r,false),r+4};function ss(t,e,r,n,i,s){if(r+n>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function os(t,e,r,n,i){return i||ss(t,e,r,4),st.write(t,e,r,n,23,4),r+4}E.prototype.writeFloatLE=function(e,r,n){return os(this,e,r,true,n)};E.prototype.writeFloatBE=function(e,r,n){return os(this,e,r,false,n)};function as(t,e,r,n,i){return i||ss(t,e,r,8),st.write(t,e,r,n,52,8),r+8}E.prototype.writeDoubleLE=function(e,r,n){return as(this,e,r,true,n)};E.prototype.writeDoubleBE=function(e,r,n){return as(this,e,r,false,n)};E.prototype.copy=function(e,r,n,i){if(n||(n=0),!i&&i!==0&&(i=this.length),r>=e.length&&(r=e.length),r||(r=0),i>0&&i<n&&(i=n),i===n||e.length===0||this.length===0)return 0;if(r<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-r<i-n&&(i=e.length-r+n);var s=i-n,o;if(this===e&&n<r&&r<i)for(o=s-1;o>=0;--o)e[o+r]=this[o+n];else if(s<1e3||!E.TYPED_ARRAY_SUPPORT)for(o=0;o<s;++o)e[o+r]=this[o+n];else Uint8Array.prototype.set.call(e,this.subarray(n,n+s),r);return s};E.prototype.fill=function(e,r,n,i){if(typeof e=="string"){if(typeof r=="string"?(i=r,r=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"&&!E.isEncoding(i))throw new TypeError("Unknown encoding: "+i)}else typeof e=="number"&&(e=e&255);if(r<0||this.length<r||this.length<n)throw new RangeError("Out of range index");if(n<=r)return this;r=r>>>0,n=n===void 0?this.length:n>>>0,e||(e=0);var o;if(typeof e=="number")for(o=r;o<n;++o)this[o]=e;else {var a=E.isBuffer(e)?e:ar(new E(e,i).toString()),l=a.length;for(o=0;o<n-r;++o)this[o+r]=a[o%l];}return this};var Xc=/[^+\/0-9A-Za-z-_]/g;function Zc(t){if(t=eu(t).replace(Xc,""),t.length<2)return "";for(;t.length%4!==0;)t=t+"=";return t}function eu(t){return t.trim?t.trim():t.replace(/^\s+|\s+$/g,"")}function tu(t){return t<16?"0"+t.toString(16):t.toString(16)}function ar(t,e){e=e||1/0;for(var r,n=t.length,i=null,s=[],o=0;o<n;++o){if(r=t.charCodeAt(o),r>55295&&r<57344){if(!i){if(r>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=r;continue}if(r<56320){(e-=3)>-1&&s.push(239,191,189),i=r;continue}r=(i-55296<<10|r-56320)+65536;}else i&&(e-=3)>-1&&s.push(239,191,189);if(i=null,r<128){if((e-=1)<0)break;s.push(r);}else if(r<2048){if((e-=2)<0)break;s.push(r>>6|192,r&63|128);}else if(r<65536){if((e-=3)<0)break;s.push(r>>12|224,r>>6&63|128,r&63|128);}else if(r<1114112){if((e-=4)<0)break;s.push(r>>18|240,r>>12&63|128,r>>6&63|128,r&63|128);}else throw new Error("Invalid code point")}return s}function ru(t){for(var e=[],r=0;r<t.length;++r)e.push(t.charCodeAt(r)&255);return e}function nu(t,e){for(var r,n,i,s=[],o=0;o<t.length&&!((e-=2)<0);++o)r=t.charCodeAt(o),n=r>>8,i=r%256,s.push(i),s.push(n);return s}function ls(t){return cn.toByteArray(Zc(t))}function ur(t,e,r,n){for(var i=0;i<n&&!(i+r>=e.length||i>=t.length);++i)e[i+r]=t[i];return i}function iu(t){return t!==t}});var cs={};nr(cs,{default:()=>ou});var su,ou,us=tt(()=>{su={},ou=su;});var bn={};nr(bn,{__assign:()=>mn,__asyncDelegator:()=>wu,__asyncGenerator:()=>_u,__asyncValues:()=>Eu,__await:()=>kt,__awaiter:()=>hu,__classPrivateFieldGet:()=>Tu,__classPrivateFieldSet:()=>vu,__createBinding:()=>gu,__decorate:()=>uu,__exportStar:()=>mu,__extends:()=>lu,__generator:()=>pu,__importDefault:()=>Su,__importStar:()=>Ru,__makeTemplateObject:()=>Au,__metadata:()=>fu,__param:()=>du,__read:()=>ds,__rest:()=>cu,__spread:()=>yu,__spreadArrays:()=>bu,__values:()=>yn});function lu(t,e){gn(t,e);function r(){this.constructor=t;}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r);}function cu(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(t,n[i])&&(r[n[i]]=t[n[i]]);return r}function uu(t,e,r,n){var i=arguments.length,s=i<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,r):n,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(t,e,r,n);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(s=(i<3?o(s):i>3?o(e,r,s):o(e,r))||s);return i>3&&s&&Object.defineProperty(e,r,s),s}function du(t,e){return function(r,n){e(r,n,t);}}function fu(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function hu(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s);})}return new(r||(r=Promise))(function(s,o){function a(d){try{c(n.next(d));}catch(h){o(h);}}function l(d){try{c(n.throw(d));}catch(h){o(h);}}function c(d){d.done?s(d.value):i(d.value).then(a,l);}c((n=n.apply(t,e||[])).next());})}function pu(t,e){var r={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 l([c,d])}}function l(c){if(n)throw new TypeError("Generator is already executing.");for(;r;)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 r.label++,{value:c[1],done:!1};case 5:r.label++,i=c[1],c=[0];continue;case 7:c=r.ops.pop(),r.trys.pop();continue;default:if(s=r.trys,!(s=s.length>0&&s[s.length-1])&&(c[0]===6||c[0]===2)){r=0;continue}if(c[0]===3&&(!s||c[1]>s[0]&&c[1]<s[3])){r.label=c[1];break}if(c[0]===6&&r.label<s[1]){r.label=s[1],s=c;break}if(s&&r.label<s[2]){r.label=s[2],r.ops.push(c);break}s[2]&&r.ops.pop(),r.trys.pop();continue}c=e.call(t,r);}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 gu(t,e,r,n){n===void 0&&(n=r),t[n]=e[r];}function mu(t,e){for(var r in t)r!=="default"&&!e.hasOwnProperty(r)&&(e[r]=t[r]);}function yn(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return {next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function ds(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),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&&(r=n.return)&&r.call(n);}finally{if(o)throw o.error}}return s}function yu(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(ds(arguments[e]));return t}function bu(){for(var t=0,e=0,r=arguments.length;e<r;e++)t+=arguments[e].length;for(var n=Array(t),i=0,e=0;e<r;e++)for(var s=arguments[e],o=0,a=s.length;o<a;o++,i++)n[i]=s[o];return n}function kt(t){return this instanceof kt?(this.v=t,this):new kt(t)}function _u(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=r.apply(t,e||[]),i,s=[];return i={},o("next"),o("throw"),o("return"),i[Symbol.asyncIterator]=function(){return this},i;function o(u){n[u]&&(i[u]=function(g){return new Promise(function(p,m){s.push([u,g,p,m])>1||a(u,g);})});}function a(u,g){try{l(n[u](g));}catch(p){h(s[0][3],p);}}function l(u){u.value instanceof kt?Promise.resolve(u.value.v).then(c,d):h(s[0][2],u);}function c(u){a("next",u);}function d(u){a("throw",u);}function h(u,g){u(g),s.shift(),s.length&&a(s[0][0],s[0][1]);}}function wu(t){var e,r;return e={},n("next"),n("throw",function(i){throw i}),n("return"),e[Symbol.iterator]=function(){return this},e;function n(i,s){e[i]=t[i]?function(o){return (r=!r)?{value:kt(t[i](o)),done:i==="return"}:s?s(o):o}:s;}}function Eu(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof yn=="function"?yn(t):t[Symbol.iterator](),r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r);function n(s){r[s]=t[s]&&function(o){return new Promise(function(a,l){o=t[s](o),i(a,l,o.done,o.value);})};}function i(s,o,a,l){Promise.resolve(l).then(function(c){s({value:c,done:a});},o);}}function Au(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function Ru(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)Object.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function Su(t){return t&&t.__esModule?t:{default:t}}function Tu(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function vu(t,e,r){if(!e.has(t))throw new TypeError("attempted to set private field on non-instance");return e.set(t,r),r}var gn,mn,_n=tt(()=>{gn=function(t,e){return gn=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n;}||function(r,n){for(var i in n)n.hasOwnProperty(i)&&(r[i]=n[i]);},gn(t,e)};mn=function(){return mn=Object.assign||function(e){for(var r,n=1,i=arguments.length;n<i;n++){r=arguments[n];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(e[s]=r[s]);}return e},mn.apply(this,arguments)};});var wn=se(pe=>{Object.defineProperty(pe,"__esModule",{value:true});pe.MAX_HASHABLE_LENGTH=pe.INIT=pe.KEY=pe.DIGEST_LENGTH=pe.BLOCK_SIZE=void 0;pe.BLOCK_SIZE=64;pe.DIGEST_LENGTH=32;pe.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]);pe.INIT=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225];pe.MAX_HASHABLE_LENGTH=Math.pow(2,53)-1;});var fs=se(fr=>{Object.defineProperty(fr,"__esModule",{value:true});fr.RawSha256=void 0;var ge=wn(),Iu=(function(){function t(){this.state=Int32Array.from(ge.INIT),this.temp=new Int32Array(64),this.buffer=new Uint8Array(64),this.bufferLength=0,this.bytesHashed=0,this.finished=false;}return t.prototype.update=function(e){if(this.finished)throw new Error("Attempted to update an already finished hash.");var r=0,n=e.byteLength;if(this.bytesHashed+=n,this.bytesHashed*8>ge.MAX_HASHABLE_LENGTH)throw new Error("Cannot hash more than 2^53 - 1 bits");for(;n>0;)this.buffer[this.bufferLength++]=e[r++],n--,this.bufferLength===ge.BLOCK_SIZE&&(this.hashBuffer(),this.bufferLength=0);},t.prototype.digest=function(){if(!this.finished){var e=this.bytesHashed*8,r=new DataView(this.buffer.buffer,this.buffer.byteOffset,this.buffer.byteLength),n=this.bufferLength;if(r.setUint8(this.bufferLength++,128),n%ge.BLOCK_SIZE>=ge.BLOCK_SIZE-8){for(var i=this.bufferLength;i<ge.BLOCK_SIZE;i++)r.setUint8(i,0);this.hashBuffer(),this.bufferLength=0;}for(var i=this.bufferLength;i<ge.BLOCK_SIZE-8;i++)r.setUint8(i,0);r.setUint32(ge.BLOCK_SIZE-8,Math.floor(e/4294967296),true),r.setUint32(ge.BLOCK_SIZE-4,e),this.hashBuffer(),this.finished=true;}for(var s=new Uint8Array(ge.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},t.prototype.hashBuffer=function(){for(var e=this,r=e.buffer,n=e.state,i=n[0],s=n[1],o=n[2],a=n[3],l=n[4],c=n[5],d=n[6],h=n[7],u=0;u<ge.BLOCK_SIZE;u++){if(u<16)this.temp[u]=(r[u*4]&255)<<24|(r[u*4+1]&255)<<16|(r[u*4+2]&255)<<8|r[u*4+3]&255;else {var g=this.temp[u-2],p=(g>>>17|g<<15)^(g>>>19|g<<13)^g>>>10;g=this.temp[u-15];var m=(g>>>7|g<<25)^(g>>>18|g<<14)^g>>>3;this.temp[u]=(p+this.temp[u-7]|0)+(m+this.temp[u-16]|0);}var b=(((l>>>6|l<<26)^(l>>>11|l<<21)^(l>>>25|l<<7))+(l&c^~l&d)|0)+(h+(ge.KEY[u]+this.temp[u]|0)|0)|0,y=((i>>>2|i<<30)^(i>>>13|i<<19)^(i>>>22|i<<10))+(i&s^i&o^s&o)|0;h=d,d=c,c=l,l=a+b|0,a=o,o=s,s=i,i=b+y|0;}n[0]+=i,n[1]+=s,n[2]+=o,n[3]+=a,n[4]+=l,n[5]+=c,n[6]+=d,n[7]+=h;},t})();fr.RawSha256=Iu;});var hs,ps,gs=tt(()=>{hs=t=>{let e=[];for(let r=0,n=t.length;r<n;r++){let i=t.charCodeAt(r);if(i<128)e.push(i);else if(i<2048)e.push(i>>6|192,i&63|128);else if(r+1<t.length&&(i&64512)===55296&&(t.charCodeAt(r+1)&64512)===56320){let s=65536+((i&1023)<<10)+(t.charCodeAt(++r)&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)},ps=t=>{let e="";for(let r=0,n=t.length;r<n;r++){let i=t[r];if(i<128)e+=String.fromCharCode(i);else if(192<=i&&i<224){let s=t[++r];e+=String.fromCharCode((i&31)<<6|s&63);}else if(240<=i&&i<365){let o="%"+[i,t[++r],t[++r],t[++r]].map(a=>a.toString(16)).join("%");e+=decodeURIComponent(o);}else e+=String.fromCharCode((i&15)<<12|(t[++r]&63)<<6|t[++r]&63);}return e};});function ms(t){return new TextEncoder().encode(t)}function ys(t){return new TextDecoder("utf-8").decode(t)}var bs=tt(()=>{});var _s={};nr(_s,{fromUtf8:()=>Pu,toUtf8:()=>ku});var Pu,ku,ws=tt(()=>{gs();bs();Pu=t=>typeof TextEncoder=="function"?ms(t):hs(t),ku=t=>typeof TextDecoder=="function"?ys(t):ps(t);});var Es=se(hr=>{Object.defineProperty(hr,"__esModule",{value:true});hr.convertToBuffer=void 0;var xu=(ws(),nt(_s)),Uu=typeof Buffer<"u"&&Buffer.from?function(t){return Buffer.from(t,"utf8")}:xu.fromUtf8;function Cu(t){return t instanceof Uint8Array?t:typeof t=="string"?Uu(t):ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(t)}hr.convertToBuffer=Cu;});var As=se(pr=>{Object.defineProperty(pr,"__esModule",{value:true});pr.isEmptyData=void 0;function Du(t){return typeof t=="string"?t.length===0:t.byteLength===0}pr.isEmptyData=Du;});var Rs=se(gr=>{Object.defineProperty(gr,"__esModule",{value:true});gr.numToUint8=void 0;function Nu(t){return new Uint8Array([(t&4278190080)>>24,(t&16711680)>>16,(t&65280)>>8,t&255])}gr.numToUint8=Nu;});var Ss=se(mr=>{Object.defineProperty(mr,"__esModule",{value:true});mr.uint32ArrayFrom=void 0;function Ou(t){if(!Array.from){for(var e=new Uint32Array(t.length),r=0;r<t.length;)e[r]=t[r];return e}return Uint32Array.from(t)}mr.uint32ArrayFrom=Ou;});var Ts=se(Ie=>{Object.defineProperty(Ie,"__esModule",{value:true});Ie.uint32ArrayFrom=Ie.numToUint8=Ie.isEmptyData=Ie.convertToBuffer=void 0;var Fu=Es();Object.defineProperty(Ie,"convertToBuffer",{enumerable:true,get:function(){return Fu.convertToBuffer}});var Lu=As();Object.defineProperty(Ie,"isEmptyData",{enumerable:true,get:function(){return Lu.isEmptyData}});var Mu=Rs();Object.defineProperty(Ie,"numToUint8",{enumerable:true,get:function(){return Mu.numToUint8}});var qu=Ss();Object.defineProperty(Ie,"uint32ArrayFrom",{enumerable:true,get:function(){return qu.uint32ArrayFrom}});});var Is=se(br=>{Object.defineProperty(br,"__esModule",{value:true});br.Sha256=void 0;var vs=(_n(),nt(bn)),yr=wn(),En=fs(),An=Ts(),Vu=(function(){function t(e){if(this.hash=new En.RawSha256,e){this.outer=new En.RawSha256;var r=Bu(e),n=new Uint8Array(yr.BLOCK_SIZE);n.set(r);for(var i=0;i<yr.BLOCK_SIZE;i++)r[i]^=54,n[i]^=92;this.hash.update(r),this.outer.update(n);for(var i=0;i<r.byteLength;i++)r[i]=0;}}return t.prototype.update=function(e){if(!((0, An.isEmptyData)(e)||this.error))try{this.hash.update((0,An.convertToBuffer)(e));}catch(r){this.error=r;}},t.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()},t.prototype.digest=function(){return (0, vs.__awaiter)(this,void 0,void 0,function(){return (0, vs.__generator)(this,function(e){return [2,this.digestSync()]})})},t})();br.Sha256=Vu;function Bu(t){var e=(0, An.convertToBuffer)(t);if(e.byteLength>yr.BLOCK_SIZE){var r=new En.RawSha256;r.update(e),e=r.digest();}var n=new Uint8Array(yr.BLOCK_SIZE);return n.set(e),n}});var Sn=se(Rn=>{Object.defineProperty(Rn,"__esModule",{value:true});var ju=(_n(),nt(bn));(0, ju.__exportStar)(Is(),Rn);});var Dn={};nr(Dn,{default:()=>Fd});function Fd(t,e){return e=e||{},new Promise(function(r,n){var i=new XMLHttpRequest,s=[],o=[],a={},l=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:l,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",t,true),i.onload=function(){i.getAllResponseHeaders().replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm,function(d,h,u){s.push(h=h.toLowerCase()),o.push([h,u]),a[h]=a[h]?a[h]+","+u:u;}),r(l());},i.onerror=n,i.withCredentials=e.credentials=="include",e.headers)i.setRequestHeader(c,e.headers[c]);i.send(e.body||null);})}var Nn=tt(()=>{});var Fs=se((qp,Os)=>{Os.exports=self.fetch||(self.fetch=(Nn(),nt(Dn)).default||(Nn(),nt(Dn)));});function it(t){let r=(typeof globalThis<"u"?globalThis:void 0)?.process;if(r&&typeof r.getBuiltinModule=="function")try{return r.getBuiltinModule(t)}catch{}try{if(typeof Be=="function")return Be(t)}catch{}return null}var tn,rn,nn=()=>tn!==void 0?tn:tn=it("fs"),sn=()=>rn!==void 0?rn:rn=it("path"),De=typeof globalThis<"u"?globalThis:void 0,ir=De?.window;function Tc(t){if(Buffer)return Buffer.from(t).toString("base64");let e="",r=new Uint8Array(t),n=32768;for(let i=0;i<r.length;i+=n){let s=r.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(ir)ir.global=ir,ir.global._runningInNodeJS=false;else if(De&&(De.global=De,typeof De.window>"u")){class t{constructor(){this.result=null;this.error=null;this.onload=null;this.onloadend=null;this.onerror=null;}readAsDataURL(n){n.arrayBuffer().then(i=>{let s=Tc(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});});}}De.FileReader=t;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);});}}De.XMLHttpRequest=e,De.window={_runningInNodeJS:true,alert:r=>console.error("[Alert]",r),sessionStorage:(()=>{let r=new Map;return {getItem:n=>r.has(n)?r.get(n):null,setItem:(n,i)=>{r.set(n,String(i));},removeItem:n=>{r.delete(n);}}})(),localStorage:{getItem:r=>{let n=nn(),i=sn();if(!n||!i)return null;try{let s=i.resolve(process.cwd(),"states","localStorage",`${r}.skapi`);return n.existsSync(s)?n.readFileSync(s,"utf8"):null}catch{return null}},setItem:(r,n)=>{let i=nn(),s=sn();if(!(!i||!s))try{let o=s.resolve(process.cwd(),"states","localStorage");i.existsSync(o)||i.mkdirSync(o,{recursive:!0});let a=s.resolve(o,`${r}.skapi`);i.writeFileSync(a,n,"utf8");}catch{}},removeItem:r=>{let n=nn(),i=sn();if(!(!n||!i))try{let s=i.resolve(process.cwd(),"states","localStorage",`${r}.skapi`);n.existsSync(s)&&n.unlinkSync(s);}catch{}}},location:{href:"",origin:"",hostname:"",protocol:"",replace:r=>{}},navigator:{userAgent:`nodejs/${De?.process?.versions?.node||"unknown"}`,mediaDevices:{getUserMedia:async r=>{throw new Error("getUserMedia is not supported in Node.js environment.")}}},addEventListener:()=>{},removeEventListener:()=>{}};}var on=(function(){function t(r){var n=r||{},i=n.ValidationData,s=n.Username,o=n.Password,a=n.AuthParameters,l=n.ClientMetadata;this.validationData=i||{},this.authParameters=a||{},this.clientMetadata=l||{},this.username=s,this.password=o;}var e=t.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},t})();var Oe=rt(dr());var he;typeof window<"u"&&window.crypto&&(he=window.crypto);!he&&typeof window<"u"&&window.msCrypto&&(he=window.msCrypto);!he&&typeof globalThis<"u"&&globalThis.crypto&&(he=globalThis.crypto);if(!he&&typeof Be=="function")try{he=(us(),nt(cs));}catch{}function hn(){if(he){if(typeof he.getRandomValues=="function")try{return he.getRandomValues(new Uint32Array(1))[0]}catch{}if(typeof he.randomBytes=="function")try{return he.randomBytes(4).readInt32LE()}catch{}}throw new Error("Native crypto module could not be used to get secure random number.")}function au(t){for(var e=t.words,r=t.sigBytes,n=[],i=0;i<r;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 pn=(function(){function t(r,n){r=this.words=r||[],n!=null?this.sigBytes=n:this.sigBytes=r.length*4;}var e=t.prototype;return e.random=function(n){for(var i=[],s=0;s<n;s+=4)i.push(hn());return new t(i,n)},e.toString=function(){return au(this)},t})();var wr=rt(Sn());var G=L;function L(t,e){t!=null&&this.fromString(t,e);}function ne(){return new L(null)}var je,Ku=0xdeadbeefcafe,Ps=(Ku&16777215)==15715070;function $u(t,e,r,n,i,s){for(;--s>=0;){var o=e*this[t++]+r[n]+i;i=Math.floor(o/67108864),r[n++]=o&67108863;}return i}function Hu(t,e,r,n,i,s){for(var o=e&32767,a=e>>15;--s>=0;){var l=this[t]&32767,c=this[t++]>>15,d=a*l+c*o;l=o*l+((d&32767)<<15)+r[n]+(i&1073741823),i=(l>>>30)+(d>>>15)+a*c+(i>>>30),r[n++]=l&1073741823;}return i}function Gu(t,e,r,n,i,s){for(var o=e&16383,a=e>>14;--s>=0;){var l=this[t]&16383,c=this[t++]>>14,d=a*l+c*o;l=o*l+((d&16383)<<14)+r[n]+i,i=(l>>28)+(d>>14)+a*c,r[n++]=l&268435455;}return i}var ks=typeof navigator<"u";ks&&Ps&&navigator.appName=="Microsoft Internet Explorer"?(L.prototype.am=Hu,je=30):ks&&Ps&&navigator.appName!="Netscape"?(L.prototype.am=$u,je=26):(L.prototype.am=Gu,je=28);L.prototype.DB=je;L.prototype.DM=(1<<je)-1;L.prototype.DV=1<<je;var Tn=52;L.prototype.FV=Math.pow(2,Tn);L.prototype.F1=Tn-je;L.prototype.F2=2*je-Tn;var Wu="0123456789abcdefghijklmnopqrstuvwxyz",_r=new Array,at,me;at=48;for(me=0;me<=9;++me)_r[at++]=me;at=97;for(me=10;me<36;++me)_r[at++]=me;at=65;for(me=10;me<36;++me)_r[at++]=me;function xs(t){return Wu.charAt(t)}function zu(t,e){var r=_r[t.charCodeAt(e)];return r??-1}function Ju(t){for(var e=this.t-1;e>=0;--e)t[e]=this[e];t.t=this.t,t.s=this.s;}function Yu(t){this.t=1,this.s=t<0?-1:0,t>0?this[0]=t:t<-1?this[0]=t+this.DV:this.t=0;}function vn(t){var e=ne();return e.fromInt(t),e}function Qu(t,e){var r;if(e==16)r=4;else if(e==8)r=3;else if(e==2)r=1;else if(e==32)r=5;else if(e==4)r=2;else throw new Error("Only radix 2, 4, 8, 16, 32 are supported");this.t=0,this.s=0;for(var n=t.length,i=false,s=0;--n>=0;){var o=zu(t,n);if(o<0){t.charAt(n)=="-"&&(i=true);continue}i=false,s==0?this[this.t++]=o:s+r>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+=r,s>=this.DB&&(s-=this.DB);}this.clamp(),i&&L.ZERO.subTo(this,this);}function Xu(){for(var t=this.s&this.DM;this.t>0&&this[this.t-1]==t;)--this.t;}function Zu(t){if(this.s<0)return "-"+this.negate().toString(t);var e;if(t==16)e=4;else if(t==8)e=3;else if(t==2)e=1;else if(t==32)e=5;else if(t==4)e=2;else throw new Error("Only radix 2, 4, 8, 16, 32 are supported");var r=(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=xs(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)&r,a<=0&&(a+=this.DB,--o)),n>0&&(i=true),i&&(s+=xs(n));return i?s:"0"}function ed(){var t=ne();return L.ZERO.subTo(this,t),t}function td(){return this.s<0?this.negate():this}function rd(t){var e=this.s-t.s;if(e!=0)return e;var r=this.t;if(e=r-t.t,e!=0)return this.s<0?-e:e;for(;--r>=0;)if((e=this[r]-t[r])!=0)return e;return 0}function In(t){var e=1,r;return (r=t>>>16)!=0&&(t=r,e+=16),(r=t>>8)!=0&&(t=r,e+=8),(r=t>>4)!=0&&(t=r,e+=4),(r=t>>2)!=0&&(t=r,e+=2),(r=t>>1)!=0&&(t=r,e+=1),e}function nd(){return this.t<=0?0:this.DB*(this.t-1)+In(this[this.t-1]^this.s&this.DM)}function id(t,e){var r;for(r=this.t-1;r>=0;--r)e[r+t]=this[r];for(r=t-1;r>=0;--r)e[r]=0;e.t=this.t+t,e.s=this.s;}function sd(t,e){for(var r=t;r<this.t;++r)e[r-t]=this[r];e.t=Math.max(this.t-t,0),e.s=this.s;}function od(t,e){var r=t%this.DB,n=this.DB-r,i=(1<<n)-1,s=Math.floor(t/this.DB),o=this.s<<r&this.DM,a;for(a=this.t-1;a>=0;--a)e[a+s+1]=this[a]>>n|o,o=(this[a]&i)<<r;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 ad(t,e){e.s=this.s;var r=Math.floor(t/this.DB);if(r>=this.t){e.t=0;return}var n=t%this.DB,i=this.DB-n,s=(1<<n)-1;e[0]=this[r]>>n;for(var o=r+1;o<this.t;++o)e[o-r-1]|=(this[o]&s)<<i,e[o-r]=this[o]>>n;n>0&&(e[this.t-r-1]|=(this.s&s)<<i),e.t=this.t-r,e.clamp();}function ld(t,e){for(var r=0,n=0,i=Math.min(t.t,this.t);r<i;)n+=this[r]-t[r],e[r++]=n&this.DM,n>>=this.DB;if(t.t<this.t){for(n-=t.s;r<this.t;)n+=this[r],e[r++]=n&this.DM,n>>=this.DB;n+=this.s;}else {for(n+=this.s;r<t.t;)n-=t[r],e[r++]=n&this.DM,n>>=this.DB;n-=t.s;}e.s=n<0?-1:0,n<-1?e[r++]=this.DV+n:n>0&&(e[r++]=n),e.t=r,e.clamp();}function cd(t,e){var r=this.abs(),n=t.abs(),i=r.t;for(e.t=i+n.t;--i>=0;)e[i]=0;for(i=0;i<n.t;++i)e[i+r.t]=r.am(0,n[i],e,i,0,r.t);e.s=0,e.clamp(),this.s!=t.s&&L.ZERO.subTo(e,e);}function ud(t){for(var e=this.abs(),r=t.t=2*e.t;--r>=0;)t[r]=0;for(r=0;r<e.t-1;++r){var n=e.am(r,e[r],t,2*r,0,1);(t[r+e.t]+=e.am(r+1,2*e[r],t,2*r+1,n,e.t-r-1))>=e.DV&&(t[r+e.t]-=e.DV,t[r+e.t+1]=1);}t.t>0&&(t[t.t-1]+=e.am(r,e[r],t,2*r,0,1)),t.s=0,t.clamp();}function dd(t,e,r){var n=t.abs();if(!(n.t<=0)){var i=this.abs();if(i.t<n.t){e?.fromInt(0),r!=null&&this.copyTo(r);return}r==null&&(r=ne());var s=ne(),o=this.s,a=t.s,l=this.DB-In(n[n.t-1]);l>0?(n.lShiftTo(l,s),i.lShiftTo(l,r)):(n.copyTo(s),i.copyTo(r));var c=s.t,d=s[c-1];if(d!=0){var h=d*(1<<this.F1)+(c>1?s[c-2]>>this.F2:0),u=this.FV/h,g=(1<<this.F1)/h,p=1<<this.F2,m=r.t,b=m-c,y=e??ne();for(s.dlShiftTo(b,y),r.compareTo(y)>=0&&(r[r.t++]=1,r.subTo(y,r)),L.ONE.dlShiftTo(c,y),y.subTo(s,s);s.t<c;)s[s.t++]=0;for(;--b>=0;){var A=r[--m]==d?this.DM:Math.floor(r[m]*u+(r[m-1]+p)*g);if((r[m]+=s.am(0,A,r,b,0,c))<A)for(s.dlShiftTo(b,y),r.subTo(y,r);r[m]<--A;)r.subTo(y,r);}e!=null&&(r.drShiftTo(c,e),o!=a&&L.ZERO.subTo(e,e)),r.t=c,r.clamp(),l>0&&r.rShiftTo(l,r),o<0&&L.ZERO.subTo(r,r);}}}function fd(t){var e=ne();return this.abs().divRemTo(t,null,e),this.s<0&&e.compareTo(L.ZERO)>0&&t.subTo(e,e),e}function hd(){if(this.t<1)return 0;var t=this[0];if((t&1)==0)return 0;var e=t&3;return e=e*(2-(t&15)*e)&15,e=e*(2-(t&255)*e)&255,e=e*(2-((t&65535)*e&65535))&65535,e=e*(2-t*e%this.DV)%this.DV,e>0?this.DV-e:-e}function pd(t){return this.compareTo(t)==0}function gd(t,e){for(var r=0,n=0,i=Math.min(t.t,this.t);r<i;)n+=this[r]+t[r],e[r++]=n&this.DM,n>>=this.DB;if(t.t<this.t){for(n+=t.s;r<this.t;)n+=this[r],e[r++]=n&this.DM,n>>=this.DB;n+=this.s;}else {for(n+=this.s;r<t.t;)n+=t[r],e[r++]=n&this.DM,n>>=this.DB;n+=t.s;}e.s=n<0?-1:0,n>0?e[r++]=n:n<-1&&(e[r++]=this.DV+n),e.t=r,e.clamp();}function md(t){var e=ne();return this.addTo(t,e),e}function yd(t){var e=ne();return this.subTo(t,e),e}function bd(t){var e=ne();return this.multiplyTo(t,e),e}function _d(t){var e=ne();return this.divRemTo(t,e,null),e}function lt(t){this.m=t,this.mp=t.invDigit(),this.mpl=this.mp&32767,this.mph=this.mp>>15,this.um=(1<<t.DB-15)-1,this.mt2=2*t.t;}function wd(t){var e=ne();return t.abs().dlShiftTo(this.m.t,e),e.divRemTo(this.m,null,e),t.s<0&&e.compareTo(L.ZERO)>0&&this.m.subTo(e,e),e}function Ed(t){var e=ne();return t.copyTo(e),this.reduce(e),e}function Ad(t){for(;t.t<=this.mt2;)t[t.t++]=0;for(var e=0;e<this.m.t;++e){var r=t[e]&32767,n=r*this.mpl+((r*this.mph+(t[e]>>15)*this.mpl&this.um)<<15)&t.DM;for(r=e+this.m.t,t[r]+=this.m.am(0,n,t,e,0,this.m.t);t[r]>=t.DV;)t[r]-=t.DV,t[++r]++;}t.clamp(),t.drShiftTo(this.m.t,t),t.compareTo(this.m)>=0&&t.subTo(this.m,t);}function Rd(t,e){t.squareTo(e),this.reduce(e);}function Sd(t,e,r){t.multiplyTo(e,r),this.reduce(r);}lt.prototype.convert=wd;lt.prototype.revert=Ed;lt.prototype.reduce=Ad;lt.prototype.mulTo=Sd;lt.prototype.sqrTo=Rd;function Td(t,e,r){var n=t.bitLength(),i,s=vn(1),o=new lt(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,l=3,c=i-1,d=(1<<i)-1;if(a[1]=o.convert(this),i>1){var h=ne();for(o.sqrTo(a[1],h);l<=d;)a[l]=ne(),o.mulTo(h,a[l-2],a[l]),l+=2;}var u=t.t-1,g,p=true,m=ne(),b;for(n=In(t[u])-1;u>=0;){for(n>=c?g=t[u]>>n-c&d:(g=(t[u]&(1<<n+1)-1)<<c-n,u>0&&(g|=t[u-1]>>this.DB+n-c)),l=i;(g&1)==0;)g>>=1,--l;if((n-=l)<0&&(n+=this.DB,--u),p)a[g].copyTo(s),p=false;else {for(;l>1;)o.sqrTo(s,m),o.sqrTo(m,s),l-=2;l>0?o.sqrTo(s,m):(b=s,s=m,m=b),o.mulTo(m,a[g],s);}for(;u>=0&&(t[u]&1<<n)==0;)o.sqrTo(s,m),b=s,s=m,m=b,--n<0&&(n=this.DB-1,--u);}var y=o.revert(s);return r(null,y),y}L.prototype.copyTo=Ju;L.prototype.fromInt=Yu;L.prototype.fromString=Qu;L.prototype.clamp=Xu;L.prototype.dlShiftTo=id;L.prototype.drShiftTo=sd;L.prototype.lShiftTo=od;L.prototype.rShiftTo=ad;L.prototype.subTo=ld;L.prototype.multiplyTo=cd;L.prototype.squareTo=ud;L.prototype.divRemTo=dd;L.prototype.invDigit=hd;L.prototype.addTo=gd;L.prototype.toString=Zu;L.prototype.negate=ed;L.prototype.abs=td;L.prototype.compareTo=rd;L.prototype.bitLength=nd;L.prototype.mod=fd;L.prototype.equals=pd;L.prototype.add=md;L.prototype.subtract=yd;L.prototype.multiply=bd;L.prototype.divide=_d;L.prototype.modPow=Td;L.ZERO=vn(0);L.ONE=vn(1);function Pn(t){return Oe.Buffer.from(new pn().random(t).toString(),"hex")}var vd=/^[89a-f]/i,Id="FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200CBBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF",Pd="userAttributes.",Ke=(function(){function t(r){this.N=new G(Id,16),this.g=new G("2",16),this.k=new G(this.hexHash(""+this.padHex(this.N)+this.padHex(this.g)),16),this.smallAValue=this.generateRandomSmallA(),this.getLargeAValue(function(){}),this.infoBits=Oe.Buffer.from("Caldera Derived Key","utf8"),this.poolName=r;}var e=t.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=Pn(128).toString("hex"),i=new G(n,16);return i},e.generateRandomString=function(){return Pn(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,l=this.hash(a),c=Pn(16).toString("hex");this.SaltToHashDevices=this.padHex(new G(c,16)),this.g.modPow(new G(this.hexHash(this.SaltToHashDevices+l),16),this.N,function(d,h){d&&s(d,null),o.verifierDevices=o.padHex(h),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(G.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 G(this.UHexHash,16);return s},e.hash=function(n){var i=new wr.Sha256;i.update(n);var s=i.digestSync(),o=Oe.Buffer.from(s).toString("hex");return new Array(64-o.length).join("0")+o},e.hexHash=function(n){return this.hash(Oe.Buffer.from(n,"hex"))},e.computehkdf=function(n,i){var s=Oe.Buffer.concat([this.infoBits,Oe.Buffer.from("","utf8")]),o=new wr.Sha256(i);o.update(n);var a=o.digestSync(),l=new wr.Sha256(a);l.update(s);var c=l.digestSync(),d=c,h=d.slice(0,16);return h},e.getPasswordAuthenticationKey=function(n,i,s,o,a){var l=this;if(s.mod(this.N).equals(G.ZERO))throw new Error("B cannot be zero.");if(this.UValue=this.calculateU(this.largeAValue,s),this.UValue.equals(G.ZERO))throw new Error("U cannot be zero.");var c=""+this.poolName+n+":"+i,d=this.hash(c),h=new G(this.hexHash(this.padHex(o)+d),16);this.calculateS(h,s,function(u,g){u&&a(u,null);var p=l.computehkdf(Oe.Buffer.from(l.padHex(g),"hex"),Oe.Buffer.from(l.padHex(l.UValue),"hex"));a(null,p);});},e.calculateS=function(n,i,s){var o=this;this.g.modPow(n,this.N,function(a,l){a&&s(a,null);var c=i.subtract(o.k.multiply(l));c.modPow(o.smallAValue.add(o.UValue.multiply(n)),o.N,function(d,h){d&&s(d,null),s(null,h.mod(o.N));});});},e.getNewPasswordRequiredChallengeUserAttributePrefix=function(){return Pd},e.padHex=function(n){if(!(n instanceof G))throw new Error("Not a BigInteger");var i=n.compareTo(G.ZERO)<0,s=n.abs().toString(16);if(s=s.length%2!==0?"0"+s:s,s=vd.test(s)?"00"+s:s,i){var o=s.split("").map(function(l){var c=~parseInt(l,16)&15;return "0123456789ABCDEF".charAt(c)}).join(""),a=new G(o,16).add(G.ONE);s=a.toString(16),s.toUpperCase().startsWith("FF8")&&(s=s.substring(2));}return s},t})();var Us=rt(dr());var Er=(function(){function t(r){this.jwtToken=r||"",this.payload=this.decodePayload();}var e=t.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(Us.Buffer.from(n,"base64").toString("utf8"))}catch{return {}}},t})();function kd(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,kn(t,e);}function kn(t,e){return kn=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(r,n){return r.__proto__=n,r},kn(t,e)}var ct=(function(t){function e(r){var n=r===void 0?{}:r,i=n.AccessToken;return t.call(this,i||"")||this}return kd(e,t),e})(Er);function xd(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,xn(t,e);}function xn(t,e){return xn=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(r,n){return r.__proto__=n,r},xn(t,e)}var ut=(function(t){function e(r){var n=r===void 0?{}:r,i=n.IdToken;return t.call(this,i||"")||this}return xd(e,t),e})(Er);var dt=(function(){function t(r){var n=r===void 0?{}:r,i=n.RefreshToken;this.token=i||"";}var e=t.prototype;return e.getToken=function(){return this.token},t})();var Y=rt(dr()),Cn=rt(Sn());var Cs="5.0.4";var Ud="aws-amplify/"+Cs,Un={userAgent:Ud,isReactNative:typeof navigator<"u"&&navigator.product==="ReactNative"},Ds=function(){return Un.userAgent};var ft=(function(){function t(r){var n=r===void 0?{}:r,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=t.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()},t})();var Cd=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],Dd=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],Ar=(function(){function t(){}var e=t.prototype;return e.getNowString=function(){var n=new Date,i=Dd[n.getUTCDay()],s=Cd[n.getUTCMonth()],o=n.getUTCDate(),a=n.getUTCHours();a<10&&(a="0"+a);var l=n.getUTCMinutes();l<10&&(l="0"+l);var c=n.getUTCSeconds();c<10&&(c="0"+c);var d=n.getUTCFullYear(),h=i+" "+s+" "+o+" "+a+":"+l+":"+c+" UTC "+d;return h},t})();var Pe=(function(){function t(r){var n=r===void 0?{}:r,i=n.Name,s=n.Value;this.Name=i||"",this.Value=s||"";}var e=t.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}},t})();var Je={},Nd=(function(){function t(){}return t.setItem=function(r,n){return Je[r]=n,Je[r]},t.getItem=function(r){return Object.prototype.hasOwnProperty.call(Je,r)?Je[r]:void 0},t.removeItem=function(r){return delete Je[r]},t.clear=function(){return Je={},Je},t})(),Rr=(function(){function t(){try{this.storageWindow=window.localStorage,this.storageWindow.setItem("aws.cognito.test-ls",1),this.storageWindow.removeItem("aws.cognito.test-ls");}catch{this.storageWindow=Nd;}}var e=t.prototype;return e.getStorage=function(){return this.storageWindow},t})();var Od=typeof navigator<"u",Ns=Od?Un.isReactNative?"react-native":navigator.userAgent:"nodejs",Fe=(function(){function t(r){if(r==null||r.Username==null||r.Pool==null)throw new Error("Username and Pool information are required.");this.username=r.Username||"",this.pool=r.Pool,this.Session=null,this.client=r.Pool.client,this.signInUserSession=null,this.authenticationFlowType="USER_SRP_AUTH",this.storage=r.Storage||new Rr().getStorage(),this.keyPrefix="CognitoIdentityServiceProvider."+this.pool.getClientId(),this.userDataKey=this.keyPrefix+"."+this.username+".userData";}var e=t.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(),l={AuthFlow:"CUSTOM_AUTH",ClientId:this.pool.getClientId(),AuthParameters:o,ClientMetadata:a};this.getUserContextData()&&(l.UserContextData=this.getUserContextData()),this.client.request("InitiateAuth",l,function(c,d){if(c)return i.onFailure(c);var h=d.ChallengeName,u=d.ChallengeParameters;return h==="CUSTOM_CHALLENGE"?(s.Session=d.Session,i.customChallenge(u)):(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 Ke(this.pool.getUserPoolName()),a=new Ar,l,c,d={};this.deviceKey!=null&&(d.DEVICE_KEY=this.deviceKey),d.USERNAME=this.username,o.getLargeAValue(function(h,u){h&&i.onFailure(h),d.SRP_A=u.toString(16),s.authenticationFlowType==="CUSTOM_AUTH"&&(d.CHALLENGE_NAME="SRP_A");var g=Object.keys(n.getValidationData()).length!==0?n.getValidationData():n.getClientMetadata(),p={AuthFlow:s.authenticationFlowType,ClientId:s.pool.getClientId(),AuthParameters:d,ClientMetadata:g};s.getUserContextData(s.username)&&(p.UserContextData=s.getUserContextData(s.username)),s.client.request("InitiateAuth",p,function(m,b){if(m)return i.onFailure(m);var y=b.ChallengeParameters;s.username=y.USER_ID_FOR_SRP,s.userDataKey=s.keyPrefix+"."+s.username+".userData",l=new G(y.SRP_B,16),c=new G(y.SALT,16),s.getCachedDeviceKeyAndPassword(),o.getPasswordAuthenticationKey(s.username,n.getPassword(),l,c,function(A,w){A&&i.onFailure(A);var S=a.getNowString(),R=Y.Buffer.concat([Y.Buffer.from(s.pool.getUserPoolName(),"utf8"),Y.Buffer.from(s.username,"utf8"),Y.Buffer.from(y.SECRET_BLOCK,"base64"),Y.Buffer.from(S,"utf8")]),U=new Cn.Sha256(w);U.update(R);var O=U.digestSync(),C=Y.Buffer.from(O).toString("base64"),I={};I.USERNAME=s.username,I.PASSWORD_CLAIM_SECRET_BLOCK=y.SECRET_BLOCK,I.TIMESTAMP=S,I.PASSWORD_CLAIM_SIGNATURE=C,s.deviceKey!=null&&(I.DEVICE_KEY=s.deviceKey);var D=function(te,ie){return s.client.request("RespondToAuthChallenge",te,function(q,X){return q&&q.code==="ResourceNotFoundException"&&q.message.toLowerCase().indexOf("device")!==-1?(I.DEVICE_KEY=null,s.deviceKey=null,s.randomPassword=null,s.deviceGroupKey=null,s.clearCachedDeviceKeyAndPassword(),D(te,ie)):ie(q,X)})},N={ChallengeName:"PASSWORD_VERIFIER",ClientId:s.pool.getClientId(),ChallengeResponses:I,Session:b.Session,ClientMetadata:g};s.getUserContextData()&&(N.UserContextData=s.getUserContextData()),D(N,function(M,te){return M?i.onFailure(M):s.authenticateUserInternal(te,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 Ke(this.pool.getUserPoolName());this.getCachedDeviceKeyAndPassword(),this.deviceKey!=null&&(o.DEVICE_KEY=this.deviceKey);var l=Object.keys(n.getValidationData()).length!==0?n.getValidationData():n.getClientMetadata(),c={AuthFlow:"USER_PASSWORD_AUTH",ClientId:this.pool.getClientId(),AuthParameters:o,ClientMetadata:l};this.getUserContextData(this.username)&&(c.UserContextData=this.getUserContextData(this.username)),this.client.request("InitiateAuth",c,function(d,h){return d?i.onFailure(d):s.authenticateUserInternal(h,a,i)});},e.authenticateUserInternal=function(n,i,s){var o=this,a=n.ChallengeName,l=n.ChallengeParameters;if(a==="SMS_MFA")return this.Session=n.Session,s.mfaRequired(a,l);if(a==="SELECT_MFA_TYPE")return this.Session=n.Session,s.selectMFAType(a,l);if(a==="MFA_SETUP")return this.Session=n.Session,s.mfaSetup(a,l);if(a==="SOFTWARE_TOKEN_MFA")return this.Session=n.Session,s.totpRequired(a,l);if(a==="CUSTOM_CHALLENGE")return this.Session=n.Session,s.customChallenge(l);if(a==="NEW_PASSWORD_REQUIRED"){this.Session=n.Session;var c=null,d=null,h=[],u=i.getNewPasswordRequiredChallengeUserAttributePrefix();if(l&&(c=JSON.parse(n.ChallengeParameters.userAttributes),d=JSON.parse(n.ChallengeParameters.requiredAttributes)),d)for(var g=0;g<d.length;g++)h[g]=d[g].substr(u.length);return s.newPasswordRequired(c,h)}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 p=n.AuthenticationResult.NewDeviceMetadata;if(p==null)return s.onSuccess(this.signInUserSession);i.generateHashDevice(n.AuthenticationResult.NewDeviceMetadata.DeviceGroupKey,n.AuthenticationResult.NewDeviceMetadata.DeviceKey,function(m){if(m)return s.onFailure(m);var b={Salt:Y.Buffer.from(i.getSaltDevices(),"hex").toString("base64"),PasswordVerifier:Y.Buffer.from(i.getVerifierDevices(),"hex").toString("base64")};o.verifierDevices=b.PasswordVerifier,o.deviceGroupKey=p.DeviceGroupKey,o.randomPassword=i.getRandomPassword(),o.client.request("ConfirmDevice",{DeviceKey:p.DeviceKey,AccessToken:o.signInUserSession.getAccessToken().getJwtToken(),DeviceSecretVerifierConfig:b,DeviceName:Ns},function(y,A){return y?s.onFailure(y):(o.deviceKey=n.AuthenticationResult.NewDeviceMetadata.DeviceKey,o.cacheDeviceKeyAndPassword(),A.UserConfirmationNecessary===true?s.onSuccess(o.signInUserSession,A.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 l=new Ke(this.pool.getUserPoolName()),c=l.getNewPasswordRequiredChallengeUserAttributePrefix(),d={};i&&Object.keys(i).forEach(function(u){d[c+u]=i[u];}),d.NEW_PASSWORD=n,d.USERNAME=this.username;var h={ChallengeName:"NEW_PASSWORD_REQUIRED",ClientId:this.pool.getClientId(),ChallengeResponses:d,Session:this.Session,ClientMetadata:o};this.getUserContextData()&&(h.UserContextData=this.getUserContextData()),this.client.request("RespondToAuthChallenge",h,function(u,g){return u?s.onFailure(u):a.authenticateUserInternal(g,l,s)});},e.getDeviceResponse=function(n,i){var s=this,o=new Ke(this.deviceGroupKey),a=new Ar,l={};l.USERNAME=this.username,l.DEVICE_KEY=this.deviceKey,o.getLargeAValue(function(c,d){c&&n.onFailure(c),l.SRP_A=d.toString(16);var h={ChallengeName:"DEVICE_SRP_AUTH",ClientId:s.pool.getClientId(),ChallengeResponses:l,ClientMetadata:i,Session:s.Session};s.getUserContextData()&&(h.UserContextData=s.getUserContextData()),s.client.request("RespondToAuthChallenge",h,function(u,g){if(u)return n.onFailure(u);var p=g.ChallengeParameters,m=new G(p.SRP_B,16),b=new G(p.SALT,16);o.getPasswordAuthenticationKey(s.deviceKey,s.randomPassword,m,b,function(y,A){if(y)return n.onFailure(y);var w=a.getNowString(),S=Y.Buffer.concat([Y.Buffer.from(s.deviceGroupKey,"utf8"),Y.Buffer.from(s.deviceKey,"utf8"),Y.Buffer.from(p.SECRET_BLOCK,"base64"),Y.Buffer.from(w,"utf8")]),R=new Cn.Sha256(A);R.update(S);var U=R.digestSync(),O=Y.Buffer.from(U).toString("base64"),C={};C.USERNAME=s.username,C.PASSWORD_CLAIM_SECRET_BLOCK=p.SECRET_BLOCK,C.TIMESTAMP=w,C.PASSWORD_CLAIM_SIGNATURE=O,C.DEVICE_KEY=s.deviceKey;var I={ChallengeName:"DEVICE_PASSWORD_VERIFIER",ClientId:s.pool.getClientId(),ChallengeResponses:C,Session:g.Session};s.getUserContextData()&&(I.UserContextData=s.getUserContextData()),s.client.request("RespondToAuthChallenge",I,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(l){return l?s(l,null):s(null,"SUCCESS")});},e.sendCustomChallengeAnswer=function(n,i,s){var o=this,a={};a.USERNAME=this.username,a.ANSWER=n;var l=new Ke(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,h){return d?i.onFailure(d):o.authenticateUserInternal(h,l,i)});},e.sendMFACode=function(n,i,s,o){var a=this,l={};l.USERNAME=this.username,l.SMS_MFA_CODE=n;var c=s||"SMS_MFA";c==="SOFTWARE_TOKEN_MFA"&&(l.SOFTWARE_TOKEN_MFA_CODE=n),this.deviceKey!=null&&(l.DEVICE_KEY=this.deviceKey);var d={ChallengeName:c,ChallengeResponses:l,ClientId:this.pool.getClientId(),Session:this.Session,ClientMetadata:o};this.getUserContextData()&&(d.UserContextData=this.getUserContextData()),this.client.request("RespondToAuthChallenge",d,function(h,u){if(h)return i.onFailure(h);var g=u.ChallengeName;if(g==="DEVICE_SRP_AUTH"){a.getDeviceResponse(i);return}if(a.signInUserSession=a.getCognitoUserSession(u.AuthenticationResult),a.cacheTokens(),u.AuthenticationResult.NewDeviceMetadata==null)return i.onSuccess(a.signInUserSession);var p=new Ke(a.pool.getUserPoolName());p.generateHashDevice(u.AuthenticationResult.NewDeviceMetadata.DeviceGroupKey,u.AuthenticationResult.NewDeviceMetadata.DeviceKey,function(m){if(m)return i.onFailure(m);var b={Salt:Y.Buffer.from(p.getSaltDevices(),"hex").toString("base64"),PasswordVerifier:Y.Buffer.from(p.getVerifierDevices(),"hex").toString("base64")};a.verifierDevices=b.PasswordVerifier,a.deviceGroupKey=u.AuthenticationResult.NewDeviceMetadata.DeviceGroupKey,a.randomPassword=p.getRandomPassword(),a.client.request("ConfirmDevice",{DeviceKey:u.AuthenticationResult.NewDeviceMetadata.DeviceKey,AccessToken:a.signInUserSession.getAccessToken().getJwtToken(),DeviceSecretVerifierConfig:b,DeviceName:Ns},function(y,A){return y?i.onFailure(y):(a.deviceKey=u.AuthenticationResult.NewDeviceMetadata.DeviceKey,a.cacheDeviceKeyAndPassword(),A.UserConfirmationNecessary===true?i.onSuccess(a.signInUserSession,A.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,l){return a?i(a,null):o.getUserData(function(){return i(null,"SUCCESS",l)},{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 l={Name:s.UserAttributes[a].Name,Value:s.UserAttributes[a].Value},c=new Pe(l);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",l=s+".refreshToken",c=s+".clockDrift";if(this.storage.getItem(o)){var d=new ut({IdToken:this.storage.getItem(o)}),h=new ct({AccessToken:this.storage.getItem(a)}),u=new dt({RefreshToken:this.storage.getItem(l)}),g=parseInt(this.storage.getItem(c),0)||0,p={IdToken:d,AccessToken:h,RefreshToken:u,ClockDrift:g},m=new ft(p);if(m.isValid())return this.signInUserSession=m,n(null,this.signInUserSession);if(!u.getToken())return n(new Error("Cannot retrieve a new session. Please authenticate."),null);this.refreshSession(u,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,l={};l.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 h=c+"."+this.username+".deviceKey";this.deviceKey=this.storage.getItem(h),l.DEVICE_KEY=this.deviceKey;}var u={ClientId:this.pool.getClientId(),AuthFlow:"REFRESH_TOKEN_AUTH",AuthParameters:l,ClientMetadata:s};this.getUserContextData()&&(u.UserContextData=this.getUserContextData()),this.client.requestWithRetry("InitiateAuth",u,function(g,p){if(g)return g.code==="NotAuthorizedException"&&o.clearCachedUser(),a(g,null);if(p){var m=p.AuthenticationResult;return Object.prototype.hasOwnProperty.call(m,"RefreshToken")||(m.RefreshToken=n.getToken()),o.signInUserSession=o.getCognitoUserSession(m),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",l=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(l,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",l=n+"."+this.username+".clockDrift";this.storage.removeItem(i),this.storage.removeItem(s),this.storage.removeItem(o),this.storage.removeItem(a),this.storage.removeItem(l);},e.getCognitoUserSession=function(n){var i=new ut(n),s=new ct(n),o=new dt(n),a={IdToken:i,AccessToken:s,RefreshToken:o};return new ft(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(l){return l?s.onFailure(l):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,l){return a?s.onFailure(a):s.onSuccess(l)});},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(),l=this.signInUserSession.getAccessToken();if(this.isSessionRevocable(l)&&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(l,c){if(l)return i.onFailure(l);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,l){return a?s.onFailure(a):s.onSuccess(l)}):this.client.request("VerifySoftwareToken",{Session:this.Session,UserCode:n,FriendlyDeviceName:i},function(a,l){if(a)return s.onFailure(a);o.Session=l.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(h,u){return h?s.onFailure(h):(o.signInUserSession=o.getCognitoUserSession(u.AuthenticationResult),o.cacheTokens(),s.onSuccess(o.signInUserSession))});});},t})();rt(Fs());function ht(){}ht.prototype.userAgent=Ds();var Ls=function(e){var r=ht.category?" "+ht.category:"",n=ht.framework?" framework/"+ht.framework:"",i=""+ht.prototype.userAgent+r+n;return i};function Ld(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,xt(t,e);}function On(t){var e=typeof Map=="function"?new Map:void 0;return On=function(n){if(n===null||!qd(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 Md(n,arguments,Fn(this).constructor)}return i.prototype=Object.create(n.prototype,{constructor:{value:i,enumerable:false,writable:true,configurable:true}}),xt(i,n)},On(t)}function Md(t,e,r){if(Ms())return Reflect.construct.apply(null,arguments);var n=[null];n.push.apply(n,e);var i=new(t.bind.apply(t,n));return r&&xt(i,r.prototype),i}function Ms(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}));}catch{}return (Ms=function(){return !!t})()}function qd(t){try{return Function.toString.call(t).indexOf("[native code]")!==-1}catch{return typeof t=="function"}}function xt(t,e){return xt=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(r,n){return r.__proto__=n,r},xt(t,e)}function Fn(t){return Fn=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},Fn(t)}var Vd=(function(t){function e(r,n,i,s){var o;return o=t.call(this,r)||this,o.code=n,o.name=i,o.statusCode=s,o}return Ld(e,t),e})(On(Error)),qs=(function(){function t(r,n,i){this.endpoint=n||"https://cognito-idp."+r+".amazonaws.com/";var s=i||{},o=s.credentials;this.fetchOptions=o?{credentials:o}:{};}var e=t.prototype;return e.promisifyRequest=function(n,i){var s=this;return new Promise(function(o,a){s.request(n,i,function(l,c){l?a(new Vd(l.message,l.code,l.name,l.statusCode)):o(c);});})},e.requestWithRetry=function(n,i,s){var o=this,a=5*1e3;$d(function(l){return new Promise(function(c,d){o.request(n,l,function(h,u){h?d(h):c(u);});})},[i],a).then(function(l){return s(null,l)}).catch(function(l){return s(l)});},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":Ls(),"Cache-Control":"no-store"},a=Object.assign({},this.fetchOptions,{headers:o,method:"POST",mode:"cors",body:JSON.stringify(i)}),l;fetch(this.endpoint,a).then(function(d){return l=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(l.ok)return s(null,d);var h=(d.__type||d.code).split("#").pop(),u=new Error(d.message||d.Message||null);return u.name=h,u.code=h,s(u)}).catch(function(d){if(l&&l.headers&&l.headers.get("x-amzn-errortype"))try{var h=l.headers.get("x-amzn-errortype").split(":")[0],u=new Error(l.status?l.status.toString():null);return u.code=h,u.name=h,u.statusCode=l.status,s(u)}catch{return s(d)}else d instanceof Error&&d.message==="Network error"&&(d.code="NetworkError");return s(d)});},t})();var Sr={debug:function(){}};var Bd=function(e){var r="nonRetryable";return e&&e[r]};function Vs(t,e,r,n){if(n===void 0&&(n=1),typeof t!="function")throw Error("functionToRetry must be a function");return Sr.debug(t.name+" attempt #"+n+" with args: "+JSON.stringify(e)),t.apply(void 0,e).catch(function(i){if(Sr.debug("error on "+t.name,i),Bd(i))throw Sr.debug(t.name+" non retryable error",i),i;var s=r(n,e,i);if(Sr.debug(t.name+" retrying in "+s+" ms"),s!==false)return new Promise(function(o){return setTimeout(o,s)}).then(function(){return Vs(t,e,r,n+1)});throw i})}function jd(t){var e=100,r=100;return function(n){var i=Math.pow(2,n)*e+r*Math.random();return i>t?false:i}}function $d(t,e,r){return Vs(t,e,jd(r))}var Hd=55,Ln=(function(){function t(r,n){var i=r||{},s=i.UserPoolId,o=i.ClientId,a=i.endpoint,l=i.fetchOptions,c=i.AdvancedSecurityDataCollectionFlag;if(!s||!o)throw new Error("Both UserPoolId and ClientId are required.");if(s.length>Hd||!/^[\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 qs(d,a,l),this.advancedSecurityDataCollectionFlag=c!==false,this.storage=r.Storage||new Rr().getStorage(),n&&(this.wrapRefreshSessionCallback=n);}var e=t.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,l){var c=this,d={ClientId:this.clientId,Username:n,Password:i,UserAttributes:s,ValidationData:o,ClientMetadata:l};this.getUserContextData(n)&&(d.UserContextData=this.getUserContextData(n)),this.client.request("SignUp",d,function(h,u){if(h)return a(h,null);var g={Username:n,Pool:c,Storage:c.storage},p={user:new Fe(g),userConfirmed:u.UserConfirmed,userSub:u.UserSub,codeDeliveryDetails:u.CodeDeliveryDetails};return a(null,p)});},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 Fe(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 {}}},t})();function Tr(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)n!=="__proto__"&&(t[n]=r[n]);}return t}var Gd={read:function(t){return t[0]==='"'&&(t=t.slice(1,-1)),t.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(t){return encodeURIComponent(t).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}};function Mn(t,e){function r(i,s,o){if(!(typeof document>"u")){o=Tr({},e,o),typeof o.expires=="number"&&(o.expires=new Date(Date.now()+o.expires*864e5)),o.expires&&(o.expires=o.expires.toUTCString()),i=encodeURIComponent(i).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var a="";for(var l in o)o[l]&&(a+="; "+l,o[l]!==true&&(a+="="+o[l].split(";")[0]));return document.cookie=i+"="+t.write(s,i)+a}}function n(i){if(!(typeof document>"u"||arguments.length&&!i)){for(var s=document.cookie?document.cookie.split("; "):[],o={},a=0;a<s.length;a++){var l=s[a].split("="),c=l.slice(1).join("=");try{var d=decodeURIComponent(l[0]);if(d in o||(o[d]=t.read(c,d)),i===d)break}catch{}}return i?o[i]:o}}return Object.create({set:r,get:n,remove:function(i,s){r(i,"",Tr({},s,{expires:-1}));},withAttributes:function(i){return Mn(this.converter,Tr({},this.attributes,i))},withConverter:function(i){return Mn(Tr({},this.converter,i),this.attributes)}},{attributes:{value:Object.freeze(e)},converter:{value:Object.freeze(t)}})}Mn(Gd,{path:"/"});var f=class extends Error{constructor(e,r){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=r?.name||"SKAPI",this.code=r?.code||e[0]||"ERROR",r?.cause&&(this.cause=r.cause);}else super((e?.message||(typeof e=="string"?e:"Something went wrong.")).trim()),typeof e=="string"?(this.name=r?.name||"SKAPI",this.code=r?.code||"ERROR",r?.cause&&(this.cause=r.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=r?.name||"SKAPI",this.code=r?.code||"ERROR",this.cause=e?.cause);}};var Le="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",qn=BigInt(Le.length),zd=2*1024*1024,Jd=["aud","cognito:username","event_id","exp","iat","iss","jti","origin_jti","secret_key","token_use"],Bs={auth_time:"log",sub:"user_id"},Gs=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f","g","h","i","j","k","l"],Ws=["us31","us72","ap51","ap22","ap41","eu71","ap21","us32","us71","af51","ap31","ap43","ap23","ap42","ca01","eu01","eu72","eu51","eu73","eu11","me51","sa31"],js=typeof TextEncoder<"u"?new TextEncoder:null;function Yd(){if(typeof globalThis<"u")return globalThis.Buffer}function W(t){if(js)return js.encode(t);let e=unescape(encodeURIComponent(t)),r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return r}function Vn(t){if(t instanceof Uint8Array)return t;if(typeof t=="string")return W(t);if(typeof ArrayBuffer<"u"&&t instanceof ArrayBuffer)return new Uint8Array(t);if(typeof ArrayBuffer<"u"&&ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);if(Array.isArray(t))return Uint8Array.from(t);let e=Yd();if(e)return new Uint8Array(e.from(t));throw new Error("No byte conversion available in this environment.")}var v=class v{static hash(e){typeof e!="string"&&(console.warn("coercing non-string value to empty string"),e="");let r=v.sb(e),n=1732584193,i=-271733879,s=-1732584194,o=271733878,a,l,c,d;for(let h=0;h<r.length;h+=16)a=n,l=i,c=s,d=o,n=v.ff(n,i,s,o,r[h],7,-680876936),o=v.ff(o,n,i,s,r[h+1],12,-389564586),s=v.ff(s,o,n,i,r[h+2],17,606105819),i=v.ff(i,s,o,n,r[h+3],22,-1044525330),n=v.ff(n,i,s,o,r[h+4],7,-176418897),o=v.ff(o,n,i,s,r[h+5],12,1200080426),s=v.ff(s,o,n,i,r[h+6],17,-1473231341),i=v.ff(i,s,o,n,r[h+7],22,-45705983),n=v.ff(n,i,s,o,r[h+8],7,1770035416),o=v.ff(o,n,i,s,r[h+9],12,-1958414417),s=v.ff(s,o,n,i,r[h+10],17,-42063),i=v.ff(i,s,o,n,r[h+11],22,-1990404162),n=v.ff(n,i,s,o,r[h+12],7,1804603682),o=v.ff(o,n,i,s,r[h+13],12,-40341101),s=v.ff(s,o,n,i,r[h+14],17,-1502002290),i=v.ff(i,s,o,n,r[h+15],22,1236535329),n=v.gg(n,i,s,o,r[h+1],5,-165796510),o=v.gg(o,n,i,s,r[h+6],9,-1069501632),s=v.gg(s,o,n,i,r[h+11],14,643717713),i=v.gg(i,s,o,n,r[h],20,-373897302),n=v.gg(n,i,s,o,r[h+5],5,-701558691),o=v.gg(o,n,i,s,r[h+10],9,38016083),s=v.gg(s,o,n,i,r[h+15],14,-660478335),i=v.gg(i,s,o,n,r[h+4],20,-405537848),n=v.gg(n,i,s,o,r[h+9],5,568446438),o=v.gg(o,n,i,s,r[h+14],9,-1019803690),s=v.gg(s,o,n,i,r[h+3],14,-187363961),i=v.gg(i,s,o,n,r[h+8],20,1163531501),n=v.gg(n,i,s,o,r[h+13],5,-1444681467),o=v.gg(o,n,i,s,r[h+2],9,-51403784),s=v.gg(s,o,n,i,r[h+7],14,1735328473),i=v.gg(i,s,o,n,r[h+12],20,-1926607734),n=v.hh(n,i,s,o,r[h+5],4,-378558),o=v.hh(o,n,i,s,r[h+8],11,-2022574463),s=v.hh(s,o,n,i,r[h+11],16,1839030562),i=v.hh(i,s,o,n,r[h+14],23,-35309556),n=v.hh(n,i,s,o,r[h+1],4,-1530992060),o=v.hh(o,n,i,s,r[h+4],11,1272893353),s=v.hh(s,o,n,i,r[h+7],16,-155497632),i=v.hh(i,s,o,n,r[h+10],23,-1094730640),n=v.hh(n,i,s,o,r[h+13],4,681279174),o=v.hh(o,n,i,s,r[h],11,-358537222),s=v.hh(s,o,n,i,r[h+3],16,-722521979),i=v.hh(i,s,o,n,r[h+6],23,76029189),n=v.hh(n,i,s,o,r[h+9],4,-640364487),o=v.hh(o,n,i,s,r[h+12],11,-421815835),s=v.hh(s,o,n,i,r[h+15],16,530742520),i=v.hh(i,s,o,n,r[h+2],23,-995338651),n=v.ii(n,i,s,o,r[h],6,-198630844),o=v.ii(o,n,i,s,r[h+7],10,1126891415),s=v.ii(s,o,n,i,r[h+14],15,-1416354905),i=v.ii(i,s,o,n,r[h+5],21,-57434055),n=v.ii(n,i,s,o,r[h+12],6,1700485571),o=v.ii(o,n,i,s,r[h+3],10,-1894986606),s=v.ii(s,o,n,i,r[h+10],15,-1051523),i=v.ii(i,s,o,n,r[h+1],21,-2054922799),n=v.ii(n,i,s,o,r[h+8],6,1873313359),o=v.ii(o,n,i,s,r[h+15],10,-30611744),s=v.ii(s,o,n,i,r[h+6],15,-1560198380),i=v.ii(i,s,o,n,r[h+13],21,1309151649),n=v.ii(n,i,s,o,r[h+4],6,-145523070),o=v.ii(o,n,i,s,r[h+11],10,-1120210379),s=v.ii(s,o,n,i,r[h+2],15,718787259),i=v.ii(i,s,o,n,r[h+9],21,-343485551),n=v.ad(n,a),i=v.ad(i,l),s=v.ad(s,c),o=v.ad(o,d);return v.rh(n)+v.rh(i)+v.rh(s)+v.rh(o)}static rh(e){let r="";for(let n=0;n<=3;n++)r+=v.alphabet.charAt(e>>n*8+4&15)+v.alphabet.charAt(e>>n*8&15);return r}static ad(e,r){let n=(e&65535)+(r&65535);return (e>>16)+(r>>16)+(n>>16)<<16|n&65535}static rl(e,r){return e<<r|e>>>32-r}static cm(e,r,n,i,s,o){return v.ad(v.rl(v.ad(v.ad(r,e),v.ad(i,o)),s),n)}static ff(e,r,n,i,s,o,a){return v.cm(r&n|~r&i,e,r,s,o,a)}static gg(e,r,n,i,s,o,a){return v.cm(r&i|n&~i,e,r,s,o,a)}static hh(e,r,n,i,s,o,a){return v.cm(r^n^i,e,r,s,o,a)}static ii(e,r,n,i,s,o,a){return v.cm(n^(r|~i),e,r,s,o,a)}static sb(e){let r,n=(e.length+8>>6)+1,i=new Array(n*16);for(r=0;r<n*16;r++)i[r]=0;for(r=0;r<e.length;r++)i[r>>2]|=e.charCodeAt(r)<<r%4*8;return i[r>>2]|=128<<r%4*8,i[n*16-2]=e.length*8,i}};v.alphabet="0123456789abcdef";var ce=v;function zs(t){if(t===0)return Le[0];let e="";for(;t>0;)e=Le[t%62]+e,t=Math.floor(t/62);return e}function _e(t){return t.split("").reverse().reduce((e,r,n)=>e+Le.indexOf(r)*62**n,0)}function Ye(t=6){let e="",r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n=r.length,i=0;for(;i<t;)e+=r.charAt(Math.floor(Math.random()*n)),i+=1;return e}function Bn(){return typeof window>"u"||!!window?._runningInNodeJS}function J(){return !Bn()&&typeof document<"u"&&typeof document.createElement=="function"}function vr(t){let e;try{e=JSON.stringify(t);}catch{throw new f("Invalid data type.",{code:"INVALID_REQUEST"})}if(new Blob([e]).size>zd)throw new f("Data should not exceed 2MB",{code:"INVALID_REQUEST"})}function Ks(t){return t===""||t==="on"||t==="true"}function $s(t){return t==="false"}function Hs(t,e,r){e.name&&r(t,e.name,e.value);}var Ir=J(),Qd=typeof SubmitEvent<"u",Xd=typeof HTMLFormElement<"u";function K(t,e,r){let n={},i=[];function s(l,c,d){if(e?.ignoreEmpty&&d==="")return;if(e?.nullIfEmpty&&d===""&&(d=null),typeof r=="function"){let g=r(c,d);g!==void 0&&(d=g);}let h=c.split("[").map(g=>{let p=g.replace("]",""),m=Number(p);return !isNaN(m)&&!p.includes(".")?p=m:(p[0]==='"'&&p[p.length-1]==='"'||p[0]==="'"&&p[p.length-1]==="'")&&(p=p.replace(/"/g,"").replace(/'/g,"")),p}),u=l;if(typeof h[0]=="number")throw new f("Form key cannot start with an array index.",{code:"INVALID_REQUEST"});for(let g=0;g<h.length;g++){let p=h[g];g<h.length-1?(u[p]===void 0&&(typeof h[g+1]=="number"?u[p]=[]:u[p]={}),u=u[p]):u[p]===void 0?u[p]=d:Array.isArray(u[p])?u[p].push(d):u[p]=[u[p],d];}}function o(l,c,d){if(d instanceof File)l.push({name:c,file:d});else if(d instanceof FileList&&d&&d.length>0)for(let h=0;h<=d.length-1;h++){let u=d.item(h);u&&l.push({name:c,file:u});}}let a=l=>{l.name&&(l.type==="number"?l.value&&s(n,l.name,Number(l.value)):l.type==="checkbox"||l.type==="radio"?l.checked?l.type==="checkbox"&&l.value===""||Ks(l.value)?s(n,l.name,true):$s(l.value)?s(n,l.name,false):l.value&&s(n,l.name,l.value):l.type==="checkbox"&&(Ks(l.value)?s(n,l.name,false):$s(l.value)&&s(n,l.name,true)):l.type==="file"?l.files&&l.files.length>0&&o(i,l.name,l.files):s(n,l.name,l.value));};if(Ir&&(t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement))return a(t),vr(n),{data:n,files:i};if(Ir&&t instanceof FormData){for(let l of t.entries()){let c=l[0],d=l[1];if(d instanceof File||d instanceof FileList)o(i,c,d);else if(d instanceof Blob){let h=d;if(h.type==="application/json")try{let u=JSON.parse(h.text());s(n,c,u);}catch{s(n,c,h);}}else s(n,c,d);}return vr(n),{data:n,files:i}}if(Ir&&Qd&&t instanceof SubmitEvent&&(t=t.target),Ir&&Xd&&t instanceof HTMLFormElement){let l=t.querySelectorAll("input"),c=t.querySelectorAll("select"),d=t.querySelectorAll("textarea");for(let h=0;h<c.length;h++)Hs(n,c[h],s);for(let h=0;h<d.length;h++)Hs(n,d[h],s);for(let h=0;h<l.length;h++)a(l[h]);return vr(n),{data:n,files:i}}return vr(t),{data:t,files:i}}function Ut(t){let e={};for(let r in t){let n=t[r];if(!Jd.includes(r))if(Bs[r])e[Bs[r]]=n;else if(r.includes("custom:"))e[r.replace("custom:","")]=n;else if(r==="address"){let i=n;if(i&&typeof i=="object"&&Object.keys(i).length){if(i?.formatted)try{e[r]=JSON.parse(i.formatted);}catch{e[r]=i.formatted;}}else e[r]=i;}else e[r]=n;}for(let r of ["address_public","birthdate_public","email_public","gender_public","phone_number_public","access_group"])r.includes("_public")?e.hasOwnProperty(r.split("_")[0])?e[r]=e.hasOwnProperty(r)?!!Number(e[r]):false:delete e[r]:e[r]=e.hasOwnProperty(r)?Number(e[r]):0;for(let r of ["email","phone_number"])e.hasOwnProperty(r)?e[r+"_verified"]=e[r+"_verified"]===true:delete e[r+"_verified"];return e}function jn(t){if(t=af(t),t.split("-").length===7){let e=t.split("-"),r,n;try{r=Ws[Gs.indexOf(e[1][0])],n=e.slice(2).join("-");}catch{throw new Error("INVALID_PARAMETER: Service ID is invalid: "+t)}if(!r)throw new Error("INVALID_PARAMETER: Service ID is invalid: "+t);return {service:r+e[0]+e[1].slice(1),owner:n}}return {service:t,owner:""}}function Kn(t,e){let r=Ws.indexOf(t.slice(0,4)),n=Gs[r],s=`${t.slice(4,-4)}-${n}${t.slice(-4)}-${e}`;return of(s)}function Zd(t){let e=0n;for(let r of t){let n=Le.indexOf(r);if(n<0)throw new Error(`INVALID_PARAMETER: Invalid base62 character: ${r}`);e=e*qn+BigInt(n);}return e}function ef(t,e=1){if(t<0n)throw new Error("INVALID_PARAMETER: Negative values are not supported.");if(t===0n)return "0".repeat(Math.max(1,e));let r="",n=t;for(;n>0n;){let i=Number(n%qn);r=Le[i]+r,n/=qn;}return r.length<e&&(r="0".repeat(e-r.length)+r),r}function tf(t){if(t===0n)return Uint8Array.from([0]);let e=[],r=t;for(;r>0n;)e.push(Number(r&0xffn)),r>>=8n;return e.reverse(),Uint8Array.from(e)}function rf(t){let e=0n;for(let r of t)e=(e<<8n)+BigInt(r);return e}function nf(t){let e=String(t).replace(/-/g,"");if(!/^[0-9a-fA-F]{32}$/.test(e))throw new Error("INVALID_PARAMETER: Invalid UUID format.");let r=new Uint8Array(16);for(let n=0;n<16;n++)r[n]=parseInt(e.slice(n*2,n*2+2),16);return r}function sf(t){let e=Array.from(Vn(t),r=>r.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 of(t){let e=String(t);if(e.split("-").length===2)return e;let r=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(!r)throw new Error("INVALID_PARAMETER: Input must match <base62>-<base62>-<uuid>.");let[,n,i,s]=r;if(n.length<2)throw new Error("INVALID_PARAMETER: The first part must contain at least 2 characters.");if(i.length>=Le.length)throw new Error("INVALID_PARAMETER: The middle section is too long to encode.");let o=n.slice(0,2),a=n.slice(2),l=i+o,c=Le[i.length]+a+l,d=nf(s),h=ef(rf(d));return `${c}-${h}`}function af(t){let e=String(t);if(e.split("-").length!==2)return e;let r=e.split("-");if(r.length!==2||!r[0]||!r[1])throw new Error("INVALID_PARAMETER: Corrupt compressed token: "+e);let[n,i]=r,s=Le.indexOf(n[0]);if(s<0)throw new Error("INVALID_PARAMETER: Corrupt compressed token: "+e);let o=n.slice(1),a=s+2;if(o.length<a)throw new Error("INVALID_PARAMETER: Corrupt compressed token: "+e);let l=o.slice(0,o.length-a),c=o.slice(o.length-a),d=c.slice(s),h=c.slice(0,s),u=d+l;if(!/^[0-9A-Za-z]+$/.test(u)||!/^[0-9A-Za-z]+$/.test(h))throw new Error("INVALID_PARAMETER: Corrupt compressed token: "+e);let g=Zd(i),p=tf(g);if(p.length>16)throw new Error("INVALID_PARAMETER: Corrupt compressed token: "+e);let m=new Uint8Array(16);m.set(p,16-p.length);let b=sf(m);return `${u}-${h}-${b}`}function Ct(t){if(typeof TextDecoder<"u")return new TextDecoder().decode(t);let e="";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return decodeURIComponent(escape(e))}function $n(...t){let e=0;for(let i of t)e+=i.length;let r=new Uint8Array(e),n=0;for(let i of t)r.set(i,n),n+=i.length;return r}function Dt(t,e,r=[],n=null){let i=["string","number","boolean","object","array","function","null","undefined"];function s(p){return p!==null&&typeof p=="object"&&!Array.isArray(p)}function o(p){return s(p)}function a(p){return Array.isArray(p)}function l(p){return typeof p=="string"&&i.indexOf(p)!==-1}function c(p){return Array.isArray(p)?"array":p===null?"null":typeof p}function d(p){try{return JSON.stringify(p)}catch{return String(p)}}function h(p){if(l(p))return `Type<${p}>`;if(typeof p=="function")return "custom validator";try{return JSON.stringify(p,(m,b)=>typeof b=="function"?"custom validator":b)}catch{return String(p)}}function u(p,m){return m==="array"?Array.isArray(p):m==="object"?s(p):m==="null"?p===null:m==="undefined"?typeof p>"u":typeof p===m}function g(p){return n===null?p:`${n}[${p}]`}if(typeof e>"u")throw new Error('Argument "struct" is required.');if(typeof e=="function")return e(t);if(o(e)){if(!s(t))throw new Error(`Data schema does not match:
|
|
207
|
-
`+JSON.stringify(t,null,2));for(let p of Object.keys(e)){let m=g(p);if(Object.prototype.hasOwnProperty.call(t,p))t[p]=Dt(t[p],e[p],r,m);else {if(r.indexOf(m)!==-1)throw new Error(`Key "${m}" is required.`);let b=e[p];a(b)&&b.length>1&&typeof b[b.length-1]=="function"&&(t[p]=b[b.length-1]());}}return t}if(a(e)){let p=false;if(e.length===1&&!a(e[0])&&!o(e[0])){let m=e[0];if(!Array.isArray(t))throw new Error(`Type <${c(t)}> is invalid in "${n}". Expected a list.`);for(let b=0;b<t.length;b++){let y=t[b];if(l(m)){if(!u(y,m))throw new Error(`Type <${c(y)}> is invalid in "${n}". Expected a list of Type <${m}>.`)}else if(typeof m=="function")t[b]=m(y);else if(y!==m)throw new Error(`Value ${d(y)} is invalid in "${n}". Expected a list of ${d(m)}.`)}p=true;}else if(Array.isArray(t)&&e.every(b=>!a(b)&&b!=="array")){for(let b=0;b<t.length;b++){let y=false,A="";for(let w of e)try{t[b]=Dt(t[b],w,r,n),y=!0;break}catch(S){typeof w=="function"&&(A=S?.message||String(S));}if(!y&&A)throw new Error(A);if(!y){let w=e.map(h).join(", ");throw new Error(`${d(t[b])} is invalid in "${n}". allowed types or values are: ${w}.`)}}p=true;}else {let b="";for(let y of e)try{t=Dt(t,y,r,n),p=!0;break}catch(A){typeof y=="function"&&(b=A?.message||String(A));}if(!p&&b)throw new Error(b)}if(!p){let m=e.map(h).join(", ");throw new Error(`${d(t)} is invalid in "${n}". allowed types or values are: ${m}.`)}return t}if(l(e)&&u(t,e)||t===e)return t;throw new Error(`${d(t)} is invalid in "${n}". allowed type or value is: ${h(e)}.`)}function lf(t,e="User ID"){let r=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;if(t){if(typeof t!="string")throw new f(`${e} should be type: string.`,{code:"INVALID_PARAMETER"});if(!t.match(r))throw new f(`${e} is invalid.`,{code:"INVALID_PARAMETER"})}else throw new f(`${e} is empty.`,{code:"INVALID_PARAMETER"});return t}function cf(t){if(t&&(typeof t!="string"||t.charAt(0)!=="+"||isNaN(Number(t.substring(1)))))throw new f('"phone_number" is invalid. The format should be "+00123456789". Type: string.',{code:"INVALID_PARAMETER"});return t||""}function uf(t){if(t){if(typeof t!="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(t.length!==10||t.split("-").length!==3||!e.test(t))throw new f('"birthdate" is invalid. The format should be "yyyy-mm-dd". Type: string.',{code:"INVALID_PARAMETER"})}}return t||""}function df(t){if(t){if(typeof t!="string")throw new f('"password" should be type: string.',{code:"INVALID_PARAMETER"});if(t.length<6)throw new f('"password" should be at least 6 characters.',{code:"INVALID_PARAMETER"});if(t.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 t}function ff(t,e="email"){if(t){if(typeof t!="string")throw new f(`"${e}"should be type: string.`,{code:"INVALID_PARAMETER"});if(t.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(t)&&(t=t.trim(),t.split("@")[1].split(".").length>=2))return t.toLowerCase()}else throw new f(`"${e}" is required.`,{code:"INVALID_PARAMETER"});throw new f(`"${t}" is an invalid email.`,{code:"INVALID_PARAMETER"})}function hf(t){let e=typeof window<"u",r=(()=>{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]==="/"&&r){if(r.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=r+s;}else if(s[0]==="."&&r){if(r.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(t)?t.map(i=>n(i)):n(t)}var pf=/^[a-z0-9]{2,20}$/,gf=/[a-z]/,mf=/^[0-9]+e[0-9]+$/,yf=["tp","admin","public","authorized","newsletter","forward","all","true","false","null"];function bf(t,e){if(t==null){if(e?.allowNull)return null;throw new f('"group" is required.',{code:"INVALID_PARAMETER"})}if(!e?.nameOnly){if(t==="public")return 0;if(t==="authorized")return 1;if(typeof t=="number"){if(!Number.isInteger(t)||t<0||t>99)throw new f('"group" should be an integer between 0 and 99.',{code:"INVALID_PARAMETER"});return t}}if(typeof t!="string"||!pf.test(t)||!gf.test(t)||mf.test(t)||yf.includes(t))throw new f("Newsletter group name must be 2-20 lowercase alphanumeric characters, contain a letter, and not be a reserved name.",{code:"INVALID_PARAMETER"});return t}function _f(t,e,r=[],n){let i=K(t,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 Dt(o,e,r)}catch(a){throw new f(a.message,{code:"INVALID_PARAMETER"})}}var _={UserId:lf,PhoneNumber:cf,Birthdate:uf,Password:df,Email:ff,Url:hf,newsletterGroup:bf,Params:_f};var ae="skapi.enc.v1",Qs=6e5,Nt=12,Pr=null,pt=null;function Xs(){return new f("Encryption requires Web Crypto, which needs a secure context (https, or localhost) in the browser, or Node 18 or newer. A page served over plain http has crypto.getRandomValues but crypto.subtle is undefined.",{code:"NOT_SUPPORTED"})}function Zs(){if(pt)return pt;let t=typeof globalThis<"u"?globalThis:void 0;if(t?.crypto?.subtle&&typeof t.crypto.getRandomValues=="function")return pt=t.crypto,pt;try{let e=typeof globalThis<"u"?globalThis:void 0,r=null;if(e?.process&&typeof e.process.getBuiltinModule=="function"&&(r=e.process.getBuiltinModule("crypto")),!r&&typeof Be=="function"&&(r=Be("crypto")),r?.webcrypto?.subtle)return pt=r.webcrypto,pt}catch{}throw Xs()}function ye(){if(Pr)return Pr;let t=Zs();if(!t.subtle)throw Xs();return Pr=t.subtle,Pr}function Gn(){try{return ye(),!0}catch{return false}}function le(t){let e=Zs(),r=new Uint8Array(t),n=65536;for(let i=0;i<t;i+=n)e.getRandomValues(r.subarray(i,Math.min(i+n,t)));return r}function j(t){let e=Vn(t),r;if(typeof Buffer<"u"&&typeof Buffer.from=="function")r=Buffer.from(e).toString("base64");else if(typeof btoa=="function"){let n="";for(let s=0;s<e.length;s+=32768)n+=String.fromCharCode.apply(null,Array.from(e.subarray(s,s+32768)));r=btoa(n);}else throw new f("No base64 encoder available in this environment.",{code:"NOT_SUPPORTED"});return r.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function $(t){if(typeof t!="string")throw new f("Expected a base64url string.",{code:"INVALID_PARAMETER"});let e=t.replace(/-/g,"+").replace(/_/g,"/"),r=e.length%4;if(r===2)e+="==";else if(r===3)e+="=";else if(r===1)throw new f("Malformed base64url string.",{code:"INVALID_PARAMETER"});if(typeof Buffer<"u"&&typeof Buffer.from=="function"){let n=Buffer.from(e,"base64");return new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}if(typeof atob=="function"){let n=atob(e),i=new Uint8Array(n.length);for(let s=0;s<n.length;s++)i[s]=n.charCodeAt(s);return i}throw new f("No base64 decoder available in this environment.",{code:"NOT_SUPPORTED"})}async function kr(t){let e=await ye().digest("SHA-256",t);return new Uint8Array(e)}async function Lt(t,e,r,n){let i=ye(),s=await i.importKey("raw",t,"HKDF",false,["deriveBits"]),o=await i.deriveBits({name:"HKDF",hash:"SHA-256",salt:e,info:r},s,n*8);return new Uint8Array(o)}async function mt(t,e,r,n){let i=ye(),s=W(t.normalize("NFC")),o=await i.importKey("raw",s,"PBKDF2",false,["deriveBits"]),a=new Uint8Array(await i.deriveBits({name:"PBKDF2",salt:e,iterations:r,hash:"SHA-256"},o,256)),l=await Lt(a,e,n,32);B(a),B(s);let c=await we(l);return B(l),c}async function we(t){return ye().importKey("raw",t,{name:"AES-GCM"},false,["encrypt","decrypt"])}async function eo(){let t=le(32),e=await we(t);return {bytes:t,key:e}}async function be(t,e,r){let n=le(Nt),i=await ye().encrypt({name:"AES-GCM",iv:n,additionalData:r,tagLength:128},t,e);return {iv:n,ct:new Uint8Array(i)}}async function Ee(t,e,r,n){let i=await ye().decrypt({name:"AES-GCM",iv:e,additionalData:n,tagLength:128},t,r);return new Uint8Array(i)}var xr={name:"ECDH",namedCurve:"P-256"};async function to(){let t=ye(),e=await t.generateKey(xr,true,["deriveBits"]),r=new Uint8Array(await t.exportKey("raw",e.publicKey)),n=new Uint8Array(await t.exportKey("pkcs8",e.privateKey)),i=await Wn(n);return {pubRaw:r,pkcs8:n,priv:i}}async function Wn(t){return ye().importKey("pkcs8",t,xr,false,["deriveBits"])}async function ro(t){if(t.length!==65||t[0]!==4)throw new f("Malformed public key: expected a 65 byte uncompressed P-256 point.",{code:"INVALID_PARAMETER"});return ye().importKey("raw",t,xr,false,[])}async function zn(t){return j(await kr(t))}async function no(t,e,r,n){let i=ye(),s=await ro(t),o=await i.generateKey(xr,true,["deriveBits"]),a=new Uint8Array(await i.deriveBits({name:"ECDH",public:s},o.privateKey,256)),l=await Lt(a,new Uint8Array(32),r,32);B(a);let c=await we(l);B(l);let{iv:d,ct:h}=await be(c,e,n);return {epk:new Uint8Array(await i.exportKey("raw",o.publicKey)),iv:d,ct:h}}async function io(t,e,r,n,i,s){let o=ye(),a=await ro(e),l=new Uint8Array(await o.deriveBits({name:"ECDH",public:a},t,256)),c=await Lt(l,new Uint8Array(32),i,32);B(l);let d=await we(c);return B(c),Ee(d,r,n,s)}function B(t){t&&t.length&&t.fill(0);}function wf(t,e){if(t.length!==e.length)return false;let r=0;for(let n=0;n<t.length;n++)r|=t[n]^e[n];return r===0}function Jn(t){return W(JSON.stringify(t))}function Mt(t,e,r){return $n(t,new Uint8Array([0]),W(e),new Uint8Array([0]),W(r))}var Qe="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Ot=16,Js=26,Ys=28;function so(t){let e=2166136261;for(let r=0;r<t.length;r++)e^=t[r],e=e*16777619>>>0;return e&1023}function oo(t){if(t.length!==Ot)throw new f(`A recovery code needs exactly ${Ot} bytes.`,{code:"INVALID_PARAMETER"});let e="",r=0,n=0;for(let s=0;s<t.length;s++)for(r=r<<8|t[s],n+=8;n>=5;)n-=5,e+=Qe[r>>n&31];n>0&&(e+=Qe[r<<5-n&31]);let i=so(t);return e+=Qe[i>>5&31]+Qe[i&31],(e.match(/.{1,4}/g)||[]).join("-")}function ao(t){if(typeof t!="string")throw new f("Recovery code should be a string.",{code:"INVALID_PARAMETER"});let e=t.toUpperCase().replace(/[\s\-_]/g,"").replace(/O/g,"0").replace(/[IL]/g,"1");if(e.length!==Ys)throw new f(`That does not look like a recovery code: expected ${Ys} characters, got ${e.length}.`,{code:"ENCRYPTION_BAD_RECOVERY_CODE"});let r=e.slice(0,Js),n=e.slice(Js),i=0,s=0,o=[];for(let c=0;c<r.length;c++){let d=Qe.indexOf(r[c]);if(d<0)throw new f(`That does not look like a recovery code: "${r[c]}" is not a valid character.`,{code:"ENCRYPTION_BAD_RECOVERY_CODE"});i=i<<5|d,s+=5,s>=8&&(s-=8,o.push(i>>s&255));}let a=new Uint8Array(o.slice(0,Ot)),l=so(a);if(n!==Qe[l>>5&31]+Qe[l&31])throw new f("That recovery code has a typo in it: the check characters do not match.",{code:"ENCRYPTION_BAD_RECOVERY_CODE"});return a}async function Yn(t,e,r){let n=await Lt(t,e,r,32),i=await we(n);return B(n),i}var Hn=[83,75,69,78,67,70],lo=2,Ft=56,co=16,Ef=4*1024*1024;function Qn(t){if(!t||t.length<Ft)return false;for(let e=0;e<Hn.length;e++)if(t[e]!==Hn[e])return false;return true}function Xe(t,e,r){t[e]=r>>>24&255,t[e+1]=r>>>16&255,t[e+2]=r>>>8&255,t[e+3]=r&255;}function gt(t,e){return (t[e]<<24>>>0)+(t[e+1]<<16)+(t[e+2]<<8)+t[e+3]}function Af(t,e,r){let n=Math.floor(r/4294967296);Xe(t,e,n),Xe(t,e+4,r>>>0);}function Rf(t,e){return gt(t,e)*4294967296+gt(t,e+4)}async function uo(t,e,r,n,i,s){let o=W(`${ae}|binfile|${r}|${n}|${i}|${s}`),a=await Lt(t,e,o,32),l=await we(a);return B(a),l}async function fo(t){return (await kr($n(W(`${ae}|dekid`),t))).subarray(0,8)}function ho(t,e,r){return Jn([`${ae}|binchunk`,j(t),e,r])}function Sf(t,e,r,n,i,s){let o=new Uint8Array(Ft+s.length);return o.set(Hn,0),o[6]=lo,o[7]=s.length?1:0,Xe(o,8,t),Xe(o,12,e),o.set(r,16),Af(o,32,n),o.set(i,40),Xe(o,48,s.length),Xe(o,52,0),s.length&&o.set(s,Ft),o}async function po(t,e,r,n,i=Ef){let s=le(co),o=await uo(t,s,r.service,r.owner,r.recordOwner,r.recordId),a=await fo(t),l=n?W(JSON.stringify(n)):new Uint8Array(0);if(l.length>4096)throw new f("Encrypted file metadata is too large.",{code:"INVALID_PARAMETER"});let c=e.length===0?1:Math.ceil(e.length/i),d=Sf(i,c,s,e.length,a,l),h=await kr(d),u=[],g=d.length;for(let b=0;b<c;b++){let y=e.subarray(b*i,Math.min((b+1)*i,e.length)),A=await be(o,y,ho(h,b,c));u.push(A),g+=4+A.iv.length+A.ct.length;}let p=new Uint8Array(g);p.set(d,0);let m=d.length;for(let b of u)Xe(p,m,b.iv.length+b.ct.length),m+=4,p.set(b.iv,m),m+=b.iv.length,p.set(b.ct,m),m+=b.ct.length;return p}function Tf(t){if(!Qn(t))throw new f("This file is not an encrypted skapi file.",{code:"INVALID_PARAMETER"});let e=gt(t,48),r=Ft+e;if(t.length<r)throw new f("Encrypted file header is truncated.",{code:"INVALID_REQUEST"});let n=null;return e&&(n=JSON.parse(Ct(t.subarray(Ft,r)))),{version:t[6],chunkBytes:gt(t,8),count:gt(t,12),fileId:t.subarray(16,16+co),plainLen:Rf(t,32),dekId:t.subarray(40,48),meta:n,headerLen:r}}async function go(t,e,r){let n=Tf(e);if(n.version!==lo)throw new f(`This file was encrypted by a different version of the SDK (container v${n.version}).`,{code:"NOT_SUPPORTED"});if(!n.count||!n.chunkBytes)throw new f("Encrypted file header is malformed.",{code:"INVALID_PARAMETER"});let i=await fo(t);if(!wf(i,n.dekId))throw new f("This file was encrypted under a previous data key for this record, so it can no longer be opened. It was most likely left behind by an interrupted access change.",{code:"ENCRYPTION_FILE_STALE_KEY"});let s=await uo(t,n.fileId,r.service,r.owner,r.recordOwner,r.recordId),o=await kr(e.subarray(0,n.headerLen)),a=[],l=n.headerLen,c=0;for(let u=0;u<n.count;u++){if(l+4>e.length)throw new f("Encrypted file is truncated.",{code:"INVALID_REQUEST"});let g=gt(e,l);if(l+=4,g<Nt+16||l+g>e.length)throw new f("Encrypted file is truncated.",{code:"INVALID_REQUEST"});let p=await Ee(s,e.subarray(l,l+Nt),e.subarray(l+Nt,l+g),ho(o,u,n.count));l+=g,a.push(p),c+=p.length;}let d=new Uint8Array(c),h=0;for(let u of a)d.set(u,h),h+=u.length;return {bytes:d,meta:n.meta}}var vf="__skapi__keyring",qt="__skapi_enc__",yo=1,If="skapi-enc",He="keys",Zn=new WeakMap;function bo(t){if(!t)return null;if(t===true&&(t={}),typeof t!="object")throw new f('"options.encryption" should be a boolean or an object.',{code:"INVALID_PARAMETER"});let e=typeof t.iterations=="number"?t.iterations:Qs;if(e<1e5)throw new f('"encryption.iterations" must be at least 100000.',{code:"INVALID_PARAMETER"});let r=t.trustPolicy==="strict"?"strict":"tofu";return {enabled:true,iterations:e,trustPolicy:r,persistDevice:t.persistDevice!==false,minPasswordLength:typeof t.minPasswordLength=="number"?t.minPasswordLength:0,withheld:t.withheld==="sentinel"?"sentinel":"null",recovery:t.recovery==="none"?"none":"code",table:typeof t.table=="string"&&t.table?t.table:vf}}function V(){return Zn.get(this)||null}function _o(t){if(!t){Zn.delete(this);return}Zn.set(this,{cfg:t,status:"locked",reason:"NO_SESSION_KEY",user_id:"",scope:"",mk:null,ikPriv:null,pubRaw:null,fpr:"",keyringRecordId:"",pins:{},dek:new Map,roll:new Set,passthrough:new Map,rawRead:false,ready:null,unlocking:false,pendingRecoveryCode:"",peerPub:new Map,peerInflight:new Map});}function ei(){let t=V.call(this);if(t){t.user_id&&di.call(this,t).catch(()=>{}),t.ready=null,t.unlocking=false,t.pendingRecoveryCode="";for(let[,e]of t.dek)B(e.bytes);t.dek.clear(),t.roll.clear(),t.passthrough.clear(),t.peerPub.clear(),t.peerInflight.clear(),t.pins={},t.mk=null,t.ikPriv=null,t.pubRaw=null,t.fpr="",t.keyringRecordId="",t.user_id="",t.status="locked",t.reason="NO_SESSION_KEY";}}function wo(){let t=V.call(this);return t?{status:t.status,reason:t.status==="unlocked"?void 0:t.reason,user_id:t.user_id||void 0,fingerprint:t.fpr||void 0}:{status:"disabled"}}function Eo(t,e){return typeof e=="string"&&e===t.cfg.table}function yt(){return `${this.service}/${this.owner}`}function ti(t,e,r,n){let[i,s]=t.split("/");return Jn([ae,i,s,e,r,n])}function Ao(t,e,r,n,i){let[s,o]=t.split("/");return W(`${ae}|dekwrap|${s}|${o}|${e}|${r}|${n}|${i}`)}function ri(t){return t.anch==="uid"?t.uid:t.anch==="rid"?t.rid:""}function Cr(t){return !!t&&typeof t=="object"&&!Array.isArray(t)&&typeof t[qt]=="number"&&typeof t.ct=="string"&&typeof t.iv=="string"&&typeof t.own=="string"&&typeof t.anch=="string"&&!!t.k&&typeof t.k=="object"&&!Array.isArray(t.k)}var Ro="__skapi_no_access__";function ue(t,e,r){if(t.withheld!=="sentinel")return null;let n={[Ro]:true,reason:e};return r&&(n.recipients=r),Object.freeze(n)}function ni(t){return !!t&&typeof t=="object"&&t[Ro]===true}var Pf=256*1024,jt="__skenc_ct__",So="payload.bin",kf=`/${jt}/${So}`;function ii(t,e){return t===jt&&e===So}async function xf(t,e,r){let n=e?.table,i=typeof n=="string"?n:n?.name;if(n&&(typeof n=="string"||n.access_group!==void 0))return {group:typeof n=="string"?0:mo(n.access_group),table:i,record:null};if(!r)return {group:n?.access_group!==void 0?mo(n.access_group):0,table:i,record:null};let s=t.dek.get(r);if(s)return {group:s.access_group,table:i,record:null};let o=await $e.call(this,r);if(!o)throw new f(`Record "${r}" not found.`,{code:"NOT_EXISTS"});return {group:o.table.access_group,table:o.table.name,record:o}}function Uf(t){return this.getFile(t,{dataType:"blob"})}async function $e(t){let e=/^[a-zA-Z0-9]+$/.test(t)?{record_id:t}:{unique_id:t};return (await this.getRecords(e,{limit:1}))?.list?.[0]||null}function mo(t){return t==="private"||t==="*"||t==="**"?"private":t==="public"?0:t==="authorized"?1:t==="admin"?99:typeof t=="number"?t:0}function Xn(t,e,r){let n=this.user?.user_id;if(!(!t||!t.user_id||!n||t.user_id===n))throw new f(`Record "${e}" belongs to another user (${t.user_id}), so ${r} would either seal it under the wrong key or strand its contents. Encryption only operates on records you own, no matter what access level you hold.`,{code:"ENCRYPTION_NOT_RECORD_OWNER"})}async function si(t,e,r){let n=V.call(this);if(!n)return {send:t,plain:t,encrypted:false,omit:false};let i=e?.record_id||"",s=i,o=e?.unique_id||"";if(i&&n.passthrough.has(i)){let q=n.passthrough.get(i);return n.passthrough.delete(i),{send:q,plain:t,encrypted:true,omit:false}}let{group:a,table:l,record:c}=await xf.call(this,n,e,s);if(a!=="private"){let q=true;if(!r&&i){let re=c||await $e.call(this,i);if(re&&re.encrypted){if(Xn.call(this,re,i,"making it non-private"),re.encrypted.status==="failed")throw new f(`Cannot make record "${i}" non-private: its current contents could not be decrypted (${re.encrypted.reason}), so they cannot be written back in the clear. Unlock encryption, or supply the record's data with the access group change.`,{code:"ENCRYPTION_LOCKED"});let Pt=!!re.bin&&Object.keys(re.bin).some(rr=>(re.bin[rr]||[]).some(Bi=>Bi&&Bi.encrypted));if(!Pt&&s){let rr=n.dek.get(s);rr&&(B(rr.bytes),n.dek.delete(s));}return {send:re.data,plain:re.data,encrypted:false,omit:false,files:Pt?"decrypt":void 0}}}let X=c;i&&!X&&(X=await $e.call(this,i).catch(()=>null)),X&&X.encrypted&&Xn.call(this,X,i,"making it non-private");let tr=!!X&&!!X.bin&&Object.keys(X.bin).some(re=>(X.bin[re]||[]).some(Pt=>Pt&&Pt.encrypted));if(tr&&(q=false),q&&s){let re=n.dek.get(s);re&&(B(re.bytes),n.dek.delete(s));}return {send:t,plain:t,encrypted:false,omit:!r,files:tr?"decrypt":void 0}}if(Eo(n,l))return {send:t,plain:t,encrypted:false,omit:false};if(n.ready&&!n.unlocking)try{await n.ready;}catch{}if(!r)return {send:t,plain:t,encrypted:false,omit:true};if(ni.call(this,t))throw new f("This record's data could not be decrypted by this session, so it cannot be written back. Writing it would replace the record with the placeholder.",{code:"ENCRYPTION_CANNOT_REWRITE_WITHHELD"});if(n.status!=="unlocked"||!n.mk)throw new f("Encryption is enabled but locked, so this private record cannot be written. Call unlockEncryption({ password }) first, or the user must log in with their password.",{code:"ENCRYPTION_LOCKED"});if(t&&typeof t=="object"&&!Array.isArray(t)&&Object.prototype.hasOwnProperty.call(t,qt))throw new f(`"${qt}" is a reserved key in record data.`,{code:"INVALID_PARAMETER"});if(e?.service&&e.service!==this.service||e?.owner&&e.owner!==this.owner)throw new f("Encrypted records cannot be written to another project. The encryption key is derived per project, so a record written under one service and read under another could never be decrypted. Construct a separate Skapi instance for that project.",{code:"INVALID_REQUEST"});let d=this.user?.user_id;if(!d)throw new f("User login is required to write an encrypted record.",{code:"INVALID_REQUEST"});let h=yt.call(this),u=false;if(i&&n.roll.has(i)){u=true,n.roll.delete(i);let q=n.dek.get(i);n.dek.delete(i),q&&B(q.bytes);}let g=c;i&&!g&&!n.dek.has(i)&&(g=await $e.call(this,i).catch(()=>null)),g&&Xn.call(this,g,i,"making it private");let p=!!g&&!g.encrypted&&!!g.bin&&Object.keys(g.bin).some(q=>(g.bin[q]||[]).some(X=>X&&!X.encrypted)),m=null;if(i&&!u&&(m=n.dek.get(i)||null,!m)){let q=g||c||await $e.call(this,i);if(q&&(s=q.record_id||i,m=n.dek.get(s)||null,!o&&q.unique_id&&(o=q.unique_id),!m&&q.encrypted?.status==="failed"))throw new f(`Cannot update encrypted record "${i}": its current contents could not be decrypted (${q.encrypted.reason}), so its existing key wraps cannot be preserved. Updating anyway would revoke everyone it is shared with.`,{code:"ENCRYPTION_LOCKED"})}s===i&&m&&m.rid&&(s=m.rid),!o&&m&&m.anch==="uid"&&m.uid&&(o=m.uid);let b,y,A;if(m){if(m.own&&m.own!==d)throw new f(`Record "${i}" belongs to another user (${m.own}). Encryption only operates on records you own.`,{code:"ENCRYPTION_NOT_RECORD_OWNER"});b=m.bytes,y=m.key,A=Object.assign({},m.recipients);}else {let q=await eo();b=q.bytes,y=q.key,A={};}let w=o?"uid":s?"rid":"new",S=w==="uid"?o:w==="rid"?s:"",R=ti(h,d,w,S),U=Mt(R,d,"mk"),O=await be(n.mk,b,U);A[d]={t:"mk",iv:j(O.iv),ct:j(O.ct)},m&&(m.anch!==w||ri(m)!==S)&&(A=await Cf.call(this,n,b,A,h,d,w,S,R));let C=W(JSON.stringify(t===void 0?null:t)),I=await be(y,C,R);B(C);let D={[qt]:yo,enc:"A256GCM",kw:"ECDH-ES+A256GCM",anch:w,uid:o,rid:s,own:d,iv:j(I.iv),ct:j(I.ct),k:A},N,M,te=D.ct;s&&te.length>Pf&&(N=$(te),D.ct="",D.ct_ref=kf,m&&m.ctRef&&(M=m.ctRef));let ie=JSON.stringify(D).length;if(ie>2*1024*1024)throw new f(`Encrypted record data is too large: once encrypted and base64 encoded it becomes ${ie} bytes, over the ${2*1024*1024} byte limit. Encryption costs about 33% plus roughly 230 bytes per additional recipient.`,{code:"ENCRYPTED_DATA_TOO_LARGE"});return s&&n.dek.set(s,{bytes:b,key:y,recipients:A,anch:w,uid:o,rid:s,own:d,access_group:"private"}),{send:D,plain:t,encrypted:true,omit:false,spill:N,retireCt:M,dek:{bytes:b,key:y,recipients:A,anch:w,uid:o,rid:s,own:d,access_group:"private"},files:p?"encrypt":void 0}}function To(t,e){let r=V.call(this);!r||!e||!t||r.dek.has(t)||r.dek.set(t,Object.assign({},e,{rid:t}));}async function Cf(t,e,r,n,i,s,o,a){let l=Object.keys(r).filter(h=>h!==i);if(!l.length)return r;let c=await fi.call(this,l),d={[i]:r[i]};for(let h of l){let u=c[h];u&&(d[h]=await vo.call(this,e,u,n,o,i,h,a));}return d}async function vo(t,e,r,n,i,s,o){let a=Ao(r,n,i,s,e.fpr),l=Mt(o,s,e.fpr),c=await no(e.pubRaw,t,a,l);return {t:"ecdh",epk:j(c.epk),iv:j(c.iv),ct:j(c.ct),fpr:e.fpr}}async function Io(t,e){if(!Cr(t))return {value:t};if(e.access_group!=="private")return {value:t};let r=V.call(this);if(!r)return {value:null,flag:{status:"failed",reason:"ENCRYPTION_DISABLED"}};if(r.rawRead)return {value:t};if(Eo(r,e.table_name))return {value:t};if(t[qt]!==yo)return {value:ue(r.cfg,"UNSUPPORTED_VERSION"),flag:{status:"failed",reason:"UNSUPPORTED_VERSION"}};if(r.ready&&!r.unlocking)try{await r.ready;}catch{}if(t.own!==e.user_id)return {value:ue(r.cfg,"BINDING_MISMATCH"),flag:{status:"failed",reason:"BINDING_MISMATCH"}};if(t.uid&&e.unique_id&&t.uid!==e.unique_id)return {value:ue(r.cfg,"BINDING_MISMATCH"),flag:{status:"failed",reason:"BINDING_MISMATCH"}};if(t.rid&&e.record_id&&t.rid!==e.record_id)return {value:ue(r.cfg,"BINDING_MISMATCH"),flag:{status:"failed",reason:"BINDING_MISMATCH"}};let n=this.user?.user_id,i=n?t.k[n]:null;if(!i)return {value:ue(r.cfg,"NOT_A_RECIPIENT",Object.keys(t.k)),flag:{status:"failed",reason:"NOT_A_RECIPIENT",recipients:Object.keys(t.k)}};if(r.status!=="unlocked"||!r.mk)return {value:ue(r.cfg,"NO_SESSION_KEY"),flag:{status:"failed",reason:"NO_SESSION_KEY"}};let s=yt.call(this),o=ri(t),a=ti(s,t.own,t.anch,o),l;try{if(i.t==="mk")l=await Ee(r.mk,$(i.iv),$(i.ct),Mt(a,n,"mk"));else if(i.t==="ecdh"){if(!r.ikPriv)return {value:ue(r.cfg,"NO_SESSION_KEY"),flag:{status:"failed",reason:"NO_SESSION_KEY"}};l=await io(r.ikPriv,$(i.epk),$(i.iv),$(i.ct),Ao(s,o,t.own,n,i.fpr),Mt(a,n,i.fpr));}else return {value:ue(r.cfg,"UNSUPPORTED_VERSION"),flag:{status:"failed",reason:"UNSUPPORTED_VERSION"}}}catch{return {value:ue(r.cfg,"BAD_KEY"),flag:{status:"failed",reason:"BAD_KEY"}}}let c;try{if(t.ct_ref){if(!e.ctUrl)return B(l),{value:ue(r.cfg,"DATA_UNAVAILABLE"),flag:{status:"failed",reason:"DATA_UNAVAILABLE"}};let g=await Uf.call(this,e.ctUrl);c=new Uint8Array(await g.arrayBuffer());}else c=$(t.ct);}catch{return B(l),{value:ue(r.cfg,"DATA_UNAVAILABLE"),flag:{status:"failed",reason:"DATA_UNAVAILABLE"}}}let d,h;try{h=await we(l),d=await Ee(h,$(t.iv),c,a);}catch{return B(l),{value:ue(r.cfg,"CORRUPT"),flag:{status:"failed",reason:"CORRUPT"}}}let u;try{u=JSON.parse(Ct(d));}catch{return B(d),B(l),{value:ue(r.cfg,"CORRUPT"),flag:{status:"failed",reason:"CORRUPT"}}}if(B(d),e.record_id){let g=r.dek.get(e.record_id);g?(g.bytes=l,g.key=h,g.recipients=t.k,g.anch=t.anch,g.uid=t.uid,g.own=t.own,g.access_group="private",g.ctRef=t.ct_ref||""):r.dek.set(e.record_id,{bytes:l,key:h,recipients:t.k,anch:t.anch,uid:t.uid,rid:e.record_id,own:t.own,access_group:"private",ctRef:t.ct_ref||""});}else B(l);return {value:u,flag:{status:"encrypted",recipients:Object.keys(t.k)}}}function Vt(t,e){let[r,n]=t.split("/");return W(`${ae}|kek|${r}|${n}|${e}`)}function Bt(t,e,r,n){let[i,s]=t.split("/");return W(`${ae}|mk|${i}|${s}|${e}|PBKDF2-SHA256|${r}|${n}`)}function Po(t,e){let[r,n]=t.split("/");return W(`${ae}|recovery|${r}|${n}|${e}`)}function ko(t,e,r){let[n,i]=t.split("/");return W(`${ae}|rk|${n}|${i}|${e}|HKDF-SHA256|${r}`)}function xo(t,e){let[r,n]=t.split("/");return W(`${ae}|self|${r}|${n}|${e}`)}function Uo(t,e){let[r,n]=t.split("/");return W(`${ae}|ik|${r}|${n}|${e}`)}async function Dr(t){let r=((await this.getRecords({table:{name:t.cfg.table,access_group:"private"},index:{name:"$user_id",value:this.user.user_id,condition:"="}},{limit:2}))?.list||[]).filter(n=>n.user_id===this.user.user_id);return r.length?(r.sort((n,i)=>n.uploaded-i.uploaded),r[0]):null}async function oi(t,e,r){let n=le(Ot),i=oo(n),s=le(16),o=j(s),a=await Yn(n,s,Po(t,e)),l=await be(a,r,ko(t,e,o));return B(n),{code:i,wrap:{id:j(le(6)),p:"recovery",kdf:{a:"HKDF-SHA256",s:o},iv:j(l.iv),ct:j(l.ct),created:Date.now()}}}async function Df(t,e,r,n){let i=ao(n),s=(r||[]).filter(o=>o.p==="recovery");s.sort((o,a)=>(a.created||0)-(o.created||0));for(let o of s)try{let a=await Yn(i,$(o.kdf.s),Po(t,e)),l=await Ee(a,$(o.iv),$(o.ct),ko(t,e,o.kdf.s));return B(i),l}catch{}return B(i),null}async function Nf(t,e,r,n,i){let s=le(16),o=j(s),a=await mt(n,s,t.cfg.iterations,Vt(e,r)),l=await be(a,i,Bt(e,r,t.cfg.iterations,o));return {id:j(le(6)),p:"password",kdf:{a:"PBKDF2-SHA256",it:t.cfg.iterations,s:o},iv:j(l.iv),ct:j(l.ct),created:Date.now()}}async function Of(t,e){let r=this.user.user_id,n=t.scope,i=le(16),s=j(i),o=await mt(e,i,t.cfg.iterations,Vt(n,r)),a=le(32),l=await be(o,a,Bt(n,r,t.cfg.iterations,s)),c=await we(a),d=await to(),h=await be(c,d.pkcs8,Uo(n,r));B(d.pkcs8);let u=null;t.cfg.recovery==="code"&&(u=await oi(n,r,a));let g=await be(c,a,xo(n,r));B(a);let p=await zn(d.pubRaw),m=Date.now(),b=[{id:j(le(6)),p:"password",kdf:{a:"PBKDF2-SHA256",it:t.cfg.iterations,s},iv:j(l.iv),ct:j(l.ct),created:m}];u&&b.push(u.wrap);let y={v:1,alg:"ECDH-P-256",user_id:r,wraps:b,ik:{iv:j(h.iv),ct:j(h.ct)},self:{iv:j(g.iv),ct:j(g.ct)},pub:j(d.pubRaw),fpr:p,pins:null,created:m,updated:m};await this.postRecord({v:1,alg:"ECDH-P-256",user_id:r,pub:j(d.pubRaw),fpr:p,created:m},{table:{name:t.cfg.table,access_group:"authorized"},index:{name:"pubkey",value:r}});let A=await this.postRecord(y,{table:{name:t.cfg.table,access_group:"private"}}),w=await Dr.call(this,t);if(w&&w.record_id!==A.record_id){await Co.call(this,t,w,e);return}t.mk=c,t.ikPriv=d.priv,t.pubRaw=d.pubRaw,t.fpr=p,t.keyringRecordId=A.record_id,u&&(t.pendingRecoveryCode=u.code),t.user_id=r,t.pins={},t.status="unlocked",t.reason="";}async function Co(t,e,r){let n=this.user.user_id,i=t.scope,s=e.data;if(e.user_id!==n||s&&s.user_id&&s.user_id!==n)throw new f("The encryption keyring does not belong to this user.",{code:"ENCRYPTION_KEYRING_CORRUPT"});let a=(Array.isArray(s?.wraps)?s.wraps:[]).filter(d=>d.p==="password");if(!a.length)throw new f("The keyring has no password wrap.",{code:"ENCRYPTION_KEYRING_CORRUPT"});a.sort((d,h)=>(h.created||0)-(d.created||0));let l=null;for(let d of a)try{let h=$(d.kdf.s),u=await mt(r,h,d.kdf.it,Vt(i,n));l=await Ee(u,$(d.iv),$(d.ct),Bt(i,n,d.kdf.it,d.kdf.s));break}catch{}if(!l)throw new f("Incorrect password: the encryption keyring could not be opened.",{code:"ENCRYPTION_BAD_PASSWORD"});let c=await we(l);B(l),await ai.call(this,t,e,c);}async function ai(t,e,r){let n=this.user.user_id,i=e.data,s=await Ee(r,$(i.ik.iv),$(i.ik.ct),Uo(t.scope,n)),o=await Wn(s);B(s);let a={};if(i.pins&&typeof i.pins=="object"&&i.pins.ct)try{let l=await Ee(r,$(i.pins.iv),$(i.pins.ct),W(`${ae}|pins|${t.scope}|${n}`));a=JSON.parse(Ct(l)),B(l);}catch{a={};}t.mk=r,t.ikPriv=o,t.pubRaw=$(i.pub),t.fpr=i.fpr,t.keyringRecordId=e.record_id,t.user_id=n,t.pins=a,t.status="unlocked",t.reason="";}async function Nr(t){let e=V.call(this);if(!e||!this.user?.user_id)return;if(!Gn()){e.status="locked",e.reason="NO_WEB_CRYPTO";return}if(this.user?.is_openid){e.status="locked",e.reason="OPENID_UNSUPPORTED";return}if(e.cfg.minPasswordLength&&t.length<e.cfg.minPasswordLength){e.status="locked",e.reason="WEAK_PASSWORD";return}e.scope=yt.call(this);let r=await Dr.call(this,e);r?await Co.call(this,e,r,t):await Of.call(this,e,t),e.cfg.persistDevice&&await Lo.call(this,e).catch(()=>{});}async function Do(t){await this.__connection;let e=V.call(this);if(!e)throw new f("Encryption is not enabled for this instance.",{code:"INVALID_REQUEST"});if(!this.user?.user_id)throw new f("User login is required.",{code:"INVALID_REQUEST"});if(!t?.password||typeof t.password!="string")throw new f('"password" is required.',{code:"INVALID_PARAMETER"});if(await Nr.call(this,t.password),e.status!=="unlocked")throw new f(`Encryption could not be unlocked: ${e.reason}`,{code:"ENCRYPTION_LOCKED"});return {status:e.status}}async function No(t){this.__projectIdInput&&await this.__projectIdInput;let e=V.call(this);return e?(t?.forgetDevice&&await di.call(this,e).catch(()=>{}),ei.call(this),this.__cached_requests={},{status:e.status}):{status:"disabled"}}async function Oo(t,e){let r=V.call(this);if(!r)return;if(r.status!=="unlocked"||!r.mk)throw new f("Encryption must be unlocked before changing the password, or the encryption keyring would be left wrapped under a password that no longer exists. Call unlockEncryption({ password }) first.",{code:"ENCRYPTION_LOCKED"});let i=(await this.getRecords({record_id:r.keyringRecordId},{limit:1}))?.list?.[0];if(!i)throw new f("The encryption keyring could not be read, so the password change was stopped before it could strand it.",{code:"ENCRYPTION_KEYRING_CORRUPT"});let s=this.user.user_id,o=i.data,a=(o.wraps||[]).filter(m=>m.p==="password");a.sort((m,b)=>(b.created||0)-(m.created||0));let l=null;for(let m of a)try{let b=await mt(t,$(m.kdf.s),m.kdf.it,Vt(r.scope,s));l=await Ee(b,$(m.iv),$(m.ct),Bt(r.scope,s,m.kdf.it,m.kdf.s));break}catch{}if(!l)throw new f("Incorrect current password: the encryption keyring was not re-wrapped.",{code:"ENCRYPTION_BAD_PASSWORD"});let c=le(16),d=j(c),h=await mt(e,c,r.cfg.iterations,Vt(r.scope,s)),u=await be(h,l,Bt(r.scope,s,r.cfg.iterations,d));B(l);let g=Date.now(),p=(o.wraps||[]).concat([{id:j(le(6)),p:"password",kdf:{a:"PBKDF2-SHA256",it:r.cfg.iterations,s:d},iv:j(u.iv),ct:j(u.ct),created:g}]);await this.postRecord(Object.assign({},o,{wraps:p,updated:g}),{record_id:r.keyringRecordId});}async function Fo(){let t=V.call(this);if(!t||t.status!=="unlocked"||!t.keyringRecordId)return;let r=(await this.getRecords({record_id:t.keyringRecordId},{limit:1}))?.list?.[0];if(!r)return;let n=r.data,i=(n.wraps||[]).filter(o=>o.p==="password").sort((o,a)=>(a.created||0)-(o.created||0)),s=(n.wraps||[]).filter(o=>o.p!=="password");i.length<=1||await this.postRecord(Object.assign({},n,{wraps:[i[0]].concat(s),updated:Date.now()}),{record_id:t.keyringRecordId});}function li(){return typeof indexedDB<"u"&&!!indexedDB}function ci(){return new Promise((t,e)=>{let r=indexedDB.open(If,1);r.onupgradeneeded=()=>{let n=r.result;n.objectStoreNames.contains(He)||n.createObjectStore(He);},r.onsuccess=()=>t(r.result),r.onerror=()=>e(r.error);})}function ui(t){return `${t.scope}#${this.user?.user_id}`}async function Lo(t){if(!li()||!t.mk)return;let e=await ci();await new Promise((r,n)=>{let i=e.transaction(He,"readwrite");i.objectStore(He).put({mk:t.mk,keyringRecordId:t.keyringRecordId,saved:Date.now()},ui.call(this,t)),i.oncomplete=()=>r(),i.onerror=()=>n(i.error);}),e.close();}async function Ff(t){if(!li())return null;let e=await ci(),r=await new Promise((n,i)=>{let o=e.transaction(He,"readonly").objectStore(He).get(ui.call(this,t));o.onsuccess=()=>n(o.result||null),o.onerror=()=>i(o.error);});return e.close(),r&&r.mk?r:null}async function di(t){if(!li())return;let e=await ci();await new Promise((r,n)=>{let i=e.transaction(He,"readwrite");i.objectStore(He).delete(ui.call(this,t)),i.oncomplete=()=>r(),i.onerror=()=>n(i.error);}),e.close();}function Mo(){let t=V.call(this);!t||t.ready||(t.unlocking=true,t.ready=Lf.bind(this)().catch(()=>false).then(()=>{t.unlocking=false;}));}async function Lf(){let t=V.call(this);if(!t||!this.user?.user_id||!t.cfg.persistDevice||!Gn())return false;t.scope=yt.call(this);try{let e=await Ff.call(this,t);if(!e)return !1;let r=await Dr.call(this,t);return r?(await ai.call(this,t,r,e.mk),!0):(await di.call(this,t).catch(()=>{}),!1)}catch{return t.status="locked",t.reason="NO_SESSION_KEY",false}}async function fi(t){let e=V.call(this);if(!e)throw new f("Encryption is not enabled for this instance.",{code:"INVALID_REQUEST"});let r={},n=[],i=false;for(let s of t){let o=e.peerPub.get(s);o?r[s]=o:n.push(s);}return await Promise.all(n.map(async s=>{let o=e.peerInflight.get(s);o||(o=(async()=>{let c=((await this.getRecords({table:{name:e.cfg.table,access_group:"authorized"},index:{name:"$user_id",value:s,condition:"="}},{limit:10}))?.list||[]).filter(g=>g.user_id===s&&g.data?.pub);if(!c.length)return null;c.sort((g,p)=>p.uploaded-g.uploaded);let d=$(c[0].data.pub),h=await zn(d),u=e.pins[s];if(u&&u!==h)throw new f(`The public key for user "${s}" has changed since it was first seen. This is expected if they reset their account, and is what a key substitution attack also looks like. Verify the new fingerprint out of band, then call pinPeerKey({ user_id, fingerprint }).`,{code:"ENCRYPTION_PEER_KEY_CHANGED"});if(!u){if(e.cfg.trustPolicy==="strict")throw new f(`No pinned key for user "${s}" and trustPolicy is "strict". Pin it first with pinPeerKey().`,{code:"ENCRYPTION_PEER_NOT_PINNED"});e.pins[s]=h,i=true;}return {pubRaw:d,fpr:h}})().finally(()=>e.peerInflight.delete(s)),e.peerInflight.set(s,o));let a=await o;a&&e.peerPub.set(s,a),r[s]=a;})),i&&await jo.call(this,e).catch(()=>{}),r}async function qo(t,e){let r=yt.call(this),n=t.dek.get(e);if(n)return {entry:n,scope:r};let i=await $e.call(this,e);if(!i)throw new f(`Record "${e}" not found.`,{code:"NOT_EXISTS"});if(i.encrypted?.status==="failed"&&i.encrypted.reason==="DATA_UNAVAILABLE")throw new f(`Cannot change sharing on record "${e}": its data could not be read, so whether it is encrypted is unknown. Retry once the record reads normally.`,{code:"ENCRYPTION_DATA_UNAVAILABLE"});if(!i.encrypted)return null;if(i.user_id!==this.user?.user_id)throw new f("Only the record owner can share or revoke an encrypted record, because adding or removing a key wrap means writing the record.",{code:"ENCRYPTION_GRANT_REQUIRES_OWNER"});let s=t.dek.get(i.record_id)||t.dek.get(e);if(!s)throw new f(`Cannot change sharing on record "${e}": its data could not be decrypted`+(i.encrypted.reason?` (${i.encrypted.reason})`:"")+".",{code:"ENCRYPTION_LOCKED"});return {entry:s,scope:r}}async function hi(t,e){let r=V.call(this);if(!r)return;let n=await qo.call(this,r,t);if(!n)return;let{entry:i,scope:s}=n,o=this.user.user_id;if(i.own!==o)throw new f("Only the record owner can share an encrypted record, because adding a key wrap means writing the record.",{code:"ENCRYPTION_GRANT_REQUIRES_OWNER"});let a=await fi.call(this,e),l=e.filter(u=>!a[u]);if(l.length)throw new f(`These users have no encryption key yet, so they cannot be given access: ${l.join(", ")}. A user's key is created the first time they log in with encryption enabled.`,{code:"ENCRYPTION_RECIPIENT_HAS_NO_KEY"});let c=ri(i),d=ti(s,i.own,i.anch,c),h=Object.assign({},i.recipients);for(let u of e)u!==o&&(h[u]=await vo.call(this,i.bytes,a[u],s,c,i.own,u,d));await qf.call(this,r,t,i,h);}async function Vo(t,e){let r=V.call(this);if(!r)return;let n=await qo.call(this,r,t);if(!n)return;let{entry:i}=n,s=this.user.user_id;if(i.own!==s)throw new f("Only the record owner can revoke access to an encrypted record.",{code:"ENCRYPTION_GRANT_REQUIRES_OWNER"});let o=Object.keys(i.recipients).filter(c=>c===s?true:e?!e.includes(c):false).filter(c=>c!==s),a=await $e.call(this,t);if(!a)throw new f(`Record "${t}" not found.`,{code:"NOT_EXISTS"});Mf(a,t);let l={};if(o.length){l=await fi.call(this,o);let c=o.filter(d=>!l[d]);if(c.length)throw new f(`Cannot revoke on record "${t}": these users keep access but their encryption keys could not be read, so re-sharing after the key roll would fail and lock them out: ${c.join(", ")}.`,{code:"ENCRYPTION_RECIPIENT_HAS_NO_KEY"})}r.roll.add(a.record_id||t),await this.postRecord(a.data,{record_id:a.record_id||t,table:{name:a.table.name,access_group:"private"}}),o.length&&await hi.call(this,a.record_id||t,o);}function Mf(t,e){if(t?.encrypted?.status==="failed")throw new f(`Cannot change sharing on record "${e}": its current data could not be read (${t.encrypted.reason}), so re-writing the record would destroy it.`,{code:"ENCRYPTION_DATA_UNAVAILABLE"})}async function qf(t,e,r,n){let i=await Vf.call(this,e);if(!i)throw new f(`Cannot change sharing on record "${e}": its stored envelope could not be read.`,{code:"ENCRYPTION_DATA_UNAVAILABLE"});r.recipients=n,t.dek.set(e,r);let s=Object.assign({},i,{k:n});t.passthrough.set(e,s),await this.postRecord(void 0,{record_id:e});}async function Vf(t){let e=V.call(this);if(!e)return null;e.rawRead=true;let r;try{r=(await this.getRecords({record_id:t},{limit:1}))?.list?.[0];}finally{e.rawRead=false;}return r&&Cr(r.data)?r.data:null}async function Bo(t){this.__projectIdInput&&await this.__projectIdInput;let e=V.call(this);if(!e||e.status!=="unlocked")throw new f("Encryption is locked.",{code:"ENCRYPTION_LOCKED"});e.pins[t.user_id]=t.fingerprint,e.peerPub.delete(t.user_id),await jo.call(this,e);}async function jo(t){if(!t.mk||!t.keyringRecordId)return;let r=(await this.getRecords({record_id:t.keyringRecordId},{limit:1}))?.list?.[0];if(!r)return;let n=await be(t.mk,W(JSON.stringify(t.pins)),W(`${ae}|pins|${t.scope}|${t.user_id}`));await this.postRecord(Object.assign({},r.data,{pins:{iv:j(n.iv),ct:j(n.ct)},updated:Date.now()}),{record_id:t.keyringRecordId});}function Ko(){let t=V.call(this);if(!t||!t.pendingRecoveryCode)return null;let e=t.pendingRecoveryCode;return t.pendingRecoveryCode="",e}async function $o(t){await this.__connection;let e=V.call(this);if(!e)throw new f("Encryption is not enabled for this instance.",{code:"INVALID_REQUEST"});if(!this.user?.user_id)throw new f("User login is required. Reset the password and log in first, then use the recovery code.",{code:"INVALID_REQUEST"});if(!t?.code||typeof t.code!="string")throw new f('"code" is required.',{code:"INVALID_PARAMETER"});e.scope=yt.call(this);let r=this.user.user_id,n=await Dr.call(this,e);if(!n)throw new f("This account has no encryption keyring, so there is nothing to recover.",{code:"NOT_EXISTS"});let i=await Df(e.scope,r,n.data?.wraps||[],t.code);if(!i)throw new f("That recovery code did not open the keyring. Check it against the copy you saved when encryption was set up.",{code:"ENCRYPTION_BAD_RECOVERY_CODE"});let s=await we(i);await ai.call(this,e,n,s);let o=false,a=null,l=(n.data?.wraps||[]).slice();if(t.password&&(l=l.filter(c=>c.p!=="password"),l.push(await Nf(e,e.scope,r,t.password,i)),o=true),e.cfg.recovery==="code"){let c=await oi(e.scope,r,i);l=l.filter(d=>d.p!=="recovery"),l.push(c.wrap),a=c.code;}return B(i),await this.postRecord(Object.assign({},n.data,{wraps:l,updated:Date.now()}),{record_id:n.record_id}),e.cfg.persistDevice&&await Lo.call(this,e).catch(()=>{}),{status:e.status,repaired:o,recoveryCode:a}}async function Ho(){await this.__connection;let t=V.call(this);if(!t)throw new f("Encryption is not enabled for this instance.",{code:"INVALID_REQUEST"});if(t.status!=="unlocked"||!t.mk)throw new f("Encryption must be unlocked to issue a recovery code. Only someone who can already decrypt can create one.",{code:"ENCRYPTION_LOCKED"});if(t.cfg.recovery!=="code")throw new f('Recovery codes are disabled for this instance ("recovery" is "none").',{code:"INVALID_REQUEST"});let r=(await this.getRecords({record_id:t.keyringRecordId},{limit:1}))?.list?.[0];if(!r)throw new f("The encryption keyring could not be read.",{code:"ENCRYPTION_KEYRING_CORRUPT"});let n=r.data?.self;if(!n||!n.ct)throw new f("This keyring predates recovery-code rotation and cannot issue a new code. Use unlockWithRecoveryCode() with the existing code, which issues a replacement.",{code:"ENCRYPTION_KEYRING_CORRUPT"});let i=await Ee(t.mk,$(n.iv),$(n.ct),xo(t.scope,t.user_id)),s=await oi(t.scope,t.user_id,i);B(i);let o=(r.data.wraps||[]).filter(a=>a.p!=="recovery").concat([s.wrap]);return await this.postRecord(Object.assign({},r.data,{wraps:o,updated:Date.now()}),{record_id:t.keyringRecordId}),{recoveryCode:s.code}}var Ur="__skenc__",Go="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function Bf(t){if(t===0)return "0";let e="";for(;t>0;)e=Go[t%62]+e,t=Math.floor(t/62);return e}function jf(t){let e=0;for(let r of t){let n=Go.indexOf(r);if(n<0)return NaN;e=e*62+n;}return e}function Or(t){if(typeof t!="string")return null;let e=t.lastIndexOf(Ur);if(e<0)return null;let r=jf(t.slice(e+Ur.length));return Number.isFinite(r)?{key:t.slice(0,e),plainSize:r}:null}function pi(t){try{let e=String(t).split("?")[0].split("/").slice(3);if(e.length<12||e[4]!=="records"||e[7]!=="bin")return null;let r=Or(e[10]);return r?{recordId:e[5],recordOwner:e[3],filename:e[e.length-1],plainSize:r.plainSize}:null}catch{return null}}function Wo(t,e){return {service:this.service,owner:this.owner,recordOwner:e,recordId:t}}async function zo(t,e,r){let n=V.call(this);if(!n||!t)return {key:e,file:r,encrypted:false};let i=n.dek.get(t);if(!i)return {key:e,file:r,encrypted:false};if(Or(e))throw new f(`"${Ur}" is reserved in an upload form key.`,{code:"INVALID_PARAMETER"});if(e===jt)return {key:e,file:r,encrypted:false};let s=new Uint8Array(await r.arrayBuffer()),o={n:r.name,t:r.type||"",lm:r.lastModified||0},a=await po(i.bytes,s,Wo.call(this,t,i.own),o);return B(s),{key:`${e}${Ur}${Bf(r.size)}`,file:new File([a],r.name,{type:"application/octet-stream"}),encrypted:true}}async function Jo(t,e){let r=V.call(this),n=pi(t);if(!r||!n)return e;let i=r.dek.get(n.recordId);if(!i)throw new f(`Cannot open this file: the data key for record "${n.recordId}" is not available. Read the record first, and make sure encryption is unlocked.`,{code:"ENCRYPTION_LOCKED"});let s=new Uint8Array(await e.arrayBuffer());if(!Qn(s))throw new f("This file is marked as encrypted but its contents are not an encrypted container.",{code:"ENCRYPTION_FILE_CORRUPT"});let o=await go(i.bytes,s,Wo.call(this,n.recordId,n.recordOwner)),a=o.meta&&o.meta.t||"application/octet-stream";return new Blob([o.bytes],{type:a})}function Kf(t){let e=[];for(let r in t?.bin||{})for(let n of t.bin[r]||[])n&&n.encrypted&&e.push({formKey:r,url:n.url,filename:n.filename});return e}function $f(t){let e=[];for(let r in t?.bin||{})for(let n of t.bin[r]||[])n&&!n.encrypted&&e.push({formKey:r,url:n.url,filename:n.filename});return e}async function gi(t,e,r){let n=V.call(this);if(!n)return [];let i=await $e.call(this,t);if(!i)return [];let s=e==="decrypt"?Kf(i):$f(i);if(!s.length)return [];let o=[],a=new FormData,l=false;for(let c of s){let d=i.bin[c.formKey].find(u=>u.url===c.url);if(!d||typeof d.getFile!="function")continue;let h=await d.getFile("blob");h&&(a.append(c.formKey,new File([h],c.filename,{type:h.type||"application/octet-stream"})),o.push(c.url),l=true);}if(!l)return [];if(e==="decrypt"){let c=n.dek.get(t);c&&(B(c.bytes),n.dek.delete(t));}return await this.uploadFiles(a,{record_id:t,progress:r}),o}var H=null;function Lr(t){let e={tkid:"ticket_id",cond:"condition",stmp:"timestamp",upd:"updated",acts:"actions",actn:"action",cnt:"count",ttl:"time_to_live",plch:"placeholder",hash:"hash",desc:"description",pmc:"limit_per_user",fail:"failed",rv:"rules_version"},r={};for(let n in t)if(n==="tkid"){let i=t[n].split("#");if(i.length===1){r.ticket_id=i[0];continue}r.ticket_id=i[1],r.consume_id=i[2],r.user_id=i.slice(3).join("#");let s=i[2].slice(-4);if(r.is_test=s===":CHK",!t.stmp){let o=i[2].slice(0,-4);/^[0-9]+$/.test(o)?r.timestamp=parseInt(o,10):r.timestamp=_e(i[2].slice(0,-4));}}else e[n]?r[e[n]]=t[n]:r[n]=t[n];return r}async function Qo(t){if(!t?.ticket_id)throw new f("Ticket ID is required.",{code:"INVALID_PARAMETER"});if(!/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(t.ticket_id))throw new f('Invalid "ticket_id". Use letters, digits, "_" and "-" (up to 64 chars, starting with a letter or digit).',{code:"INVALID_PARAMETER"});if(!t.method)throw new f('Method is required. Should be either "GET" or "POST"',{code:"INVALID_PARAMETER"});let e=String(t.method).toUpperCase();if(e!=="GET"&&e!=="POST")throw new f('Method should be either "GET" or "POST".',{code:"INVALID_PARAMETER"});let r=!!t.auth;if(r&&e==="GET")throw new f("Signed-in consumption is POST only.",{code:"INVALID_PARAMETER"});await this.__connection;let n=r?"tpa":e==="GET"?"tg":"tp",i=`https://${this.service.slice(0,4)}.${this.customApiDomain}/${n}/${this.service}/${t.ticket_id}`,s=await k.bind(this)(i,t.data||{},{method:e,auth:r},{ignoreService:true});if(s&&typeof s=="object"&&s.stage)throw new f(s.message,{code:s.code,cause:s});return !s||typeof s!="object"||Array.isArray(s)||typeof s.tkid!="string"?s:Lr(s)}async function Xo(t,e){await this.__connection;let r=await k.bind(this)("ticket",Object.assign({exec:"list"},t||{}),{auth:true,fetchOptions:e});return r.list=r.list.map(Lr),r}async function Zo(t){if(!t?.ticket_id)throw new f("Ticket ID is required.",{code:"INVALID_PARAMETER"});let e=t.before===void 0||t.before===null?Date.now():t.before;if(typeof e!="number"||!Number.isInteger(e)||e<=0)throw new f('"before" should be a time in milliseconds since the epoch.',{code:"INVALID_PARAMETER"});return k.bind(this)("register-ticket",{exec:"clearlog",ticket_id:t.ticket_id,before:e},{auth:true})}async function ea(t,e){await this.__connection;let r=await k.bind(this)("ticket",Object.assign({exec:"consumed"},t||{}),{auth:true,fetchOptions:e});return r.list=r.list.map(Lr),r}async function ta(t){let e=await k.bind(this)("register-ticket",Object.assign({exec:"reg"},t),{auth:true});return e&&typeof e=="object"&&e.ticket&&(e.ticket=Lr(e.ticket)),e}async function ra(t){return k.bind(this)("register-ticket",Object.assign({exec:"unreg"},t),{auth:true})}var Hf=3600;async function bt(){if(await this.__connection,this.session){let t=Math.floor(Date.now()/1e3),r=this.session.getIdToken().getExpiration();if(r<t+Hf){this.log("request:requesting new token",null);try{await Z.bind(this)().getSession({refreshToken:!0}),this.log("request:received new tokens",{exp:this.session?.idToken?.payload?.exp,currentTime:t,expiresIn:r-t,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:t,expiresIn:r-t,token:this.session.accessToken.jwtToken,refreshToken:this.session.refreshToken.token});return this.session?.idToken?.jwtToken}else throw this.log("request:no session",null),Me.bind(this)(),new f("User login is required.",{code:"INVALID_REQUEST"})}function Yo(t,e){return new Promise((r,n)=>{e.refreshSession(t.getRefreshToken(),(i,s)=>{this.log("getSession:refreshSessionCallback",{refreshErr:i,refreshedSession:s}),i?(Me.bind(this)(),n(i)):s.isValid()?r(s):(Me.bind(this)(),n(new f("Invalid session.",{code:"INVALID_REQUEST"})));});})}function Z(){if(!this.userPool)throw new f("User pool is missing",{code:"INVALID_REQUEST"});let t=()=>{let s=H.getSignInUserSession().getIdToken().payload||null,o=Ut(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:l=false,skipUserUpdateEventTrigger:c=false}=s||{};if(l&&c&&(c=false),H=this.userPool.getCurrentUser(),!H){this.log("getSession:cognitoUser",H),Me.bind(this)(),a(null);return}let d=h=>{let u=h.getIdToken().payload;if(this.log("getSession:respond:sessionAttribute",u),u["custom:service"]!==this.service)throw this.log("getSession:respond","invalid service, signing out"),Me.bind(this)(),new f("Invalid session.",{code:"INVALID_REQUEST"});return this.session=h,t(),c||this._runOnUserUpdateListeners(this.user),this.session};H.getSession((h,u)=>{if(this.log("getSession:getSessionCallback",{err:h,session:u}),!u){Me.bind(this)(),a(new f("Current session does not exist.",{code:"INVALID_REQUEST"}));return}if(h){Yo.bind(this)(u,H).then(y=>o(d(y))).catch(a);return}let g=Math.floor(Date.now()/1e3),p=u.getIdToken(),m=p.getExpiration(),b=m<g;if(this.log("getSession:currentTime",g),this.log("getSession:idTokenExp",m),this.log("getSession:isExpired",b),this.log("getSession:existingBearerToken",this.bearerToken),this.bearerToken=p.getJwtToken(),b||l||!u.isValid())Yo.bind(this)(u,H).then(y=>o(d(y))).catch(a);else try{o(d(u));}catch(y){a(y);}});}),r=(s,o)=>{let a=o||s.includes(this.service+"-")?s:this.service+"-"+ce.hash(s);return {cognitoUser:new Fe({Username:a,Pool:this.userPool}),cognitoUsername:a}};return {getSession:e,authenticateUser:(s,o,a=false,l=false)=>new Promise((c,d)=>{this.__request_signup_confirmation=null,this.__disabledAccount=null;let h=r(s,a),u=h.cognitoUsername,g=new on({Username:u,Password:o});h.cognitoUser.authenticateUser(g,{newPasswordRequired:(p,m)=>{this.__disabledAccount=null,this.__request_signup_confirmation=u,p["custom:signup_ticket"]==="PASS"||p["custom:signup_ticket"]==="MEMBER"||p["custom:signup_ticket"]==="OIDPASS"?h.cognitoUser.completeNewPasswordChallenge(o,{},{onSuccess:b=>{H=h.cognitoUser,e().then(async y=>{if(V.call(this))try{await Nr.bind(this)(o);}catch(A){this.log("encryption:ensureKeyring:failed",A);}c(this.user);});},onFailure:b=>{d(new f(b.message||"Failed to authenticate user.",{code:b.code}));}}):d(new f("User's signup confirmation is required.",{code:"SIGNUP_CONFIRMATION_NEEDED"}));},onSuccess:p=>e({skipUserUpdateEventTrigger:true}).then(async m=>{if(this.__disabledAccount=null,V.call(this))try{await Nr.bind(this)(o);}catch(b){this.log("encryption:ensureKeyring:failed",b);}this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user),c(this.user);}),onFailure:p=>{let m=[],{parsed:b,code:y}=Fr(p),A=typeof p?.message=="string"?p.message:"";if(y==="NotAuthorizedException"?A.includes("User is disabled.")?(this.__disabledAccount=u,m=["This account is disabled.","USER_IS_DISABLED"]):l?m=["The account already exists.","ACCOUNT_EXISTS"]:m=["Incorrect username or password.","INCORRECT_USERNAME_OR_PASSWORD"]:y==="UserNotFoundException"?m=["Incorrect username or password.","INCORRECT_USERNAME_OR_PASSWORD"]:y==="UserNotConfirmedException"?(this.__request_signup_confirmation=u,m=["User's signup confirmation is required.","SIGNUP_CONFIRMATION_NEEDED"]):(y==="TooManyRequestsException"||y==="LimitExceededException")&&(m=["Too many attempts. Please try again later.","REQUEST_EXCEED"]),b.code==="SIGNUP_CONFIRMATION_NEEDED"&&(this.__request_signup_confirmation=u),m.length){let w=m[1],S=m[0];d(new f(S,{code:w,cause:p}));}else d(b);}});}),createCognitoUser:r,signup:(s,o,a)=>new Promise((l,c)=>{this.userPool.signUp(s,o,a,null,(d,h)=>{if(d){let{parsed:u,code:g}=Fr(d),p=[];g==="UsernameExistsException"?p=["The account already exists.","EXISTS"]:g==="InvalidPasswordException"?p=["Invalid password. Password must be at least 6 characters.","INVALID_PARAMETER"]:g==="InvalidParameterException"?p=[u.message||"Invalid parameter.","INVALID_PARAMETER"]:g==="TooManyRequestsException"||g==="LimitExceededException"?p=["Too many attempts. Please try again later.","REQUEST_EXCEED"]:g==="CodeDeliveryFailureException"?p=["Failed to deliver verification code.","CODE_DELIVERY_FAILURE"]:g==="UserLambdaValidationException"&&(p=[u.message||"Signup validation failed.",u.code==="EXISTS"?"EXISTS":"INVALID_REQUEST"]),p.length?c(new f(p[0],{code:p[1],cause:d})):c(u);return}l(h);});})}}function Fr(t){let e=typeof t?.code=="string"&&t.code.trim()?t.code.trim():"ERROR",n=((typeof t?.message=="string"?t.message:typeof t=="string"?t:"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:t}),code:e}}async function na(t){await this.__authConnection;let e=t?.refreshToken||false;if(!e)return this.user;try{return await Z.bind(this)().getSession(Object.assign({skipUserUpdateEventTrigger:!e,refreshToken:e},t)),this.user}catch{return null}}async function ia(t){await this.__connection,t=_.Params(t,{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:t.token,id:t.id,merge:t.merge};t.template?.welcome&&(e.template_welcome=t.template.welcome);let r=await k.bind(this)("openid-logger",e),n=r.logger.split("#"),i=this.service+"-"+n[0],s=n[1];return {userProfile:await Z.bind(this)().authenticateUser(i,s,true,true),openid:r.openid}}function Gf(t){let e=typeof globalThis<"u"?globalThis:void 0;if(e?.Buffer)return e.Buffer.from(t,"base64").toString("utf8");if(typeof atob=="function"){let r=atob(t),n=new Uint8Array(r.length);for(let i=0;i<r.length;i++)n[i]=r.charCodeAt(i);return typeof TextDecoder<"u"?new TextDecoder().decode(n):r}throw new Error("No base64 decoder available in this environment")}function Wf(t){let e=t.split(".");if(e.length!==3)throw new Error("Invalid JWT format");let n=e[1].replace(/-/g,"+").replace(/_/g,"/"),i=Gf(n);return JSON.parse(i)}async function sa(t){await this.__authConnection,this.log("loginWithToken:params",t),t=_.Params(t,{idToken:"string",accessToken:"string",refreshToken:"string"},["idToken"]);let e=Wf(t.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 r=Math.floor(Date.now()/1e3);if(e.exp&&e.exp<r)throw new f("Token has expired.",{code:"INVALID_REQUEST"});if(this.__user=Ut(e),this.session=null,t.accessToken&&t.refreshToken)try{if(this.session=new ft({IdToken:new ut({IdToken:t.idToken}),AccessToken:new ct({AccessToken:t.accessToken}),RefreshToken:new dt({RefreshToken:t.refreshToken})}),this.log("loginWithToken:session",this.session),this.log("loginWithToken:CognitoUser",Fe),this.log("loginWithToken:userPool",this.userPool),Fe&&this.userPool){this.log("loginWithToken:cognito:username",e["cognito:username"]);let n={Username:e["cognito:username"],Pool:this.userPool};this.log("loginWithToken:cognitoUserParams",n),H=new Fe(n),H.setSignInUserSession(this.session),this.log("loginWithToken:cognitoUserRestored",{cognitoUserType:typeof H,cognitoUserKeys:Object.keys(H||{}),cognitoUser:H});}}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 ee(){return await this.__connection,this.__user?.service===this.service?this.__user?.owner===this.host:(await Kt.bind(this)(),false)}async function Me(t=false){let e=null;H&&(t?e=new Promise((n,i)=>{H.globalSignOut({onSuccess:s=>{this.log("globalSignOut:success",s),n(s);},onFailure:s=>{this.log("globalSignOut:error",s),i(s);}});}):H.signOut()),ei.bind(this)();let r={session:null,__startKeyHistory:{},__cached_requests:{},__user:null};e&&(e=await e);for(let n in r)this[n]=r[n];return this._runOnUserUpdateListeners(null),this._runOnLoginListeners(null),e}async function Kt(t){await this.__connection;let{data:e}=K(t);return await Me.bind(this)(e?.global),"SUCCESS: The user has been logged out."}async function oa(){if(!this.__request_signup_confirmation)throw new f("Least one login attempt is required.",{code:"INVALID_REQUEST"});return await k.bind(this)("confirm-signup",{username:this.__request_signup_confirmation})}async function aa(t=false){if(typeof t=="string")t=_.Url(t);else if(typeof t!="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 k.bind(this)("recover-account",{username:this.__disabledAccount,redirect:t}),"SUCCESS: Recovery e-mail has been sent."}async function mi(t){let e=_.Params(t,{username:"string",email:"string",password:"string"},["password"]);await this.__authConnection;let r=null;if(e.email)try{r=_.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"});let n=e.username||e.email;try{return await Z.bind(this)().authenticateUser(n,e.password)}catch(i){if((i?.code==="UserNotFoundException"||i?.code==="NotAuthorizedException")&&r&&r!==n)return await Z.bind(this)().authenticateUser(r,e.password);throw i}}async function la(t,e){await this.__authConnection;let r={username:"string",password:c=>_.Password(c),email:c=>_.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?_.Birthdate(c):"",phone_number:c=>c?_.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?_.Url(c):"",profile:c=>c?_.Url(c):"",family_name:"string",given_name:"string",middle_name:"string",nickname:"string",website:c=>c?_.Url(c):""},n=_.Params(t||{},r,["email","password"]);await Kt.bind(this)(),e=_.Params(e||{},{email_subscription:c=>{let d=c;if(typeof c=="number"||typeof c=="string"&&c!=="public"&&c!=="authorized"){let h=_.newsletterGroup(c);if(typeof h=="number"&&h!==0&&h!==1)throw new f('"option.email_subscription" takes 0 (public), 1 (authorized), true, false or the name of a newsletter group.',{code:"INVALID_PARAMETER"});d=h;}else if(typeof c!="boolean"&&typeof c!="string")throw new f('"option.email_subscription" takes 0 (public), 1 (authorized), true, false or the name of a newsletter group.',{code:"INVALID_PARAMETER"});if(d!==false&&!e?.signup_confirmation)throw new f('"option.signup_confirmation" is required for email subscription.',{code:"INVALID_PARAMETER"});return d},signup_confirmation:c=>{let d=c;if(typeof c=="string")d=_.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===void 0||e?.email_subscription===null?false:e.email_subscription,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=Z.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 k.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(":"),l=[new Pe({Name:"custom:signup",Value:o[0]}),new Pe({Name:"locale",Value:a.split("#")[1]}),new Pe({Name:"custom:signup_ticket",Value:a})];for(let c in r){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)?l.push(new Pe({Name:"custom:"+c,Value:n[c]})):l.push(new Pe({Name:c,Value:n[c]}))));}return await Z.bind(this)().signup(s.cognitoUsername,n.password,l),n.signup_confirmation?(H=s.cognitoUser,this.__request_signup_confirmation=s.cognitoUsername,"SUCCESS: The account has been created. User's signup confirmation is required."):i?mi.bind(this)({email:n.username||n.email,password:n.password}):"SUCCESS: The account has been created."}async function ca(){await this.__connection;let t=await k.bind(this)("remove-account",{disable:this.__user.user_id},{auth:true});return await Kt.bind(this)(),t}async function ua(t){await this.__connection;let e=_.Params(t,{email:i=>_.Email(i),code:["number","string"],new_password:i=>_.Password(i)},["email","code","new_password"]),r=e.code,n=e.new_password;return typeof r=="number"&&(r=r.toString()),new Promise(async(i,s)=>{Z.bind(this)().createCognitoUser(e.email).cognitoUser.confirmPassword(r,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 da(t,e,r){await this.__connection;let n;if(!H)throw new f("The user has to be logged in.",{code:"INVALID_REQUEST"});if(t==="email"||t==="phone_number"){if(!this.__user.hasOwnProperty(t))throw new f(`No ${t==="email"?"e-mail":"phone number"} to verify`,{code:"INVALID_REQUEST"});if(this.__user?.[`${t}_verified`])return `SUCCESS: "${t}" is verified.`;n=(e?_.Params(e,{code:"string"}):{}).code||"";}else return;let i,s=r?.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 l={onSuccess:c=>{n?Z.bind(this)().getSession({refreshToken:true}).then(()=>{this.__user&&(this.__user[t+"_verified"]=true),o(`SUCCESS: "${t}" 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?H?.verifyAttribute(t,n,l):(l.inputVerificationCode=null,H?.getAttributeVerificationCode(t,l,i));})}function fa(t,e){return da.bind(this)("phone_number",t,e)}function ha(t,e){return da.bind(this)("email",t,e)}async function pa(t,e){await this.__connection;let r=_.Params(t,{email:i=>_.Email(i)},["email"]),n;if(e?.template!==void 0){if(typeof e.template!="object"||e.template===null||Array.isArray(e.template))throw new f('"template" should be type: <object>.',{code:"INVALID_PARAMETER"});if(e.template.verification!==void 0)throw new f('"template.verification" is not an option of forgotPassword(). Use "template.forgot_password" (template message_id).',{code:"INVALID_PARAMETER"});let i=e.template.forgot_password;if(i!==void 0){if(typeof i!="string"||!i)throw new f('"template.forgot_password" should be a non-empty <string> (template message_id).',{code:"INVALID_PARAMETER"});n={template_forgot_password:i};}}return new Promise(async(i,s)=>{Z.bind(this)().createCognitoUser(r.email).cognitoUser.forgotPassword({onSuccess:a=>{i("SUCCESS: Verification code has been sent.");},onFailure:a=>{let{parsed:l,code:c}=Fr(a),d={UserNotFoundException:"NOT_EXISTS",InvalidParameterException:"INVALID_PARAMETER",NotAuthorizedException:"INVALID_REQUEST",LimitExceededException:"REQUEST_EXCEED",TooManyRequestsException:"REQUEST_EXCEED",CodeDeliveryFailureException:"CODE_DELIVERY_FAILURE"}[c]||l.code||c||"ERROR";s(new f(l.message,{code:d,cause:a}));}},n);})}async function ga(t){if(await this.__connection,!this.session)throw new f("User login is required.",{code:"INVALID_REQUEST"});let e=_.Params(t,{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 _.Password(e.current_password),_.Password(e.new_password),V.call(this)&&await Oo.bind(this)(e.current_password,e.new_password),new Promise((r,n)=>{H.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}=Fr(i);n(o);}return}V.call(this)&&Fo.bind(this)().catch(o=>this.log("encryption:prune:failed",o)),r("SUCCESS: Password has been changed.");});})}async function ma(t){if(await this.__connection,!this.session)throw new f("User login is required.",{code:"INVALID_REQUEST"});let e=_.Params(t||{},{user_id:i=>_.UserId(i),email:i=>_.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?_.Birthdate(i):"",phone_number:i=>i?_.PhoneNumber(i):"",email_public:"boolean",phone_number_public:"boolean",address_public:"boolean",gender_public:"boolean",birthdate_public:"boolean",misc:"string",picture:i=>i?_.Url(i):"",profile:i=>i?_.Url(i):"",family_name:"string",given_name:"string",middle_name:"string",nickname:"string",website:i=>i?_.Url(i):""});if(e&&typeof e=="object"&&!Object.keys(e).length)return this.user;let r=[["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 r)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 k.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 Pe({Name:s,Value:e[s]}));return await new Promise((s,o)=>{H?.updateAttributes(i,(a,l)=>{a&&o([a?.code||a?.name,a?.message||"Failed to update user settings."]),s(l);});}),await Z.bind(this)().getSession({refreshToken:true}),this.user}return this.user}async function ya(t,e){t=K(t).data,t||(t={searchFor:"timestamp",condition:">",value:0},e||(e={}),e.ascending=false),await this.__connection;let r={user_id:s=>_.UserId(s),email:"string",phone_number:"string",locale:s=>{if(typeof s!="string"||typeof s=="string"&&s.length>5)throw new f('Value of "locale" should be a country code.',{code:"INVALID_PARAMETER"});return s},name:"string",address:"string",gender:"string",birthdate:s=>_.Birthdate(s),subscribers:"number",timestamp:"number",access_group:"number",approved:"string"},n=["searchFor","value"],i=(s,o)=>{let a=r[t.searchFor];if(typeof a=="function")return a(s);if(typeof s!==a)throw new f(`${o} does not match the type of "${t.searchFor}" index.`,{code:"INVALID_PARAMETER"});return s};if(t=_.Params(t,{searchFor:["user_id","name","email","phone_number","address","gender","birthdate","locale","subscribers","timestamp","access_group","approved"],condition:[">",">=","=","<","<=","gt","gte","eq","lt","lte",()=>"="],value:s=>Array.isArray(s)?s.map(o=>i(o,"Value")):i(s,"Value"),range:s=>i(s,"Range")},n),t?.condition&&t?.condition!=="="&&t.hasOwnProperty("range"))throw new f("Conditions does not apply on range search.",{code:"INVALID_PARAMETER"});if(Array.isArray(t.value)&&(t.condition!=="="||t.range))throw new f(`Conditions are not allowed on a list of "${t.searchFor}" values. Search for a single value to use a condition or range.`,{code:"INVALID_PARAMETER"});if(typeof t?.value=="string"&&!t?.value)throw new f("Value should not be an empty string.",{code:"INVALID_PARAMETER"});if(typeof t?.searchFor=="string"&&!t?.searchFor)throw new f('"searchFor" should not be an empty string.',{code:"INVALID_PARAMETER"});return k.bind(this)("get-users",t,{auth:true,fetchOptions:e})}async function ba(t){await this.__connection;let e=await k.bind(this)("last-verified-email",t,{auth:true});return e.includes("SUCCESS")?(await Z.bind(this)().getSession({refreshToken:true}),this.user):e}var zf="1.2.1",Jf=class{constructor(t){Te(this,"version",zf);Te(this,"items",[]);Te(this,"nextJobId",1);Te(this,"breakWhenError",false);Te(this,"batchSize",1);Te(this,"onProgress");Te(this,"activeCount",0);Te(this,"currentCycleCompleted",[]);Te(this,"stopProcessing",false);if(this.breakWhenError=!!t?.breakWhenError,this.batchSize=t?.batchSize??1,typeof this.batchSize!="number"||this.batchSize<1)throw new Error("batchSize must be at least 1");if(t?.onProgress)if(typeof t.onProgress=="function")this.onProgress=t.onProgress;else throw new Error("onProgress must be a function")}get batchToProcess(){return Math.ceil(this.items.length/this.batchSize)}add(t){let e=Array.isArray(t)?t:[t],r=[];for(let n of e){if(typeof n!="function")throw new Error("Each job must be a function that returns a Promise");let i=String(this.nextJobId++);this.items.push({id:i,job:n}),r.push(i);}return this.processNext(),r}setBatchSize(t){if(typeof t!="number"||t<1)throw new Error("batchSize must be at least 1");this.batchSize=t;}remove(t){let e=String(t),r=this.items.findIndex(n=>n.id===e);return r===-1?false:(this.items.splice(r,1),true)}processNext(){if(this.stopProcessing||this.items.length===0||this.activeCount>0)return;let t=this.items.splice(0,this.batchSize);this.activeCount=t.length,this.currentCycleCompleted=new Array(t.length),t.forEach((e,r)=>{Promise.resolve().then(()=>e.job()).then(n=>(this.finalizeJob(r,n,false),n)).catch(n=>(this.finalizeJob(r,n,true),n));});}finalizeJob(t,e,r){if(this.currentCycleCompleted[t]=e,this.activeCount-=1,r&&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=[];}},$t=Jf;var _t=null,Ea=typeof SubmitEvent<"u",Yf=typeof HTMLFormElement<"u",Gt=J(),yi=0;function Aa(t){if(!t)return null;let e=Number(t);if(Number.isFinite(e))return Math.max(0,e*1e3);let r=Date.parse(t);return Number.isNaN(r)?null:Math.max(0,r-Date.now())}var _i=6,_a=6e4;function Ra(t,e){let r=t>0?t:Math.min(_a,500*Math.pow(2,e));r=Math.min(_a,r);let n=Math.floor(Math.random()*Math.min(1e3,Math.max(50,r*.25)));return r+n}function Sa(t){return new f(`Too many requests: ${t} still answered 429 after ${_i} retries.`,{code:"TOO_MANY_REQUESTS"})}function bi(t,e){return e>0?t/e*100:0}var wa=t=>{let{auth:e,type:r,endpoints:n,stable:i}=t,s=n[0],o=n[1];if(yi++,r==="admin"){let a=Object.entries(s).filter(([l,c])=>l.includes(e?"_private":"_public")&&l!=="get_users_private"&&l!=="service_public"&&typeof c=="string").map(([,l])=>l);if(!a.length)throw new f("No available admin gateways.",{code:"INVALID_REQUEST"});return a[yi%a.length]}if(r==="record"){let a=Object.entries(o).filter(([l,c])=>l.includes(e?"record_private":"record_public")&&typeof c=="string").map(([,l])=>l);if(!a.length)throw new f("No available record gateways.",{code:"INVALID_REQUEST"});return i?a[0]:a[yi%a.length]}throw new f("Invalid gateway type.",{code:"INVALID_REQUEST"})};async function Qf(t,e,r){let n=await Promise.all([this.admin_endpoint,this.record_endpoint]),i=n[0],s=n[1],o=t.split("?"),a=o.length>1?"?"+o[1]:"";switch(t=o[0],t){case "get-users":return i.get_users_private+t+a;case "service":return i.service_public+t+a;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 "send-inquiry":case "register-newsletter-group":case "delete-newsletter-group":case "newsletter-group-endpoint":case "invitation-list":case "csr":case "csr-poll":case "csr-cancel":case "csr-finalize":return wa.bind(this)({auth:e,type:"admin",endpoints:n})+t+a;case "post-record":return (e?s.post_private:s.post_public)+t+a;case "get-records":return (e?s.get_private:s.get_public)+t+a;case "del-files":case "del-records":return s.del_private+t+a;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 "get-signed-urls":case "extract-file-text":case "grid-query":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 wa.bind(this)({auth:e,type:"record",endpoints:n,stable:r})+t+a;default:return _.Url(t)+a}}var Ht={};function Ta(){_t&&(_t.terminate(),_t=null);}async function k(t,e=null,r,n){this.log("request",{url:t,data:e,options:r,_etc:n||{}}),r=r||{};let{auth:i=false,method:s="post",bypassAwaitConnection:o=false}=r;s=s.toUpperCase();let a=null,l=null,c=await Qf.bind(this)(t,!!i,!!r.stableGateway),d=e?.service||this.service,h=e?.owner||this.owner;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 u=r?.tokenHeaders?.idToken===true;(i||u)&&(l=await bt.bind(this)());let g={},{fetchMore:p=false,progress:m}=r?.fetchOptions||{};if(r?.fetchOptions&&Object.keys(r.fetchOptions).length){for(let I of ["limit","startKey","ascending"])if(r.fetchOptions.hasOwnProperty(I)){if(I==="startKey"&&r.fetchOptions[I]===null)continue;g[I]=r.fetchOptions[I];}g=_.Params(g,{limit:I=>{if(typeof I!="number")throw new f("Fetch limit should be a number.",{code:"INVALID_REQUEST"});if(I>1e3)throw new f("Fetch limit should be below 1000.",{code:"INVALID_REQUEST"});return I},startKey:I=>I,ascending:"boolean"});}let b=n?.ignoreService?{}:{service:d,owner:h};Object.assign(b,g),e=K(e).data,e?e&&typeof e=="object"&&(e=Object.assign(b,e)):e=b;let y=`${s}:${i?"auth":"public"}:${t}`,A=(()=>{if(e&&typeof e=="object"&&Object.keys(e).length&&!(Gt&&e instanceof FormData)){let I=function(D){return typeof D=="object"&&D!==null?Object.keys(D).sort().reduce((N,M)=>(typeof D[M]=="object"&&D[M]!==null?N[M]=I(D[M]):N[M]=D[M],N),{}):D};return ce.hash(y+"/"+JSON.stringify(I(e)))}return ce.hash(y+"/"+d)})(),{requestKey:w,requestKeyWithStartKey:S}=Xf.bind(this)({params:e,url:t,fetchMore:p,hashedParams:A});if(!w||w&&typeof w=="object")return w;if(this.log("requestKey",S),typeof S=="string"&&Ht[S]instanceof Promise)return this.log("request:returning pending",S),Ht[S];let R={Accept:"*/*"};if(Object.prototype.hasOwnProperty.call(r,"contentType")&&r.contentType!==void 0){let I=r.contentType===null?"application/x-www-form-urlencoded":r.contentType;I&&(R["Content-Type"]=I);}else R["Content-Type"]="application/json";if(l&&(R.Authorization=l),r?.tokenHeaders){let I=(M,te)=>typeof M=="string"?M:M===true?te:null,D=I(r.tokenHeaders.accessToken,this.session?.accessToken?.jwtToken||null),N=I(r.tokenHeaders.idToken,this.bearerToken||this.session?.idToken?.jwtToken||l||null);D&&(R["X-Access-Token"]=D),N&&(R["X-Id-Token"]=N);}let O={public_identifier:this.__public_identifier,service:d,owner:h,resolves_offloaded_data:true};R["Content-Meta"]=JSON.stringify(O),r.revalidate&&(R["Cache-Control"]="no-cache",R.Pragma="no-cache");let C={headers:R};if(r?.responseType&&(C.responseType=r.responseType),s==="GET"){if(e){let I=[];if(Gt&&e instanceof FormData?I=Array.from(e.entries()).map(([D,N])=>{let M=typeof N=="string"?N:N.name;return encodeURIComponent(D)+"="+encodeURIComponent(M)}):I=Object.keys(e).map(D=>{let N=e[D];return typeof N!="string"&&(N=JSON.stringify(N)),encodeURIComponent(D)+"="+encodeURIComponent(N)}),I.length){let D=c.includes("?")?c.endsWith("?")||c.endsWith("&")?"":"&":"?";c+=D+I.join("&");}}C.body=null;}else if(Gt&&e instanceof FormData)C.body=e;else if(R["Content-Type"]==="application/x-www-form-urlencoded"&&e&&typeof e=="object"){let I=new URLSearchParams;for(let D of Object.keys(e)){let N=e[D];I.append(D,typeof N=="string"?N:JSON.stringify(N));}C.body=I.toString();}else typeof e=="string"?C.body=e:C.body=e?JSON.stringify(e):null;if(C.method=s,_t===null){let I={batchSize:this.requestBatchSize,breakWhenError:false,onProgress:D=>{this.onBatchProcess.forEach(N=>N(D));}};_t=new $t(I);}return this.log("request-opt",C),new Promise((I,D)=>{_t.add([async()=>{let N=va.bind(this)(c,C,m);Ht[S]=N;try{let M=eh.bind(this)({hashedParam:w,requestKeyWithStartKey:S,url:t,fetched:await N});return delete Ht[S],this.log("request:end",M),I(M),M}catch(M){throw delete Ht[S],this.log("request:err",M),D(M),M}}]);})}function Xf(t){let{params:e={},url:r,fetchMore:n=false,hashedParams:i}=t||{};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?.[r]?.[i]&&delete this.__cached_requests[r][i],this.__startKeyHistory?.[r]?.[i]){if(Array.isArray(this.__startKeyHistory[r][i])&&this.__startKeyHistory[r][i].length)for(let l of this.__startKeyHistory[r][i]){let c=i+ce.hash(l);this.__cached_requests?.[r]&&this.__cached_requests?.[r]?.[c]&&delete this.__cached_requests[r][c];}delete this.__startKeyHistory[r][i];}return {requestKeyWithStartKey:i,requestKey:i}}if(!Array.isArray(this.__startKeyHistory?.[r]?.[i]))return {requestKeyWithStartKey:i,requestKey:i};let s=this.__startKeyHistory[r][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+=ce.hash(o),e.startKey=JSON.parse(o);}return this.__cached_requests?.[r]?.[a]?{requestKey:this.__cached_requests[r][a],requestKeyWithStartKey:a}:{requestKeyWithStartKey:a,requestKey:i}}function Zf(t){let e=r=>r&&typeof r=="object"&&r.encrypted?Object.assign({},r,{data:null}):r;return Array.isArray(t)?t.map(e):t&&typeof t=="object"?Array.isArray(t.list)?Object.assign({},t,{list:t.list.map(e)}):e(t):t}function va(t,e,r,n=0){return new Promise((i,s)=>{let o=new XMLHttpRequest;o.open(e.method||"GET",t);for(var a in e.headers||{})o.setRequestHeader(a,e.headers[a]);e.responseType&&(o.responseType=e.responseType),o.onload=()=>{if(o.status<400)if(e.responseType=="json"||e.responseType=="blob")i(o.response);else {let l=o.responseText;try{l=JSON.parse(l);}catch{}i(l);}else if(o.status===429){let l=o.getResponseHeader("Retry-After"),c=Aa(l);if(c!==null){if(n>=_i){s(Sa(`"${t.split("?")[0]}"`));return}setTimeout(()=>{va(t,e,r,n+1).then(i,s);},Ra(c,n));}else s("Too many requests");}else {let l=o.status,c=["INVALID_CORS","INVALID_REQUEST","SERVICE_DISABLED","INVALID_PARAMETER","ERROR","EXISTS","NOT_EXISTS"],d=e.responseType=="blob"?o.response:o.responseText;try{d=JSON.parse(d);}catch{}if(typeof d=="string"){let h=d.split(":"),u=h.splice(0,1)[0].trim(),g=h.join(":").trim();s(new f(g||d,{code:c.includes(u)?u:"ERROR"}));}else if(typeof d=="object"&&(d?.message||d?.stage||d?.code)){let h=d?.code||(l?l.toString():null)||"ERROR",u=d.message,g=d?.cause;g===void 0&&d.stage&&(g=d),typeof u=="string"&&(u=u.trim()),u||(u=String(h)),s(new f(u,{cause:g,code:h}));}else s(d);}},o.onerror=()=>s("Network error"),o.onabort=()=>s("Aborted"),o.ontimeout=()=>s("Timeout"),typeof r=="function"&&(o.onprogress=l=>{r({status:"download",progress:bi(l.loaded,l.total),loaded:l.loaded,total:l.total,abort:()=>o.abort()});},o.upload&&(o.upload.onprogress=l=>{r({status:"upload",progress:bi(l.loaded,l.total),loaded:l.loaded,total:l.total,abort:()=>o.abort()});})),o.send(e.body);})}function eh(t){let{hashedParam:e,requestKeyWithStartKey:r,url:n,fetched:i}=t;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][r]=i,Object.assign({startKeyHistory:this.__startKeyHistory[n][e]},i)}function th(t){if(t instanceof f)return t;if(typeof t=="string"){let e=t.trim();if(e==="Network error")return new f("Network error",{code:"NETWORK_ERROR"});if(e==="Aborted")return new f("Aborted",{code:"ABORTED"});if(e==="Timeout")return new f("Timeout",{code:"TIMEOUT"});if(e==="Too many requests")return new f("Too many requests",{code:"TOO_MANY_REQUESTS"});let r=/<Code>([^<]+)<\/Code>/.exec(e)?.[1]?.trim()||"",n=/<Message>([^<]+)<\/Message>/.exec(e)?.[1]?.trim()||"";return r||n?new f(n||r,{code:r||"UPLOAD_FAILED",cause:e}):new f(e.length>300?e.slice(0,300):e||"Upload failed.",{code:"UPLOAD_FAILED",cause:e})}if(t&&typeof t=="object"){let e=t.code||t.Code,r=t.message||t.Message;if(e||r)return new f(String(r||e),{code:String(e||"UPLOAD_FAILED"),cause:t})}return new f("Upload failed.",{code:"UPLOAD_FAILED",cause:t})}var rh=5,nh=100;function ih(t){let e=String(t?.code??"");if(e==="404"||e==="501")return true;let r=String(t?.message??t??"");return /missing authentication token/i.test(r)||/not implemented/i.test(r)||e==="403"&&/not found/i.test(r)}function sh(t,e){let r=Array.isArray(t?.list)?t.list:[],n=Array.isArray(t?.failed)?t.failed:[],i=new Array(e);for(let s of n)s&&Number.isInteger(s.index)&&s.index>=0&&s.index<e&&(i[s.index]=new f(String(s.message||"Upload permit refused."),{code:String(s.code||"ERROR")}));for(let s=0;s<e;s++){if(i[s])continue;let o=r[s];o&&typeof o.url=="string"?i[s]={fields:o.fields||null,url:o.url,cdn:o.cdn}:i[s]=new f("No upload permit was answered for this file.",{code:"ERROR"});}return i}async function Wt(t,e){await this.__connection;let{record_id:r,service:n=this.service,progress:i,timeout:s,throwOnFileError:o=false}=e;if(!r)throw new f('"record_id" is required.',{code:"INVALID_PARAMETER"});if(s!=null){if(typeof s!="number"||!Number.isFinite(s)||s<0)throw new f('"timeout" should be a number of milliseconds, 0 or more.',{code:"INVALID_PARAMETER"})}else s=0;if(Ea&&t instanceof SubmitEvent&&(t=t.target),Yf&&t instanceof HTMLFormElement&&(t=new FormData(t)),!Gt||!(t instanceof FormData))throw new f('"fileList" should be a FormData or HTMLFormElement.',{code:"INVALID_PARAMETER"});let l={reserved_key:Ye(),service:n,request:"post"};e?.record_id&&(l.id=e.record_id);let c,d=(w,S,R,U,O=0)=>new Promise((C,I)=>{c=new XMLHttpRequest,c.open("POST",w),s>0&&(c.timeout=s),c.onload=()=>{let D=c.responseText;try{D=JSON.parse(D);}catch{}if(c.status>=200&&c.status<300)C(D);else if(c.status===429){let N=c.getResponseHeader("Retry-After"),M=Aa(N);if(M!==null){if(O>=_i){I(Sa(`the upload of "${U}" to "${w}"`));return}setTimeout(()=>{d(w,S,R,U,O+1).then(C,I);},Ra(M,O));}else I("Too many requests");}else I(D);},c.onerror=()=>I("Network error"),c.onabort=()=>I("Aborted"),c.ontimeout=()=>I(new f(`Upload timeout: "${U}" was not finished within ${s} ms.`,{code:"TIMEOUT"})),c.upload&&typeof R=="function"&&(c.upload.onprogress=R),c.send(S);});function h(w){let S="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";if(w===0)return S[0];let R="";for(;w>0;)R=S[w%62]+R,w=Math.floor(w/62);return R}let u=[],g=[],p=[],m=[],b=[];for(let[w,S]of t.entries())S instanceof File&&b.push([w,S]);let y=b.length>=rh&&!this.__bulkPermitsUnavailable,A=0;for(;A<b.length;){let w=b.slice(A,A+(y?nh:1));A+=w.length;let S=[];for(let[U,O]of w){let C=await zo.bind(this)(r,U,O);S.push({file:O,uploadFile:C.file,params:{key:C.key+"/"+C.file.name,sizeKey:h(C.file.size),contentType:C.file.type||null}});}let R=null;if(y)try{let U=await k.bind(this)("get-signed-urls",Object.assign({files:S.map(O=>O.params)},l),{auth:!!this.__user});R=sh(U,S.length);}catch(U){if(!ih(U))throw U;this.__bulkPermitsUnavailable=true,y=false;}if(!R){R=[];for(let U of S){let{fields:O=null,url:C,cdn:I}=await k.bind(this)("get-signed-url",Object.assign(U.params,l),{auth:!!this.__user});R.push({fields:O,url:C,cdn:I});}}for(let U=0;U<S.length;U++){let{file:O,uploadFile:C}=S[U],I=R[U];if(I instanceof f){if(m.push(""),g.push(O),p.push({file:O,name:O.name,error:I}),o)throw I;continue}m.push(I.cdn);let D=new FormData;for(let N in I.fields||{})D.append(N,I.fields[N]);D.append("file",C);try{await d(I.url,D,typeof i=="function"?N=>i({status:"upload",progress:bi(N.loaded,N.total),currentFile:O,completed:u,failed:g,loaded:N.loaded,total:N.total,abort:()=>c.abort()}):null,O.name),u.push(O);}catch(N){g.push(O);let M=th(N);if(p.push({file:O,name:O.name,error:M}),o)throw M}}}return {completed:u,failed:g,errors:p,bin_endpoints:m}}var Mr={};function x(t){let{preventMultipleCalls:e=false}=t||{};return function(r,n,i){let s=i.value;i.value=function(...o){let a=o[0],l=true,c=null,d="",h={},u=false;if(Ea&&a instanceof SubmitEvent){a.preventDefault();let y=window.location.href;c=a.target;let A=new URL(c.action);d=A.href;let w=d?d.match(/(?<=\{).*?(?=\})/g):"";if(w)for(let S of w){if(!S)continue;let R=c.querySelector(`[name="${S}"]`);if(R)if(R.type==="file")for(let U=0;U<=R.files.length-1;U++)R.files[U]&&(h[S]||(h[S]=[]),h[S].push(new Promise((O,C)=>{let I=new FileReader;I.onload=function(){O(I.result);},I.readAsDataURL(R.files[U]),I.onerror=C;})));else d=d.replace(`{${S}}`,R.value);}c.getAttribute("action")===null?l=false:u=A.href===y;}let g=async y=>{if(d)for(let A in h)h[A].length&&(d=d.replace(`{${A}}`,(await Promise.all(h[A])).join(",")));if(c&&l){let A=V.call(this)?Zf(y):y;window.sessionStorage.setItem(`${this.service}:${ce.hash(d)}`,JSON.stringify(A)),u?window.location.replace(d):window.location.href=d;}return y},p,m=y=>{throw y instanceof f?y.name=n+"()":y=y instanceof Error?y:new f(y,{name:n+"()"}),y},b=async()=>{try{if(this.__projectIdInput&&await this.__projectIdInput,p=s.bind(this)(...o),p instanceof Promise){let y=await p;return g(y)}return g(p)}catch(y){throw m(y)}};if(e){let y=`${n}:${this?.__public_identifier||""}:${this?.service||""}:${this?.owner||""}`;return Mr?.[y]||(Mr[y]=b().finally(()=>{delete Mr[y];})),Mr[y]}return b()};}}async function Ia(){await this.__connection;let t=`${this.service}:${ce.hash(window.location.href.split("?")[0])}`,e=window.sessionStorage.getItem(t);if(window.sessionStorage.removeItem(t),e!==null){try{e=JSON.parse(e);}catch{}return e}return null}var oh=256,ah=256,lh=256,Pa=256,ch="\u{10FFFF}",uh=/[\u0000-\u001F\u007F]|\u{10FFFF}/u,dh={"/":"%2F","!":"%21","*":"%2A","#":"%23"},fh={"%2F":"/","%21":"!","%2A":"*","%23":"#"};function hh(t){return t.replace(/%/g,"%25").replace(/[\/!*#]/g,r=>dh[r]||r)}function Ae(t){return typeof t!="string"?t:t.replace(/%(2F|21|2A|23)/gi,r=>{let n=r.toUpperCase();return fh[n]||r}).replace(/%25/gi,"%")}function ke(t,e,r={}){let{allowEmpty:n=false,maxLength:i,blockKeyDelimiters:s=false,disallowLeadingDollar:o=false,onlyAlphanumeric:a=false}=r;if(typeof t!="string")throw new f(`"${e}" should be type: <string>.`,{code:"INVALID_PARAMETER"});if(a&&/[^a-zA-Z0-9]/.test(t))throw new f(`"${e}" should only contain alphanumeric characters.`,{code:"INVALID_PARAMETER"});if(!n&&t.length===0)throw new f(`"${e}" is required.`,{code:"INVALID_PARAMETER"});if(i&&t.length>i)throw new f(`"${e}" should be <= ${i} characters.`,{code:"INVALID_PARAMETER"});if(uh.test(t)||t.includes(ch))throw new f(`"${e}" cannot include control characters or unsupported sentinel characters.`,{code:"INVALID_PARAMETER"});if(s&&(t=hh(t),i&&t.length>i))throw new f(`"${e}" should be <= ${i} characters. "/", "!", "*", "#" and "%" count as 3 characters each.`,{code:"INVALID_PARAMETER"});if(o&&t.startsWith("$"))throw new f(`"${e}" cannot start with "$".`,{code:"INVALID_PARAMETER"});return t}function wt(t,e="table.name",r={}){return ke(t,e,{allowEmpty:r.allowEmpty===true,maxLength:oh,blockKeyDelimiters:true})}function Vr(t,e="tag",r={}){return ke(t,e,{allowEmpty:r.allowEmpty===true,maxLength:ah,blockKeyDelimiters:true})}function zt(t,e="index.name",r={}){return ke(t,e,{allowEmpty:r.allowEmpty===true,maxLength:lh,blockKeyDelimiters:true,disallowLeadingDollar:true})}function ka(t,e="index.value"){return ke(t,e,{allowEmpty:true,maxLength:Pa})}function wi(t){return typeof t=="string"&&t.slice(-1)==="."}function Ei(t,e){return ke(t,e,{allowEmpty:true,maxLength:Pa,blockKeyDelimiters:true})}function xa(t){if(!t.record_id&&!t.unique_id)return null;let e={};return t?.service&&(e.service=t.service),t?.owner&&(e.owner=t.owner),t?.record_id?e.record_id=ke(t.record_id,"record_id",{allowEmpty:false,onlyAlphanumeric:true}):t?.unique_id&&(e.unique_id=t.unique_id),e}function Ai(t){if(t===void 0)return 0;if(typeof t=="number"){if(t>99||t<0)throw new f('"table.access_group" value should be within a range of 0 ~ 99.',{code:"INVALID_REQUEST"})}else if(typeof t=="string"){if(t={"*":"private",private:"private",public:0,authorized:1,admin:99}[t],t===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&&t)throw new f("Unsigned users have no access to records with access group.",{code:"INVALID_REQUEST"});return t}var qr=4503599627370496;function Br(t){if(typeof t=="number"){if(t>qr||t<-qr)throw new f(`Number value should be within range -${qr} ~ +${qr}`,{code:"INVALID_PARAMETER"});return t}if(typeof t=="boolean")return t;if(typeof t=="string")return ka(t,"index.value");throw new f('"index.value" should be type: <number | boolean | string>.',{code:"INVALID_PARAMETER"})}function Ua(t,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 t)throw new f('"index.range" type should match the type of "index.value".',{code:"INVALID_PARAMETER"});return typeof t=="string"?wi(e.index.name)?Ei(t,"index.range"):ka(t,"index.range"):t}var jr={},ph=10080*60,gh=3600,Ca=2;function mh(t,e){if(!e)return String(Ca);let r=Math.max(60,t-300)*1e3;return "g"+Ca+"w"+Math.floor(Date.now()/r)}function yh(t){if(!this.user?.user_id)return false;let e=t[6]==="**"?"**":parseInt(t[6]),r=this.user?.access_group??-1;return !(this.user.user_id!==t[3]&&(e==="**"||r<e))}function bh(t){if(typeof t=="string"){if(t.startsWith("!J%"))try{return JSON.parse(t.substring(3))}catch{return t}return t==="!D%{}"?{}:t==="!L%[]"?[]:t}if(t&&typeof t=="object"&&!Array.isArray(t)&&typeof t.__json__=="string"&&Object.keys(t).length===1)try{return JSON.parse(t.__json__)}catch{}return t}async function Kr(t){return typeof t=="string"?t:t&&typeof t.text=="function"?await t.text():await new Promise((e,r)=>{try{let n=new FileReader;n.onload=()=>e(n.result),n.onerror=()=>r(n.error||new Error("Failed to read blob")),n.readAsText(t);}catch(n){r(n);}})}function Si(t){return !!t&&typeof t=="object"&&!Array.isArray(t)&&typeof t.__data__=="string"&&Object.keys(t).length===1&&t.__data__.endsWith("/__data__/__json__.json")}var Et=new Map,_h=1024,wh=/^[0-9A-Za-z]+\/[0-9A-Za-z]+\/__data__\/__json__\.json$/,Na=/^[0-9A-Za-z_-]+$/,Eh=/^(\d{2}|\*\*)$/;function Oa(t){if(typeof t!="string")return null;let e=t.split("?")[0].split("/");if(e.length<15||e[0]!=="https:"||e[1]!==""||!e[2])return null;let r=e.slice(3);return r[0]!=="publ"&&r[0]!=="auth"||r[4]!=="records"||r[7]!=="bin"||!Na.test(r[1])?null:{origin:e.slice(0,3).join("/"),service:r[1]}}function Ah(t){let e=Oa(t);!e||Et.get(e.service)===e.origin||(Et.size>=_h&&!Et.has(e.service)&&Et.clear(),Et.set(e.service,e.origin));}function Da(t,e){if(typeof e!="string"||!wh.test(e))return null;let r=typeof t.usr_tbl=="string"?t.usr_tbl.split("/"):null,n=typeof t.tbl=="string"?t.tbl.split("/"):null,i=null,s=null;if(typeof t.srvc=="string"){let d=t.srvc.split("!")[0].split("/");d.length===2&&(i=d[0],s=d[1]);}i||(i=r?.[2]||n?.[1]||null,i&&i===this.service&&(s=this.owner));let o=typeof t.usr=="string"&&t.usr?t.usr:r?.[0]||null,a=r?.[3]||n?.[2]||null,l=t.rec;for(let d of [i,s,o,l])if(typeof d!="string"||!Na.test(d))return null;if(typeof a!="string"||!Eh.test(a))return null;let c=null;if(Array.isArray(t.bin))for(let d of t.bin){let h=Oa(d);if(h&&h.service===i){c=h.origin;break}}return c=c||Et.get(i)||null,c?`${c}/${a==="00"?"publ":"auth"}/${i}/${s}/${o}/records/${l}/${a}/bin/${e}`:null}async function Ze(t,e,r=false,n=false,i=false){let s={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:{}},o=false,a=[],l=null;function c(u){let g=u=="**"?"private":parseInt(u);return g=g==0?"public":g==1?"authorized":g==99?"admin":g,g}let d={ip:u=>{let g=u.split("#"),p=g[0];g.length>1&&(s.unique_id=g.slice(1).join("#")),p.slice(-1)==="R"?(s.readonly=true,p=p.slice(0,-1)):s.readonly=false,/^\d{1,3}-\d{1,3}-\d{1,3}-\d{1,3}$/.test(p)&&(p=p.split("-").join("."),o=true),s.ip=p;},rec:u=>{if(!u)return;s.record_id=u;let g=u.substring(0,u.length-9),p=_e(g);s.uploaded=p;},usr:u=>{s.user_id=u;},tbl:u=>{if(u&&!s.table.name){let g=u.split("/");s.table.name=Ae(g[0]),s.table.access_group=c(g[2]),g?.[3]&&(s.table.subscription.is_subscription_record=true);}},usr_tbl:u=>{let g=u.split("/");s.user_id||(s.user_id=g[0]),s.table.name||(s.table.name=Ae(g[1]),s.table.access_group=c(g[3]),g?.[4]&&(s.table.subscription.is_subscription_record=true));},idx:u=>{if(!u)return;let g=u.split("!"),p=Ae(g.splice(0,1)[0]),m=Rh("!"+g.join("!"));s.index={name:p,value:m};},ref:u=>{u&&(s.reference=u.split("/")[0]);},tags:u=>{s.tags=Array.isArray(u)?u.map(g=>Ae(g)):u;},upd:u=>{s.updated=u;},acpt_mrf:u=>{s.source.prevent_multiple_referencing=!u;},ref_limt:u=>{s.source.referencing_limit=u;},rfd:u=>{s.referenced_count=u;},bin:async u=>{let g={},p=s?.reference||null;if(Array.isArray(u)){let m=await Promise.all(u.map(async b=>{try{let y=b.split("/").slice(3).join("/"),A=y.split("/");if(A.length<12)return null;let w=A[A.length-1],S=A[10];if(S==="__data__"&&w==="__json__.json")return {isDataFile:!0,rawUrl:b};if(ii(S,w))return {isDataFile:!0,rawUrl:b};let R=Or(S),U=A[9],O=A[8],C=c(A[6]),I=b,D=C!=="public"&&yh.call(this,A)?{expires:gh,browserCache:ph}:null;if(C!=="public"&&!i)try{I=await qe.bind(this)(b,{dataType:"endpoint",_ref:p});}catch(M){console.error("Error getting signed url for private file:",M),I=b;}let N={access_group:C,filename:w,url:I,path:y,size:R?R.plainSize:_e(U),uploaded:_e(O),getFile:(M,te)=>{let ie={dataType:M||"download",progress:te,_ref:p},q=()=>qe.bind(this)(I,Object.assign({},ie,{_update:N}));return D?qe.bind(this)(b,Object.assign({},ie,D)).catch(()=>q()):q()}};return R&&(N.encrypted=!0,N.stored_size=_e(U)),{pathKey:R?R.key:S,obj:N}}catch{return null}}));for(let b of m)if(b&&!b.isDataFile){if(g[b.pathKey]){g[b.pathKey].push(b.obj);continue}g[b.pathKey]=[b.obj];}}s.bin=g;},prv_acs:u=>{for(let g in u)["notify_subscribers","upload_to_feed","feed_referencing_records","notify_referencing_records"].includes(g)?s.table.subscription[g]=u[g]:g==="referencing_index_restrictions"&&Array.isArray(u[g])?s.source[g]=u[g].map(m=>m&&typeof m=="object"&&typeof m.name=="string"?Object.assign({},m,{name:Ae(m.name)}):m):s.source[g]=u[g];},data:async u=>{let g={access_group:s.table.access_group,table_name:s.table.name,user_id:s.user_id,record_id:s.record_id,unique_id:s.unique_id,ctUrl:l},p=()=>{V.call(this)&&(s.encrypted={status:"failed",reason:"DATA_UNAVAILABLE"});},m=async y=>{if(n||!V.call(this)&&!Cr(y))return y;let A=await Io.bind(this)(y,g);return A.flag&&(s.encrypted=A.flag),A.value},b=bh(u);if(b!==u){s.data=await m(b);return}if(Si(u)){let y=u.__data__,A=a.find(w=>w.endsWith(y))||null;if(!A&&!r){await Promise.resolve();let w=Da.call(this,t,y),S=false,R;if(w)try{let U=await qe.bind(this)(w,{dataType:"blob",_ref:s.reference||null});R=JSON.parse(await Kr(U)),S=!0;}catch{}if(S){s.data=await m(R);return}p();}if(A){if(r){s.data=u;return}try{let w=await qe.bind(this)(A,{dataType:"blob",_ref:s.reference||null}),S=await Kr(w);s.data=await m(JSON.parse(S));}catch(w){let S=Da.call(this,t,y),R=false,U;if(S&&S!==A)try{let O=await qe.bind(this)(S,{dataType:"blob",_ref:s.reference||null});U=JSON.parse(await Kr(O)),R=!0;}catch{}if(R){s.data=await m(U);return}console.error("Failed to fetch offloaded record data:",w),s.data=null,p();}return}}s.data=await m(u);}};if(t.record_id)return t;if(Array.isArray(t.bin))for(let u of t.bin)try{if(typeof u!="string")continue;Ah(u);let g=u.split("/").slice(3);g.length>=12&&g[10]==="__data__"&&g[g.length-1]==="__json__.json"&&a.push(u),g.length>=12&&ii(g[10],g[g.length-1])&&(l=u);}catch{}let h=[];for(let u in d)if(t.hasOwnProperty(u)){let g=d[u](t[u]);g instanceof Promise&&h.push(g);}return o&&(s.user_id="anonymous:"+s.user_id),await Promise.all(h),s}function Rh(t){let e=t.substring(3);switch(t.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 t}}async function Fa(t){let{endpoints:e}=t;if(typeof e=="string"&&(e=[e]),!Array.isArray(e))throw new f('"endpoints" should be type: array | string.',{code:"INVALID_PARAMETER"});let r=await k.bind(this)("del-files",{endpoints:e,storage:"records"},{auth:true,method:"post"}),n=[];for(let i in r)n.push(Ze.bind(this)(r[i]));return Promise.all(n)}async function qe(t,e){if(typeof t!="string")throw new f('"url" should be type: string.',{code:"INVALID_PARAMETER"});let r=t,n=t.split("?"),i=n.shift()||"",s=n.length?"?"+n.join("?"):"",o=_.Url(i);t=o+s;let a=false,l=o.split("/"),d=l[2].split("."),h=null;d.length===3&&d[1]==="skapi"&&(h=d[0],a=true);let u=l.slice(3),g=false;if(!a&&(u[0]==="auth"||u[0]==="publ"))try{_.UserId(u[2]),_.UserId(u[3]),g=u[0]=="auth",a=!0;}catch{throw new f("Invalid file url.",{code:"INVALID_PARAMETER"})}let p=h?null:u[1];if(e=_.Params(e,{expires:["number",()=>0],browserCache:["number",()=>0],refresh:["boolean",()=>false],dataType:["base64","blob","endpoint","text","info",()=>"download"],progress:["function","undefined",null],_ref:[null,"string"],_update:w=>w}),e?.dataType==="info")return {url:t,filename:u[u.length-1],fileKey:u[u.length-2],access_group:u[6]==="**"?"private":u[6]==="01"?"authorized":u[6]==="00"?"public":parseInt(u[6]),uploader:u[3],record_id:u[4]==="records"?u[5]:"N/A",filesize:_e(u[9]),uploaded:_e(u[8])};let m=t.split("/").slice(-1)[0],b=e.expires;if(b){if(!a)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 w={request:h?"get-host":"get",id:h||u[5],key:r.split("?")[0],expires:b};p&&(w.service=p);let S=e.browserCache,R={auth:true};if(S){if(S<0)throw new f('"config.browserCache" should be > 0. (seconds)',{code:"INVALID_PARAMETER"});R.method="get",R.stableGateway=true,w.browser_cache=S;let U=this.session?.idToken?.payload?.sub||this.user?.user_id;U&&(w.uid=U),w.nocache=mh(b,e.refresh);}t=(await k.bind(this)("get-signed-url",w,R)).url;}else if(g){let w=Math.floor(Date.now()/1e3);if(!this.bearerToken&&(!this.session?.idToken?.payload?.exp||this.session.idToken.payload.exp<w)){this.log("getFile:requesting new token",null);try{await Z.bind(this)().getSession({refreshToken:!0}),this.log("getFile:received new tokens",{exp:this.session?.idToken?.payload?.exp,currTime:w,expiresIn:this.session?.idToken?.payload?.exp-w,token:this.session?.accessToken?.jwtToken,refreshToken:this.session?.refreshToken?.token});}catch(O){throw this.log("getFile:new token error",O),new f("User login is required.",{code:"INVALID_REQUEST"})}}let S=this.bearerToken||this.session?.idToken?.jwtToken;if(!S||!this.user?.user_id)throw new f("User login is required.",{code:"INVALID_REQUEST"});t+=`${t.includes("?")?"&":"?"}t=${encodeURIComponent(S)}`;let R=u[6]==="**"?"**":parseInt(u[6]),U=this.user?.access_group??-1;if(this.user.user_id!==u[3]&&(R==="**"||U<R)){let O=u[5];if(this.__private_access_key[O]&&typeof this.__private_access_key[O]=="string")t+=`&p=${encodeURIComponent(this.__private_access_key[O])}`;else if(this.owner!==this.host)try{let C=await this.requestPrivateRecordAccessKey({record_id:O,reference_id:e?._ref});t+=`&p=${encodeURIComponent(C)}`;}catch{}}}if((V.call(this)?pi(t):null)&&e?.dataType!=="endpoint"&&e?.dataType!=="info"){let w=await k.bind(this)(t,null,{method:"get",contentType:null,responseType:"blob",fetchOptions:{progress:e?.progress}},{ignoreService:true}),S=await Jo.bind(this)(t,w);if(e?.dataType==="blob")return S;if(e?.dataType==="text")return await Kr(S);if(e?.dataType==="base64")return await new Promise((O,C)=>{let I=new FileReader;I.onloadend=()=>O(I.result),I.onerror=()=>C(I.error),I.readAsDataURL(S);});let R=URL.createObjectURL(S),U=document.createElement("a");return U.href=R,document.body.appendChild(U),U.setAttribute("download",m),U.click(),document.body.removeChild(U),setTimeout(()=>URL.revokeObjectURL(R),6e4),null}if(e?.dataType==="endpoint")return e._update&&(e._update.url=t),t;if(e?.dataType==="download"){let w=document.createElement("a");return w.href=t,document.body.appendChild(w),w.setAttribute("download",m),w.target="_blank",w.click(),document.body.removeChild(w),null}return new Promise(async(w,S)=>{try{let R=await k.bind(this)(t,null,{method:"get",contentType:null,responseType:e?.dataType==="text"?"text":"blob",fetchOptions:{progress:e?.progress}},{ignoreService:!0});if(e?.dataType==="base64"){let U=new FileReader;U.onloadend=()=>w(U.result),U.readAsDataURL(R);}else w(R);}catch(R){if(e?.browserCache&&!e?.refresh)try{w(await qe.bind(this)(r,Object.assign({},e,{refresh:!0})));return}catch(U){S(U);return}S(R);}})}function $r(t,e){return `${t||this.service}/${e||this.owner}`}function Ri(t,e){let r=this.__my_unique_ids[t];return r?r[e]:void 0}function La(t,e,r){this.__my_unique_ids[t]||(this.__my_unique_ids[t]={}),this.__my_unique_ids[t][e]=r;}function Sh(t,e){this.__my_unique_ids[t]&&delete this.__my_unique_ids[t][e];}function Ma(t,e){return !e||e.table===void 0?t:Object.assign({},t,{table:e.table})}async function Jt(t){if(await this.__connection,!this.__user&&this.connection?.opt?.require_login===true)throw new f(`This project requires users to sign in before reading its database, so "${t}" is not available to a signed-out visitor.`,{code:"REQUIRE_LOGIN"})}async function qa(t,e=false){t=K(t,{ignoreEmpty:true}).data||{};let r=$r.bind(this)(t?.service,t?.owner),n="",i=xa(t);if(i){if(t=i,n=t.record_id||t.unique_id,typeof n=="string"){typeof this.__private_access_key?.[n]=="string"&&(t.private_key=this.__private_access_key?.[n]||void 0);let s=Ri.bind(this)(r,n);s&&(e?Sh.bind(this)(r,n):t.record_id=s);}}else {let s=await ee.bind(this)(),o=t?.reference,a=false;typeof o=="object"&&Object.keys(o).length&&(o?.record_id||o?.unique_id?(n=o.record_id||o.unique_id,n&&typeof this.__private_access_key?.[n]=="string"&&(t.private_key=this.__private_access_key?.[n]||void 0),t.reference=n):o?.user_id&&(a=o.user_id===this.user?.user_id,t.reference=o.user_id)),typeof t?.table=="string"&&(t.table={name:t.table,access_group:0}),t.index&&t.index.hasOwnProperty("range")&&t.index.hasOwnProperty("condition")&&delete t.index.range;let l=c=>({table:{name:d=>wt(d,"table.name"),access_group:Ai.bind(this),subscription:d=>_.UserId(d,'User ID in "subscription"')},reference:"string",index:{name:["$updated","$uploaded","$referenced_count","$user_id",d=>zt(d,"index.name")],value:d=>{let h={$updated:"number",$uploaded:"number",$referenced_count:"number",$user_id:_.UserId};if(h.hasOwnProperty(c.index.name)){let u=h[c.index.name];if(typeof u=="function")return u(d);if(u!==typeof d)throw new f(`"index.value" should be type: ${u}.`,{code:"INVALID_PARAMETER"});return d}return typeof d=="string"&&!d?"":typeof d=="string"&&wi(c.index.name)?Ei(d,"index.value"):Br(d)},condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq"],range:d=>Ua(d,c)},tag:d=>{if(d==null)return d;if(typeof d=="string")return Vr(d,"tag");throw new f('"tag" should be type: string.',{code:"INVALID_PARAMETER"})},private_key:"string"});t=_.Params(t||{},l(t),a||s?[]:["table"],{ignoreEmpty:true});}return {query:t,is_reference_fetch:n}}async function Va(t,e){await this.__connection,await Jt.call(this,"getRecords");let r=await qa.bind(this)(t),n=r.is_reference_fetch,i=await k.bind(this)("get-records",r.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(Ze.bind(this)(i.list[o]));return i.list=await Promise.all(s),i}function Ti(t){let e="",r=[],n=$r.bind(this)(t?.service,t?.owner),i=_.Params(t||{},{record_id:o=>{let a=typeof o=="string"?Ri.bind(this)(n,o):void 0;return a||ke(o,"record_id",{allowEmpty:false})},unique_id:["string",null],readonly:"boolean",table:{name:o=>wt(o,"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:Ai.bind(this)},notification:o=>{if(o==null)return o;if(typeof o!="object"||Array.isArray(o))throw new f('"notification" should be an object with "title" and "body".',{code:"INVALID_PARAMETER"});for(let a of ["title","body"])if(typeof o[a]!="string"||!o[a].trim())throw new f(`"notification.${a}" is required.`,{code:"INVALID_PARAMETER"});return {title:o.title,body:o.body}},source:{referencing_limit:o=>{if(o===null)return null;if(typeof o=="number"){if(0>o)throw new f('"reference_limit" should be >= 0',{code:"INVALID_PARAMETER"});if(o>4503599627370546)throw new f('"reference_limit" should be <= 4503599627370546',{code:"INVALID_PARAMETER"});return o}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:o=>{if(o===void 0)return;if(!o||Array.isArray(o)&&!o.length)return null;let a={name:c=>zt(c,'"name" in "index_restrictions"'),value:c=>Br(c),condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne",()=>null],range:c=>{if(c!==null&&typeof o.value!=typeof c)throw new f('Index restriction "range" type should match the type of "value".',{code:"INVALID_PARAMETER"});if(!o.hasOwnProperty("value"))throw new f('Index restriction "value" is required.',{code:"INVALID_PARAMETER"});return c}};Array.isArray(o)||(o=[o]);let l=o.map(c=>_.Params(c,a,["name"]));if(l.length)for(let c of l)c.condition&&c.hasOwnProperty("range")&&delete c.range;return l}},reference:o=>{if(o===null)return {record_id:null};if(o){if(typeof o=="string"){e=o;let a=Ri.bind(this)(n,o);return a||o}if(typeof o!="object")throw new f('"reference" should be type: <string | object>.',{code:"INVALID_PARAMETER"});return _.Params(o,{unique_id:"string",record_id:a=>a==null?a:(e=a,typeof this.__private_access_key?.[a]=="string"&&(t.reference_private_key=this.__private_access_key[a]||void 0),ke(a,"reference.record_id",{allowEmpty:false,onlyAlphanumeric:true}))})}},index:[null,{name:o=>zt(o,"index.name"),value:o=>Br(o)}],tags:o=>{if(o==null)return o;if(typeof o=="string"&&(o=o.split(",").map(a=>a.trim())),!Array.isArray(o))throw new f('"tag" should be type: <string | string[]>.',{code:"INVALID_PARAMETER"});return o.map(a=>Vr(a,"tag"))},remove_bin:o=>{if(!o)return null;let a=[];if(Array.isArray(o))for(let l of o)if(typeof l=="string")a.push(l.split("?")[0]);else if(l.url&&l.size&&l.filename){let d=l.url.split("/").slice(0,3).join("/")+"/"+l.path;a.push(d);}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 a},progress:"function",data:o=>o},[],{precall:o=>{let a=o?.data||{};if(!a?.record_id&&!a.table)throw new f('"table.name" is required.',{code:"INVALID_PARAMETER"});typeof a.table=="string"&&(a.table={name:a.table},a?.record_id||(a.table.access_group=0)),o.files&&(r=o.files);}}),s=t.progress||null;if(delete i.progress,!this.__user){let o=!!(i.table?.subscription?.is_subscription_record||i.table?.subscription?.upload_to_feed||i.table?.subscription?.notify_subscribers||i.table?.subscription?.feed_referencing_records||i.table?.subscription?.notify_referencing_records);if(i.record_id)throw new f("Public users cannot update existing records.",{code:"INVALID_REQUEST"});if(i.table.access_group!=="public"&&i.table.access_group!==0)throw new f("Public users can only post records to public tables.",{code:"INVALID_REQUEST"});if(o)throw new f("Public users cannot post subscription records.",{code:"INVALID_REQUEST"});if(i.remove_bin)throw new f("Public users cannot remove files from records.",{code:"INVALID_REQUEST"});if(i.unique_id)throw new f("Public users cannot set unique_id for records.",{code:"INVALID_REQUEST"})}return {config:i,progress:s,is_reference_post:e,files:r}}async function vi(t){if(await this.__connection,!Array.isArray(t)||!t.length)throw new f('"params" should be a non-empty array.',{code:"INVALID_PARAMETER"});let e=[],r,n,i=null,s={},o={},l={_is_bulk_:await Promise.all(t.map(async(p,m)=>{if(!p||typeof p!="object"||Array.isArray(p))throw new f(`"params[${m}]" should be type: <object>.`,{code:"INVALID_PARAMETER"});o[m]={has:p.data!==void 0,value:p.data};let b=Ti.bind(this)(p),y=b.config;if(V.call(this)){let A=Object.prototype.hasOwnProperty.call(y,"data"),w=await si.bind(this)(y.data,Ma(p,y),A);w.encrypted&&(y.data=w.send,s[m]=w.plain);}if(b.is_reference_post&&e.push(b.is_reference_post),typeof y.progress=="function"&&i===null&&(i=y.progress),y.service!==void 0){if(r===void 0)r=y.service;else if(r!==y.service)throw new f('All bulk params should share the same "service" value.',{code:"INVALID_PARAMETER"})}if(y.owner!==void 0){if(n===void 0)n=y.owner;else if(n!==y.owner)throw new f('All bulk params should share the same "owner" value.',{code:"INVALID_PARAMETER"})}return delete y.progress,delete y.service,delete y.owner,y})),service:"",owner:""};r!==void 0&&(l.service=r),n!==void 0&&(l.owner=n);let c={auth:!!this.__user,method:"post"},d={};Object.keys(d).length&&Object.assign(c,{fetchOptions:d});let h=await k.bind(this)("post-record",l,c),u=await Promise.all(h.map((p,m)=>Ze.bind(this)(p,"called from postRecord",o[m]?.has===true,s.hasOwnProperty(m))));for(let p=0;p<u.length;p++)s.hasOwnProperty(p)&&u[p]&&!u[p].error?(u[p].data=s[p],u[p].encrypted={status:"encrypted"}):o[p]?.has&&u[p]&&!h[p]?.error&&Si(h[p]?.data)&&(u[p].data=o[p].value);let g=$r.bind(this)(r,n);for(let p=0;p<h.length;p++){let m=h[p],b=u[p];if(m&&typeof m=="object"&&m.error&&b&&!b.record_id&&(b.error=m.error),typeof m?.reference_private_key=="string")for(let y of e)this.__private_access_key[y]=m.reference_private_key;b?.unique_id&&La.bind(this)(g,b.unique_id,b.record_id);}return u}async function Ii(t,e,r){if(await this.__connection,!e)throw new f('"config" argument is required.',{code:"INVALID_PARAMETER"});let n=Ti.bind(this)(e),i=n.config,s=n.progress,o=n.is_reference_post,a={auth:!!this.__user,method:"post"},l=[],c=K(t);r&&Array.isArray(r)&&r.length&&(l=l.concat(r)),c.files&&Array.isArray(c.files)&&c.files.length&&(l=l.concat(c.files));let d=e?.data!==void 0?e.data:c.data,h=d!==void 0,u=await si.bind(this)(d,Ma(e,i),h),g=null;g=Object.assign({},i),delete g.data,u.omit||(g.data=u.send);let p={};if(typeof s=="function"&&(p.progress=s),Object.keys(p).length&&Object.assign(a,{fetchOptions:p}),u.files==="decrypt"&&e?.record_id){let w=await gi.bind(this)(e.record_id,"decrypt",s);if(w.length){let S=g.remove_bin;g.remove_bin=Array.isArray(S)?S.concat(w):w;}}if(u.spill&&e?.record_id){let w=new FormData;if(w.append(jt,new File([u.spill],"payload.bin",{type:"application/octet-stream"})),await Wt.bind(this)(w,{record_id:e.record_id}),u.retireCt){let S=g.remove_bin,R=[u.retireCt];g.remove_bin=Array.isArray(S)?S.concat(R):R;}}let m=await k.bind(this)("post-record",g,a);if(u.encrypted&&m?.rec&&To.bind(this)(m.rec,u.dek),u.files==="encrypt"&&m?.rec)try{let w=await gi.bind(this)(m.rec,"encrypt",s);w.length&&await Ii.bind(this)(void 0,{record_id:m.rec,remove_bin:w});}catch(w){console.error("Failed to encrypt existing attachments after making the record private:",w);}if(J()&&l.length){let w=new FormData;for(let U of l)w.append(U.name,U.file,U.file.name);let S={record_id:m.rec,progress:s};i.hasOwnProperty("service")&&(S.service=i.service);let{bin_endpoints:R}=await Wt.bind(this)(w,S);m.bin?m.bin.push(...R):m.bin=R;}o&&typeof m?.reference_private_key=="string"&&(this.__private_access_key[o]=m.reference_private_key);let b=!!m&&Si(m.data),y=!u.omit&&u.send!==void 0,A=await Ze.bind(this)(m,"called from postRecord",y,u.encrypted);if(b&&y&&!u.encrypted&&(A.data=u.plain),u.encrypted&&(A.data=u.plain,A.encrypted={status:"encrypted",recipients:Object.keys(u.send.k||{})}),A.unique_id){let w=$r.bind(this)(i?.service,i?.owner);La.bind(this)(w,A.unique_id,A.record_id),J()&&(this.__uniqueIdsPersistTimer!==null&&clearTimeout(this.__uniqueIdsPersistTimer),this.__uniqueIdsPersistTimer=setTimeout(()=>{this.__uniqueIdsPersistTimer=null;try{window.sessionStorage.setItem(`${w}:uniqueids`,JSON.stringify(this.__my_unique_ids[w]||{}));}catch{}},500));}return A}async function Ba(t,e){await Jt.call(this,"getTables");let r=await k.bind(this)("get-table",_.Params(t||{},{table:i=>wt(i,"table",{allowEmpty:true}),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(r?.list))for(let i of r.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=Ae(i.table));}return r}async function ja(t,e){if(await Jt.call(this,"getIndexes"),!t?.table)throw new f('"table" is required.',{code:"INVALID_PARAMETER"});let r=_.Params(t||{},{table:s=>wt(s,"table",{allowEmpty:true}),index:s=>zt(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:s=>{if(t?.order?.by==="index_name"&&typeof s=="string")return ke(s,"order.value",{allowEmpty:true,maxLength:256,blockKeyDelimiters:true});if(typeof s!="string"&&typeof s!="number"&&typeof s!="boolean")throw new f('"order.value" should be type: <string | number | boolean>.',{code:"INVALID_PARAMETER"});return s},condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}},["table"]);if(r.hasOwnProperty("order")){if(!r.order?.by)throw new f('"order.by" is required.',{code:"INVALID_PARAMETER"});if(r.order.hasOwnProperty("condition")&&!r.order.hasOwnProperty("value"))throw new f('"value" is required for "condition".',{code:"INVALID_PARAMETER"});if(r.hasOwnProperty("index")&&r.index.substring(r.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 k.bind(this)("get-index",r,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:Ae(o[1]),index:Ae(o[2]),number_of_records:s.cnt_rec};for(let l in i)Object.prototype.hasOwnProperty.call(s,l)&&(a[i[l]]=s[l]);return a})),n}async function Ka(t,e){await Jt.call(this,"getTags");let r=await k.bind(this)("get-tag",_.Params(t||{},{table:n=>wt(n,"table",{allowEmpty:true}),tag:n=>Vr(n,"tag",{allowEmpty:true}),condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}),Object.assign({auth:!!this.__user},{fetchOptions:e}));return Array.isArray(r?.list)&&(r.list=r.list.map(n=>{let i=n.tag.split("/");return {table:Ae(i[1]),tag:Ae(i[0]),number_of_records:n.cnt_rec}})),r}async function $a(t,e){await Jt.call(this,"getUniqueId");let r=await k.bind(this)("get-uniqueid",_.Params(t||{},{unique_id:"string",condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}),Object.assign({auth:!!this.__user},{fetchOptions:e}));if(Array.isArray(r?.list))for(let n in r.list){let i=r.list[n];r.list[n]={unique_id:i.unq,record_id:i.rec};}return r}async function Ha(t,e){await this.__connection;let r=await qa.bind(this)(t,true),n=r.is_reference_fetch,i=await k.bind(this)("del-records",r.query,{auth:true,fetchOptions:e});return n&&typeof i?.reference_private_key=="string"&&(this.__private_access_key[n]=i.reference_private_key),Array.isArray(i?.list)&&(i.list=await Promise.all(i.list.map(async s=>{if(!s||typeof s!="object")return s;try{return await Ze.bind(this)(s,"called from deleteRecords",!0,!1,!0)}catch{return s}}))),i?.message||i}async function Ga(t){if(V.call(this)){let e=typeof t.user_id=="string"?[t.user_id]:t.user_id;Array.isArray(e)&&e.length&&await hi.bind(this)(t.record_id,e);}return Ya.bind(this)({record_id:t.record_id,user_id:t.user_id,execute:"add"})}async function Wa(t){let e=await Ya.bind(this)({record_id:t.record_id,user_id:t.user_id||null,execute:"remove"});if(V.call(this)){let r=typeof t.user_id=="string"?[t.user_id]:t.user_id;await Vo.bind(this)(t.record_id,Array.isArray(r)&&r.length?r:null);}return e}async function za(t,e){let r={record_id:t.record_id||void 0,user_id:t.user_id||void 0,execute:"list"};if(!r.record_id&&!r.user_id)throw new f("Either record_id or user_id must be provided.",{code:"INVALID_PARAMETER"});if(r.user_id)if(typeof r.user_id=="string")_.UserId(r.user_id),r.user_id=[r.user_id];else if(Array.isArray(r.user_id))for(let s of r.user_id)_.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 k.bind(this)("grant-private-access",r,{auth:true,fetchOptions:e});return i.list=i.list.map(n),i}function Ja(t){let e=t.record_id,r=t.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(r&&typeof r!="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(jr[e])return jr[e];let n=k.bind(this)("request-private-access-key",{record_id:e,reference_id:r},{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 jr[e];});return jr[e]=n,n}function Ya(t){t.execute;let r=_.Params(t,{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)_.UserId(s,'User ID in "user_id"');return i},execute:["add","remove"]},["execute","record_id","user_id"]);return r.user_id||(r.user_id=null),k.bind(this)("grant-private-access",r,{auth:true})}var Th=100;async function Qa(t){if(await this.__connection,!Array.isArray(t)||!t.length)throw new f('"items" should be a non-empty array.',{code:"INVALID_PARAMETER"});let e=[],r=[],n=[];for(let s=0;s<t.length;s++){let o=t[s];try{if(!o||typeof o!="object"||Array.isArray(o))throw new f(`"items[${s}]" should be an object with "config".`,{code:"INVALID_PARAMETER"});let a=o.config;if(!a||typeof a!="object"||Array.isArray(a))throw new f(`"items[${s}].config" is required.`,{code:"INVALID_PARAMETER"});Ti.bind(this)(Object.assign({},a));let l=Object.assign({},a);delete l.data;let c=a.data!==void 0?a.data:o.data;if(c!==void 0){let d=c!==null&&typeof c=="object"?K(c):{data:c,files:[]};if(d.files&&d.files.length)throw new f(`"items[${s}].data" carries files. postRecords() does not attach files; use uploadFiles() on the saved record.`,{code:"INVALID_PARAMETER"});l.data=d.data;}n.push({index:s,config:l});}catch(a){r.push({index:s,code:String(a?.code||"INVALID_PARAMETER"),message:String(a?.message||a)});}}let i=0;for(;i<n.length;){let s=n.slice(i,i+Th),o=await vi.bind(this)(s.map(l=>Object.assign({},l.config)));if(!Array.isArray(o)||!o.length){for(let l of s)r.push({index:l.index,code:"ERROR",message:"The server answered nothing for this record."});i+=s.length;continue}let a=Math.min(o.length,s.length);for(let l=0;l<a;l++){let c=o[l];if(c&&c.record_id)e.push(c);else {let d=c?.error||{};r.push({index:s[l].index,code:String(d.code||"ERROR"),message:String(d.message||"The record was not saved.")});}}i+=a;}return r.sort((s,o)=>s.index-o.index),{list:e,failed:r}}var F={},Q={},Re={},Ue={},xe={},Hr={},Gr={};function Xa(t,e,r){t[e]||(t[e]=[]),t[e].push(r);}async function Wr(t,e,r){let n=[];if(t[e]){for(let i of t[e])if(i){let s=r(i);s instanceof Promise&&(s=await s),n.push(s);}delete t[e];}return n}var Pi="stun:stun.skapi.com:3468";async function Za(){let t=ol();if(!t)try{t=await Ui.bind(this)();}catch{t=null;}let e=t?t.servers:[{urls:Pi}];return e.some(r=>(Array.isArray(r.urls)?r.urls:[r.urls]).some(n=>/^stuns?:/.test(n)))?e:[{urls:Pi},...e]}function el(t){if(t==null||t==="")return [{urls:Pi}];let e=r=>typeof r=="string"&&/^(stun|stuns|turn|turns):/.test(r);if(typeof t=="string"){if(!e(t))throw new f('"ice" should be a "stun:", "stuns:", "turn:" or "turns:" url, or a list of { urls, username, credential }.',{code:"INVALID_PARAMETER"});return [{urls:t}]}if(!Array.isArray(t)||!t.length)throw new f('"ice" should be a url string, or a non-empty list of { urls, username, credential }.',{code:"INVALID_PARAMETER"});return t.map((r,n)=>{if(!r||typeof r!="object"||Array.isArray(r))throw new f(`"ice[${n}]" should be an object: { urls, username, credential }.`,{code:"INVALID_PARAMETER"});let i=r.urls,s=Array.isArray(i)?i:[i];if(!s.length||!s.every(e))throw new f(`"ice[${n}].urls" should be a "stun:", "stuns:", "turn:" or "turns:" url, or a list of them.`,{code:"INVALID_PARAMETER"});let o={urls:i};for(let a of ["username","credential"])if(r[a]!==void 0){if(typeof r[a]!="string")throw new f(`"ice[${n}].${a}" should be type: <string>.`,{code:"INVALID_PARAMETER"});o[a]=r[a];}if(s.some(a=>/^turns?:/.test(a))&&(!o.username||!o.credential))throw new f(`"ice[${n}]" is a TURN server: it needs "username" and "credential".`,{code:"INVALID_PARAMETER"});return o})}async function xi(t,e){if(!this?.session?.accessToken?.jwtToken)throw new f("Access token is required.",{code:"INVALID_PARAMETER"});let r=await this.__socket;async function n(i,s,o){this.log("answerSdpOffer from",s),await F[s].setRemoteDescription(new RTCSessionDescription(i));let a=await F[s].createAnswer();await F[s].setLocalDescription(a),o.send(JSON.stringify({action:"rtc",uid:s,content:{sdpanswer:a},token:this.session.accessToken.jwtToken}));}F?.[e]?t?(await Wr(Gr,e,i=>n.bind(this)(i,e,r)),await n.bind(this)(t,e,r)):await Wr(Gr,e,i=>n.bind(this)(i,e,r)):t&&Xa(Gr,e,t);}async function zr(t,e){if(this.log("receiveIceCandidate",t),F?.[e]&&F[e]?.remoteDescription&&F[e]?.remoteDescription?.type){if(!t)return Wr(Hr,e,r=>F[e].addIceCandidate(r));await Wr(Hr,e,r=>F[e].addIceCandidate(r)),await F[e].addIceCandidate(t);}else Xa(Hr,e,t);}async function Se(t){if(typeof window>"u"||window._runningInNodeJS)throw new f("WebRTC is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});_.Params(t,{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:r,close_all:n=false}=t||{};if(!n&&!r)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 Gr[s],delete Hr[s],Q[s]&&Object.values(Q[s]).forEach(o=>{o.readyState!=="closed"&&o.close();}),delete Q[s],F?.[s]){F[s].connectionState!=="closed"&&(F[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:F[s],timestamp:new Date().toISOString(),state:F[s].connectionState,iceState:F[s].iceConnectionState,signalingState:F[s].signalingState};xe[s]&&xe[s](o),this.log("closeRTC",o);}delete xe[s],delete Ue[s],delete Re[s],delete F[s];};if(n)for(let s in F)i(s);else i(r);this.log("Cleaning up media stream..."),this.__mediaStream&&(this.__mediaStream.getTracks().forEach(s=>{s.stop();}),this.__mediaStream=null);}async function tl(t){if(t instanceof MediaStream)return t;if(!t.video&&!t.audio){let e=new MediaStream,r=document.createElement("canvas");r.width=1,r.height=1;let i=r.captureStream().getVideoTracks()[0];return e.addTrack(i),e}return window.navigator.mediaDevices.getUserMedia(t)}async function rl(t,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"});t=_.Params(t,{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:o=>o,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:r,ice:n}=t;if(!(t?.media instanceof MediaStream)&&(t?.media?.video||t?.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:n==null||n===""?await Za.bind(this)():el(n)};F?.[r]||(F[r]=new RTCPeerConnection(s)),t?.media&&(this.__mediaStream=await tl(t.media),this.__mediaStream.getTracks().forEach(o=>{F[r].addTrack(o,this.__mediaStream);})),xe[r]=e,Q[r]||(Q[r]={});for(let o=0;o<t.channels.length;o++){let a=t.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 l=a.protocol||"default";if(Object.keys(Q[r]).includes(l))throw new f(`Data channel with the protocol "${l}" already exists.`,{code:"INVALID_REQUEST"});let c=F[r].createDataChannel(l,a);Q[r][l]=c;}for(let o in Q[r]){let a=Q[r][o];sl.bind(this)(r,a);}return il.bind(this)(r,["onnegotiationneeded"]),await ki.bind(this)(r),{hangup:()=>Re[r]&&Re[r](false),connection:new Promise(o=>{Re[r]=(a=>{if(this.log("receiver picked up the call",r),!a)return Se.bind(this)({cid:r}),null;F[r].onnegotiationneeded=()=>{this.log("onnegotiationneeded",`sending offer to "${r}".`),ki.bind(this)(r),xe[r]&&xe[r]({type:"negotiationneeded",target:F[r],timestamp:new Date().toISOString(),signalingState:F[r].signalingState,connectionState:F[r].iceConnectionState,gatheringState:F[r].iceGatheringState});},o({target:F[r],channels:Q[r],hangup:()=>Se.bind(this)({cid:r}),media:this.__mediaStream});}).bind(this);})}}function nl(t){return async(e,r)=>{e=e||{},e=K(e).data;let n=t.sender_cid,i=await this.__socket;if(!Ue[n])return null;if(typeof r!="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 s=e.ice===void 0||e.ice===null||e.ice===""?await Za.bind(this)():el(e.ice);return F?.[n]||(F[n]=new RTCPeerConnection({iceServers:s})),e?.media&&(this.__mediaStream=await tl(e.media),this.__mediaStream.getTracks().forEach(o=>{F[n].addTrack(o,this.__mediaStream);})),delete Ue[n],xe[n]=r,Q[n]||(Q[n]={}),F[n].ondatachannel=o=>{this.log("ondatachannel",`received data channel "${o.channel.label}".`);let a=o.channel;Q[n][a.label]=a,sl.bind(this)(n,a);},il.bind(this)(n,["onnegotiationneeded"]),await xi.bind(this)(null,n),await zr.bind(this)(null,n),i.send(JSON.stringify({action:"rtc",uid:n,content:{pickup:this.user.user_id},token:this.session.accessToken.jwtToken})),{target:F[n],channels:Q[n],hangup:()=>Se.bind(this)({cid:n}),media:this.__mediaStream}}}async function ki(t){if(!this?.session?.accessToken?.jwtToken)throw new f("Access token is required.",{code:"INVALID_PARAMETER"});this.log("sendOffer",t);let e=await this.__socket,r=await F[t].createOffer();await F[t].setLocalDescription(r);let n=F[t].localDescription;this.log("rtcSdpOffer to",n),e.send(JSON.stringify({action:"rtc",uid:t,content:{sdpoffer:n},token:this.session.accessToken.jwtToken}));}async function vh(t,e){if(!this?.session?.accessToken?.jwtToken)throw new f("Access token is required.",{code:"INVALID_PARAMETER"});this.log("sendIceCandidate to",e);let r=await this.__socket;if(!t.candidate){this.log("candidate-end","all ice candidates have been sent");return}let n=xe[e]||(()=>{}),i=t.candidate;this.log("ice gathering state set to",F[e].iceGatheringState),n({type:"icecandidate",target:F[e],timestamp:new Date().toISOString(),candidate:t.candidate.candidate,sdpMid:t.candidate.sdpMid,sdpMLineIndex:t.candidate.sdpMLineIndex,usernameFragment:t.candidate.usernameFragment,protocol:t.candidate.protocol,gatheringState:F[e].iceGatheringState,connectionState:F[e].iceConnectionState}),r.send(JSON.stringify({action:"rtc",uid:e,content:{candidate:i},token:this.session.accessToken.jwtToken}));}function il(t,e){let r=new Set(e),n=xe[t]||(o=>{}),i=F[t],s={ontrack:o=>{n({type:"track",target:i,timeStamp:o.timeStamp,streams:o.streams,track:o.track});},onicecandidate:o=>{vh.bind(this)(o,t),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:()=>{ki.bind(this)(t),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")&&Se.bind(this)({cid:t});}};for(let[o,a]of Object.entries(s))r.has(o)||(i[o]=a);}function sl(t,e,r){let n=new Set(r),i=xe[t]||(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),Q[t]&&(delete Q[t][e.label],Object.keys(Q[t]).length===0&&Se.bind(this)({cid:t}));},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 St=[],At=null;function al(t){return t&&Array.isArray(t.servers)&&t.servers.length?{servers:t.servers,expires:typeof t.expires=="number"?t.expires:null}:null}function ol(){if(!At)return null;let t=Math.floor(Date.now()/1e3);return (At.expires??At.at+3600)-60>t?{servers:At.servers,expires:At.expires}:null}async function Ui(t=2500,e){let r=e||(this.__socket?await this.__socket:null);return !r||r.readyState!==1||!this?.session?.accessToken?.jwtToken?null:new Promise(n=>{let i=false,s=setTimeout(()=>{i||(i=true,St=St.filter(a=>a!==o),n(null));},t),o=a=>{i||(i=true,clearTimeout(s),n(al(a)));};St.push(o);try{r.send(JSON.stringify({action:"ice",token:this.session.accessToken.jwtToken}));}catch{o(null);}})}var Ve;function ll(){return Ve}var Ge=null,Yt=true,Rt=0;async function Ih(){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 t=await this.record_endpoint;return new WebSocket(t.websocket_private+"?token="+this.session.accessToken.jwtToken)}var Ci=null;async function Jr(){if(typeof window>"u"||window._runningInNodeJS)throw new f("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});Yt=true;let t=this.__socket?await this.__socket:this.__socket;Se.bind(this)({close_all:true}),Ve&&vt.bind(this)({group:null}),Rt=0,Ge&&(Ge.terminate(),Ge=null);try{t&&t.close();}catch{}return window.removeEventListener("visibilitychange",Ci),this.__socket=null,null}async function Tt(t,e=50,r){if(typeof window>"u"||window._runningInNodeJS)throw new f("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(typeof t!="function")throw new f("Callback must be a function.",{code:"INVALID_REQUEST"});if(r==="reconnect"){if(this.__socket instanceof Promise){let i=await this.__socket;if(i.readyState!==WebSocket.CLOSED&&i.readyState!==WebSocket.CLOSING)return this.__socket}}else if(Yt&&(Ci=()=>{!document.hidden&&!Yt&&Tt.bind(this)(t,0,"reconnect");},this.__socket instanceof Promise))return this.__socket;Ge&&(Ge.terminate(),Ge=null);let n={value:null};return this.__socket=new Promise(async(i,s)=>{let o=a=>{this.__socket===n.value&&(this.__socket=null),s(a);};try{await bt.bind(this)();}catch(a){o(a);return}setTimeout(async()=>{try{let a=await Ih.bind(this)();a.onopen=()=>{Yt=!1,Rt=0,r!=="reconnect"&&window.addEventListener("visibilitychange",Ci),this.log("realtime onopen","Connected to WebSocket server."),t({type:"success",message:"Connected to WebSocket server."}),Ve&&a.send(JSON.stringify({action:"joinRoom",rid:Ve,token:this.session.accessToken.jwtToken})),Ui.bind(this)(5e3,a).catch(()=>null);let l=`
|
|
206
|
+
var ru=Object.create;var it=Object.defineProperty;var Zi=Object.getOwnPropertyDescriptor;var nu=Object.getOwnPropertyNames;var iu=Object.getPrototypeOf,su=Object.prototype.hasOwnProperty;var ou=(t,e,r)=>e in t?it(t,e,{enumerable:true,configurable:true,writable:true,value:r}):t[e]=r;var He=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var st=(t,e)=>()=>(t&&(e=t(t=0)),e);var ce=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),ur=(t,e)=>{for(var r in e)it(t,r,{get:e[r],enumerable:true});},es=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of nu(e))!su.call(t,i)&&i!==r&&it(t,i,{get:()=>e[i],enumerable:!(n=Zi(e,i))||n.enumerable});return t};var ot=(t,e,r)=>(r=t!=null?ru(iu(t)):{},es(!t||!t.__esModule?it(r,"default",{value:t,enumerable:true}):r,t)),at=t=>es(it({},"__esModule",{value:true}),t),k=(t,e,r,n)=>{for(var i=Zi(e,r),s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(o(e,r,i))||i);return i&&it(e,r,i),i};var xe=(t,e,r)=>ou(t,typeof e!="symbol"?e+"":e,r);var ns=ce(fr=>{fr.byteLength=lu;fr.toByteArray=du;fr.fromByteArray=pu;var Ue=[],me=[],cu=typeof Uint8Array<"u"?Uint8Array:Array,mn="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(Qe=0,ts=mn.length;Qe<ts;++Qe)Ue[Qe]=mn[Qe],me[mn.charCodeAt(Qe)]=Qe;var Qe,ts;me[45]=62;me[95]=63;function rs(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");r===-1&&(r=e);var n=r===e?0:4-r%4;return [r,n]}function lu(t){var e=rs(t),r=e[0],n=e[1];return (r+n)*3/4-n}function uu(t,e,r){return (e+r)*3/4-r}function du(t){var e,r=rs(t),n=r[0],i=r[1],s=new cu(uu(t,n,i)),o=0,a=i>0?n-4:n,c;for(c=0;c<a;c+=4)e=me[t.charCodeAt(c)]<<18|me[t.charCodeAt(c+1)]<<12|me[t.charCodeAt(c+2)]<<6|me[t.charCodeAt(c+3)],s[o++]=e>>16&255,s[o++]=e>>8&255,s[o++]=e&255;return i===2&&(e=me[t.charCodeAt(c)]<<2|me[t.charCodeAt(c+1)]>>4,s[o++]=e&255),i===1&&(e=me[t.charCodeAt(c)]<<10|me[t.charCodeAt(c+1)]<<4|me[t.charCodeAt(c+2)]>>2,s[o++]=e>>8&255,s[o++]=e&255),s}function fu(t){return Ue[t>>18&63]+Ue[t>>12&63]+Ue[t>>6&63]+Ue[t&63]}function hu(t,e,r){for(var n,i=[],s=e;s<r;s+=3)n=(t[s]<<16&16711680)+(t[s+1]<<8&65280)+(t[s+2]&255),i.push(fu(n));return i.join("")}function pu(t){for(var e,r=t.length,n=r%3,i=[],s=16383,o=0,a=r-n;o<a;o+=s)i.push(hu(t,o,o+s>a?a:o+s));return n===1?(e=t[r-1],i.push(Ue[e>>2]+Ue[e<<4&63]+"==")):n===2&&(e=(t[r-2]<<8)+t[r-1],i.push(Ue[e>>10]+Ue[e>>4&63]+Ue[e<<2&63]+"=")),i.join("")}});var is=ce(yn=>{yn.read=function(t,e,r,n,i){var s,o,a=i*8-n-1,c=(1<<a)-1,l=c>>1,d=-7,h=r?i-1:0,u=r?-1:1,p=t[e+h];for(h+=u,s=p&(1<<-d)-1,p>>=-d,d+=a;d>0;s=s*256+t[e+h],h+=u,d-=8);for(o=s&(1<<-d)-1,s>>=-d,d+=n;d>0;o=o*256+t[e+h],h+=u,d-=8);if(s===0)s=1-l;else {if(s===c)return o?NaN:(p?-1:1)*(1/0);o=o+Math.pow(2,n),s=s-l;}return (p?-1:1)*o*Math.pow(2,s-n)};yn.write=function(t,e,r,n,i,s){var o,a,c,l=s*8-i-1,d=(1<<l)-1,h=d>>1,u=i===23?Math.pow(2,-24)-Math.pow(2,-77):0,p=n?0:s-1,g=n?1:-1,m=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*(c=Math.pow(2,-o))<1&&(o--,c*=2),o+h>=1?e+=u/c:e+=u*Math.pow(2,1-h),e*c>=2&&(o++,c/=2),o+h>=d?(a=0,o=d):o+h>=1?(a=(e*c-1)*Math.pow(2,i),o=o+h):(a=e*Math.pow(2,h-1)*Math.pow(2,i),o=0));i>=8;t[r+p]=a&255,p+=g,a/=256,i-=8);for(o=o<<i|a,l+=i;l>0;t[r+p]=o&255,p+=g,o/=256,l-=8);t[r+p-g]|=m*128;};});var os=ce((Up,ss)=>{var gu={}.toString;ss.exports=Array.isArray||function(t){return gu.call(t)=="[object Array]"};});var br=ce(ut=>{var bn=ns(),lt=is(),ls=os();ut.Buffer=A;ut.SlowBuffer=Eu;ut.INSPECT_MAX_BYTES=50;A.TYPED_ARRAY_SUPPORT=globalThis.TYPED_ARRAY_SUPPORT!==void 0?globalThis.TYPED_ARRAY_SUPPORT:mu();ut.kMaxLength=hr();function mu(){try{var t=new Uint8Array(1);return t.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},t.foo()===42&&typeof t.subarray=="function"&&t.subarray(1,1).byteLength===0}catch{return false}}function hr(){return A.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function Me(t,e){if(hr()<e)throw new RangeError("Invalid typed array length");return A.TYPED_ARRAY_SUPPORT?(t=new Uint8Array(e),t.__proto__=A.prototype):(t===null&&(t=new A(e)),t.length=e),t}function A(t,e,r){if(!A.TYPED_ARRAY_SUPPORT&&!(this instanceof A))return new A(t,e,r);if(typeof t=="number"){if(typeof e=="string")throw new Error("If encoding is specified then the first argument must be a string");return wn(this,t)}return us(this,t,e,r)}A.poolSize=8192;A._augment=function(t){return t.__proto__=A.prototype,t};function us(t,e,r,n){if(typeof e=="number")throw new TypeError('"value" argument must not be a number');return typeof ArrayBuffer<"u"&&e instanceof ArrayBuffer?_u(t,e,r,n):typeof e=="string"?bu(t,e,r):wu(t,e)}A.from=function(t,e,r){return us(null,t,e,r)};A.TYPED_ARRAY_SUPPORT&&(A.prototype.__proto__=Uint8Array.prototype,A.__proto__=Uint8Array,typeof Symbol<"u"&&Symbol.species&&A[Symbol.species]===A&&Object.defineProperty(A,Symbol.species,{value:null,configurable:true}));function ds(t){if(typeof t!="number")throw new TypeError('"size" argument must be a number');if(t<0)throw new RangeError('"size" argument must not be negative')}function yu(t,e,r,n){return ds(e),e<=0?Me(t,e):r!==void 0?typeof n=="string"?Me(t,e).fill(r,n):Me(t,e).fill(r):Me(t,e)}A.alloc=function(t,e,r){return yu(null,t,e,r)};function wn(t,e){if(ds(e),t=Me(t,e<0?0:En(e)|0),!A.TYPED_ARRAY_SUPPORT)for(var r=0;r<e;++r)t[r]=0;return t}A.allocUnsafe=function(t){return wn(null,t)};A.allocUnsafeSlow=function(t){return wn(null,t)};function bu(t,e,r){if((typeof r!="string"||r==="")&&(r="utf8"),!A.isEncoding(r))throw new TypeError('"encoding" must be a valid string encoding');var n=fs(e,r)|0;t=Me(t,n);var i=t.write(e,r);return i!==n&&(t=t.slice(0,i)),t}function _n(t,e){var r=e.length<0?0:En(e.length)|0;t=Me(t,r);for(var n=0;n<r;n+=1)t[n]=e[n]&255;return t}function _u(t,e,r,n){if(e.byteLength,r<0||e.byteLength<r)throw new RangeError("'offset' is out of bounds");if(e.byteLength<r+(n||0))throw new RangeError("'length' is out of bounds");return r===void 0&&n===void 0?e=new Uint8Array(e):n===void 0?e=new Uint8Array(e,r):e=new Uint8Array(e,r,n),A.TYPED_ARRAY_SUPPORT?(t=e,t.__proto__=A.prototype):t=_n(t,e),t}function wu(t,e){if(A.isBuffer(e)){var r=En(e.length)|0;return t=Me(t,r),t.length===0||e.copy(t,0,0,r),t}if(e){if(typeof ArrayBuffer<"u"&&e.buffer instanceof ArrayBuffer||"length"in e)return typeof e.length!="number"||Vu(e.length)?Me(t,0):_n(t,e);if(e.type==="Buffer"&&ls(e.data))return _n(t,e.data)}throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")}function En(t){if(t>=hr())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+hr().toString(16)+" bytes");return t|0}function Eu(t){return +t!=t&&(t=0),A.alloc(+t)}A.isBuffer=function(e){return !!(e!=null&&e._isBuffer)};A.compare=function(e,r){if(!A.isBuffer(e)||!A.isBuffer(r))throw new TypeError("Arguments must be Buffers");if(e===r)return 0;for(var n=e.length,i=r.length,s=0,o=Math.min(n,i);s<o;++s)if(e[s]!==r[s]){n=e[s],i=r[s];break}return n<i?-1:i<n?1:0};A.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}};A.concat=function(e,r){if(!ls(e))throw new TypeError('"list" argument must be an Array of Buffers');if(e.length===0)return A.alloc(0);var n;if(r===void 0)for(r=0,n=0;n<e.length;++n)r+=e[n].length;var i=A.allocUnsafe(r),s=0;for(n=0;n<e.length;++n){var o=e[n];if(!A.isBuffer(o))throw new TypeError('"list" argument must be an Array of Buffers');o.copy(i,s),s+=o.length;}return i};function fs(t,e){if(A.isBuffer(t))return t.length;if(typeof ArrayBuffer<"u"&&typeof ArrayBuffer.isView=="function"&&(ArrayBuffer.isView(t)||t instanceof ArrayBuffer))return t.byteLength;typeof t!="string"&&(t=""+t);var r=t.length;if(r===0)return 0;for(var n=false;;)switch(e){case "ascii":case "latin1":case "binary":return r;case "utf8":case "utf-8":case void 0:return pr(t).length;case "ucs2":case "ucs-2":case "utf16le":case "utf-16le":return r*2;case "hex":return r>>>1;case "base64":return _s(t).length;default:if(n)return pr(t).length;e=(""+e).toLowerCase(),n=true;}}A.byteLength=fs;function Au(t,e,r){var n=false;if((e===void 0||e<0)&&(e=0),e>this.length||((r===void 0||r>this.length)&&(r=this.length),r<=0)||(r>>>=0,e>>>=0,r<=e))return "";for(t||(t="utf8");;)switch(t){case "hex":return Uu(this,e,r);case "utf8":case "utf-8":return gs(this,e,r);case "ascii":return Cu(this,e,r);case "latin1":case "binary":return xu(this,e,r);case "base64":return Pu(this,e,r);case "ucs2":case "ucs-2":case "utf16le":case "utf-16le":return Du(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=true;}}A.prototype._isBuffer=true;function Xe(t,e,r){var n=t[e];t[e]=t[r],t[r]=n;}A.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 r=0;r<e;r+=2)Xe(this,r,r+1);return this};A.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 r=0;r<e;r+=4)Xe(this,r,r+3),Xe(this,r+1,r+2);return this};A.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 r=0;r<e;r+=8)Xe(this,r,r+7),Xe(this,r+1,r+6),Xe(this,r+2,r+5),Xe(this,r+3,r+4);return this};A.prototype.toString=function(){var e=this.length|0;return e===0?"":arguments.length===0?gs(this,0,e):Au.apply(this,arguments)};A.prototype.equals=function(e){if(!A.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e?true:A.compare(this,e)===0};A.prototype.inspect=function(){var e="",r=ut.INSPECT_MAX_BYTES;return this.length>0&&(e=this.toString("hex",0,r).match(/.{2}/g).join(" "),this.length>r&&(e+=" ... ")),"<Buffer "+e+">"};A.prototype.compare=function(e,r,n,i,s){if(!A.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(r===void 0&&(r=0),n===void 0&&(n=e?e.length:0),i===void 0&&(i=0),s===void 0&&(s=this.length),r<0||n>e.length||i<0||s>this.length)throw new RangeError("out of range index");if(i>=s&&r>=n)return 0;if(i>=s)return -1;if(r>=n)return 1;if(r>>>=0,n>>>=0,i>>>=0,s>>>=0,this===e)return 0;for(var o=s-i,a=n-r,c=Math.min(o,a),l=this.slice(i,s),d=e.slice(r,n),h=0;h<c;++h)if(l[h]!==d[h]){o=l[h],a=d[h];break}return o<a?-1:a<o?1:0};function hs(t,e,r,n,i){if(t.length===0)return -1;if(typeof r=="string"?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,isNaN(r)&&(r=i?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(i)return -1;r=t.length-1;}else if(r<0)if(i)r=0;else return -1;if(typeof e=="string"&&(e=A.from(e,n)),A.isBuffer(e))return e.length===0?-1:as(t,e,r,n,i);if(typeof e=="number")return e=e&255,A.TYPED_ARRAY_SUPPORT&&typeof Uint8Array.prototype.indexOf=="function"?i?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):as(t,[e],r,n,i);throw new TypeError("val must be string, number or Buffer")}function as(t,e,r,n,i){var s=1,o=t.length,a=e.length;if(n!==void 0&&(n=String(n).toLowerCase(),n==="ucs2"||n==="ucs-2"||n==="utf16le"||n==="utf-16le")){if(t.length<2||e.length<2)return -1;s=2,o/=2,a/=2,r/=2;}function c(p,g){return s===1?p[g]:p.readUInt16BE(g*s)}var l;if(i){var d=-1;for(l=r;l<o;l++)if(c(t,l)===c(e,d===-1?0:l-d)){if(d===-1&&(d=l),l-d+1===a)return d*s}else d!==-1&&(l-=l-d),d=-1;}else for(r+a>o&&(r=o-a),l=r;l>=0;l--){for(var h=true,u=0;u<a;u++)if(c(t,l+u)!==c(e,u)){h=false;break}if(h)return l}return -1}A.prototype.includes=function(e,r,n){return this.indexOf(e,r,n)!==-1};A.prototype.indexOf=function(e,r,n){return hs(this,e,r,n,true)};A.prototype.lastIndexOf=function(e,r,n){return hs(this,e,r,n,false)};function Ru(t,e,r,n){r=Number(r)||0;var i=t.length-r;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;t[r+o]=a;}return o}function Tu(t,e,r,n){return yr(pr(e,t.length-r),t,r,n)}function ps(t,e,r,n){return yr(Mu(e),t,r,n)}function Su(t,e,r,n){return ps(t,e,r,n)}function vu(t,e,r,n){return yr(_s(e),t,r,n)}function Iu(t,e,r,n){return yr(qu(e,t.length-r),t,r,n)}A.prototype.write=function(e,r,n,i){if(r===void 0)i="utf8",n=this.length,r=0;else if(n===void 0&&typeof r=="string")i=r,n=this.length,r=0;else if(isFinite(r))r=r|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-r;if((n===void 0||n>s)&&(n=s),e.length>0&&(n<0||r<0)||r>this.length)throw new RangeError("Attempt to write outside buffer bounds");i||(i="utf8");for(var o=false;;)switch(i){case "hex":return Ru(this,e,r,n);case "utf8":case "utf-8":return Tu(this,e,r,n);case "ascii":return ps(this,e,r,n);case "latin1":case "binary":return Su(this,e,r,n);case "base64":return vu(this,e,r,n);case "ucs2":case "ucs-2":case "utf16le":case "utf-16le":return Iu(this,e,r,n);default:if(o)throw new TypeError("Unknown encoding: "+i);i=(""+i).toLowerCase(),o=true;}};A.prototype.toJSON=function(){return {type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function Pu(t,e,r){return e===0&&r===t.length?bn.fromByteArray(t):bn.fromByteArray(t.slice(e,r))}function gs(t,e,r){r=Math.min(t.length,r);for(var n=[],i=e;i<r;){var s=t[i],o=null,a=s>239?4:s>223?3:s>191?2:1;if(i+a<=r){var c,l,d,h;switch(a){case 1:s<128&&(o=s);break;case 2:c=t[i+1],(c&192)===128&&(h=(s&31)<<6|c&63,h>127&&(o=h));break;case 3:c=t[i+1],l=t[i+2],(c&192)===128&&(l&192)===128&&(h=(s&15)<<12|(c&63)<<6|l&63,h>2047&&(h<55296||h>57343)&&(o=h));break;case 4:c=t[i+1],l=t[i+2],d=t[i+3],(c&192)===128&&(l&192)===128&&(d&192)===128&&(h=(s&15)<<18|(c&63)<<12|(l&63)<<6|d&63,h>65535&&h<1114112&&(o=h));}}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 ku(n)}var cs=4096;function ku(t){var e=t.length;if(e<=cs)return String.fromCharCode.apply(String,t);for(var r="",n=0;n<e;)r+=String.fromCharCode.apply(String,t.slice(n,n+=cs));return r}function Cu(t,e,r){var n="";r=Math.min(t.length,r);for(var i=e;i<r;++i)n+=String.fromCharCode(t[i]&127);return n}function xu(t,e,r){var n="";r=Math.min(t.length,r);for(var i=e;i<r;++i)n+=String.fromCharCode(t[i]);return n}function Uu(t,e,r){var n=t.length;(!e||e<0)&&(e=0),(!r||r<0||r>n)&&(r=n);for(var i="",s=e;s<r;++s)i+=Lu(t[s]);return i}function Du(t,e,r){for(var n=t.slice(e,r),i="",s=0;s<n.length;s+=2)i+=String.fromCharCode(n[s]+n[s+1]*256);return i}A.prototype.slice=function(e,r){var n=this.length;e=~~e,r=r===void 0?n:~~r,e<0?(e+=n,e<0&&(e=0)):e>n&&(e=n),r<0?(r+=n,r<0&&(r=0)):r>n&&(r=n),r<e&&(r=e);var i;if(A.TYPED_ARRAY_SUPPORT)i=this.subarray(e,r),i.__proto__=A.prototype;else {var s=r-e;i=new A(s,void 0);for(var o=0;o<s;++o)i[o]=this[o+e];}return i};function Q(t,e,r){if(t%1!==0||t<0)throw new RangeError("offset is not uint");if(t+e>r)throw new RangeError("Trying to access beyond buffer length")}A.prototype.readUIntLE=function(e,r,n){e=e|0,r=r|0,n||Q(e,r,this.length);for(var i=this[e],s=1,o=0;++o<r&&(s*=256);)i+=this[e+o]*s;return i};A.prototype.readUIntBE=function(e,r,n){e=e|0,r=r|0,n||Q(e,r,this.length);for(var i=this[e+--r],s=1;r>0&&(s*=256);)i+=this[e+--r]*s;return i};A.prototype.readUInt8=function(e,r){return r||Q(e,1,this.length),this[e]};A.prototype.readUInt16LE=function(e,r){return r||Q(e,2,this.length),this[e]|this[e+1]<<8};A.prototype.readUInt16BE=function(e,r){return r||Q(e,2,this.length),this[e]<<8|this[e+1]};A.prototype.readUInt32LE=function(e,r){return r||Q(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+this[e+3]*16777216};A.prototype.readUInt32BE=function(e,r){return r||Q(e,4,this.length),this[e]*16777216+(this[e+1]<<16|this[e+2]<<8|this[e+3])};A.prototype.readIntLE=function(e,r,n){e=e|0,r=r|0,n||Q(e,r,this.length);for(var i=this[e],s=1,o=0;++o<r&&(s*=256);)i+=this[e+o]*s;return s*=128,i>=s&&(i-=Math.pow(2,8*r)),i};A.prototype.readIntBE=function(e,r,n){e=e|0,r=r|0,n||Q(e,r,this.length);for(var i=r,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*r)),o};A.prototype.readInt8=function(e,r){return r||Q(e,1,this.length),this[e]&128?(255-this[e]+1)*-1:this[e]};A.prototype.readInt16LE=function(e,r){r||Q(e,2,this.length);var n=this[e]|this[e+1]<<8;return n&32768?n|4294901760:n};A.prototype.readInt16BE=function(e,r){r||Q(e,2,this.length);var n=this[e+1]|this[e]<<8;return n&32768?n|4294901760:n};A.prototype.readInt32LE=function(e,r){return r||Q(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24};A.prototype.readInt32BE=function(e,r){return r||Q(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]};A.prototype.readFloatLE=function(e,r){return r||Q(e,4,this.length),lt.read(this,e,true,23,4)};A.prototype.readFloatBE=function(e,r){return r||Q(e,4,this.length),lt.read(this,e,false,23,4)};A.prototype.readDoubleLE=function(e,r){return r||Q(e,8,this.length),lt.read(this,e,true,52,8)};A.prototype.readDoubleBE=function(e,r){return r||Q(e,8,this.length),lt.read(this,e,false,52,8)};function le(t,e,r,n,i,s){if(!A.isBuffer(t))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(r+n>t.length)throw new RangeError("Index out of range")}A.prototype.writeUIntLE=function(e,r,n,i){if(e=+e,r=r|0,n=n|0,!i){var s=Math.pow(2,8*n)-1;le(this,e,r,n,s,0);}var o=1,a=0;for(this[r]=e&255;++a<n&&(o*=256);)this[r+a]=e/o&255;return r+n};A.prototype.writeUIntBE=function(e,r,n,i){if(e=+e,r=r|0,n=n|0,!i){var s=Math.pow(2,8*n)-1;le(this,e,r,n,s,0);}var o=n-1,a=1;for(this[r+o]=e&255;--o>=0&&(a*=256);)this[r+o]=e/a&255;return r+n};A.prototype.writeUInt8=function(e,r,n){return e=+e,r=r|0,n||le(this,e,r,1,255,0),A.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[r]=e&255,r+1};function gr(t,e,r,n){e<0&&(e=65535+e+1);for(var i=0,s=Math.min(t.length-r,2);i<s;++i)t[r+i]=(e&255<<8*(n?i:1-i))>>>(n?i:1-i)*8;}A.prototype.writeUInt16LE=function(e,r,n){return e=+e,r=r|0,n||le(this,e,r,2,65535,0),A.TYPED_ARRAY_SUPPORT?(this[r]=e&255,this[r+1]=e>>>8):gr(this,e,r,true),r+2};A.prototype.writeUInt16BE=function(e,r,n){return e=+e,r=r|0,n||le(this,e,r,2,65535,0),A.TYPED_ARRAY_SUPPORT?(this[r]=e>>>8,this[r+1]=e&255):gr(this,e,r,false),r+2};function mr(t,e,r,n){e<0&&(e=4294967295+e+1);for(var i=0,s=Math.min(t.length-r,4);i<s;++i)t[r+i]=e>>>(n?i:3-i)*8&255;}A.prototype.writeUInt32LE=function(e,r,n){return e=+e,r=r|0,n||le(this,e,r,4,4294967295,0),A.TYPED_ARRAY_SUPPORT?(this[r+3]=e>>>24,this[r+2]=e>>>16,this[r+1]=e>>>8,this[r]=e&255):mr(this,e,r,true),r+4};A.prototype.writeUInt32BE=function(e,r,n){return e=+e,r=r|0,n||le(this,e,r,4,4294967295,0),A.TYPED_ARRAY_SUPPORT?(this[r]=e>>>24,this[r+1]=e>>>16,this[r+2]=e>>>8,this[r+3]=e&255):mr(this,e,r,false),r+4};A.prototype.writeIntLE=function(e,r,n,i){if(e=+e,r=r|0,!i){var s=Math.pow(2,8*n-1);le(this,e,r,n,s-1,-s);}var o=0,a=1,c=0;for(this[r]=e&255;++o<n&&(a*=256);)e<0&&c===0&&this[r+o-1]!==0&&(c=1),this[r+o]=(e/a>>0)-c&255;return r+n};A.prototype.writeIntBE=function(e,r,n,i){if(e=+e,r=r|0,!i){var s=Math.pow(2,8*n-1);le(this,e,r,n,s-1,-s);}var o=n-1,a=1,c=0;for(this[r+o]=e&255;--o>=0&&(a*=256);)e<0&&c===0&&this[r+o+1]!==0&&(c=1),this[r+o]=(e/a>>0)-c&255;return r+n};A.prototype.writeInt8=function(e,r,n){return e=+e,r=r|0,n||le(this,e,r,1,127,-128),A.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[r]=e&255,r+1};A.prototype.writeInt16LE=function(e,r,n){return e=+e,r=r|0,n||le(this,e,r,2,32767,-32768),A.TYPED_ARRAY_SUPPORT?(this[r]=e&255,this[r+1]=e>>>8):gr(this,e,r,true),r+2};A.prototype.writeInt16BE=function(e,r,n){return e=+e,r=r|0,n||le(this,e,r,2,32767,-32768),A.TYPED_ARRAY_SUPPORT?(this[r]=e>>>8,this[r+1]=e&255):gr(this,e,r,false),r+2};A.prototype.writeInt32LE=function(e,r,n){return e=+e,r=r|0,n||le(this,e,r,4,2147483647,-2147483648),A.TYPED_ARRAY_SUPPORT?(this[r]=e&255,this[r+1]=e>>>8,this[r+2]=e>>>16,this[r+3]=e>>>24):mr(this,e,r,true),r+4};A.prototype.writeInt32BE=function(e,r,n){return e=+e,r=r|0,n||le(this,e,r,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),A.TYPED_ARRAY_SUPPORT?(this[r]=e>>>24,this[r+1]=e>>>16,this[r+2]=e>>>8,this[r+3]=e&255):mr(this,e,r,false),r+4};function ms(t,e,r,n,i,s){if(r+n>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function ys(t,e,r,n,i){return i||ms(t,e,r,4),lt.write(t,e,r,n,23,4),r+4}A.prototype.writeFloatLE=function(e,r,n){return ys(this,e,r,true,n)};A.prototype.writeFloatBE=function(e,r,n){return ys(this,e,r,false,n)};function bs(t,e,r,n,i){return i||ms(t,e,r,8),lt.write(t,e,r,n,52,8),r+8}A.prototype.writeDoubleLE=function(e,r,n){return bs(this,e,r,true,n)};A.prototype.writeDoubleBE=function(e,r,n){return bs(this,e,r,false,n)};A.prototype.copy=function(e,r,n,i){if(n||(n=0),!i&&i!==0&&(i=this.length),r>=e.length&&(r=e.length),r||(r=0),i>0&&i<n&&(i=n),i===n||e.length===0||this.length===0)return 0;if(r<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-r<i-n&&(i=e.length-r+n);var s=i-n,o;if(this===e&&n<r&&r<i)for(o=s-1;o>=0;--o)e[o+r]=this[o+n];else if(s<1e3||!A.TYPED_ARRAY_SUPPORT)for(o=0;o<s;++o)e[o+r]=this[o+n];else Uint8Array.prototype.set.call(e,this.subarray(n,n+s),r);return s};A.prototype.fill=function(e,r,n,i){if(typeof e=="string"){if(typeof r=="string"?(i=r,r=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"&&!A.isEncoding(i))throw new TypeError("Unknown encoding: "+i)}else typeof e=="number"&&(e=e&255);if(r<0||this.length<r||this.length<n)throw new RangeError("Out of range index");if(n<=r)return this;r=r>>>0,n=n===void 0?this.length:n>>>0,e||(e=0);var o;if(typeof e=="number")for(o=r;o<n;++o)this[o]=e;else {var a=A.isBuffer(e)?e:pr(new A(e,i).toString()),c=a.length;for(o=0;o<n-r;++o)this[o+r]=a[o%c];}return this};var Nu=/[^+\/0-9A-Za-z-_]/g;function Ou(t){if(t=Fu(t).replace(Nu,""),t.length<2)return "";for(;t.length%4!==0;)t=t+"=";return t}function Fu(t){return t.trim?t.trim():t.replace(/^\s+|\s+$/g,"")}function Lu(t){return t<16?"0"+t.toString(16):t.toString(16)}function pr(t,e){e=e||1/0;for(var r,n=t.length,i=null,s=[],o=0;o<n;++o){if(r=t.charCodeAt(o),r>55295&&r<57344){if(!i){if(r>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=r;continue}if(r<56320){(e-=3)>-1&&s.push(239,191,189),i=r;continue}r=(i-55296<<10|r-56320)+65536;}else i&&(e-=3)>-1&&s.push(239,191,189);if(i=null,r<128){if((e-=1)<0)break;s.push(r);}else if(r<2048){if((e-=2)<0)break;s.push(r>>6|192,r&63|128);}else if(r<65536){if((e-=3)<0)break;s.push(r>>12|224,r>>6&63|128,r&63|128);}else if(r<1114112){if((e-=4)<0)break;s.push(r>>18|240,r>>12&63|128,r>>6&63|128,r&63|128);}else throw new Error("Invalid code point")}return s}function Mu(t){for(var e=[],r=0;r<t.length;++r)e.push(t.charCodeAt(r)&255);return e}function qu(t,e){for(var r,n,i,s=[],o=0;o<t.length&&!((e-=2)<0);++o)r=t.charCodeAt(o),n=r>>8,i=r%256,s.push(i),s.push(n);return s}function _s(t){return bn.toByteArray(Ou(t))}function yr(t,e,r,n){for(var i=0;i<n&&!(i+r>=e.length||i>=t.length);++i)e[i+r]=t[i];return i}function Vu(t){return t!==t}});var ws={};ur(ws,{default:()=>ju});var Bu,ju,Es=st(()=>{Bu={},ju=Bu;});var In={};ur(In,{__assign:()=>Sn,__asyncDelegator:()=>rd,__asyncGenerator:()=>td,__asyncValues:()=>nd,__await:()=>Nt,__awaiter:()=>Ju,__classPrivateFieldGet:()=>ad,__classPrivateFieldSet:()=>cd,__createBinding:()=>Qu,__decorate:()=>Gu,__exportStar:()=>Xu,__extends:()=>$u,__generator:()=>Yu,__importDefault:()=>od,__importStar:()=>sd,__makeTemplateObject:()=>id,__metadata:()=>zu,__param:()=>Wu,__read:()=>As,__rest:()=>Hu,__spread:()=>Zu,__spreadArrays:()=>ed,__values:()=>vn});function $u(t,e){Tn(t,e);function r(){this.constructor=t;}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r);}function Hu(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(t,n[i])&&(r[n[i]]=t[n[i]]);return r}function Gu(t,e,r,n){var i=arguments.length,s=i<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,r):n,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(t,e,r,n);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(s=(i<3?o(s):i>3?o(e,r,s):o(e,r))||s);return i>3&&s&&Object.defineProperty(e,r,s),s}function Wu(t,e){return function(r,n){e(r,n,t);}}function zu(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function Ju(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s);})}return new(r||(r=Promise))(function(s,o){function a(d){try{l(n.next(d));}catch(h){o(h);}}function c(d){try{l(n.throw(d));}catch(h){o(h);}}function l(d){d.done?s(d.value):i(d.value).then(a,c);}l((n=n.apply(t,e||[])).next());})}function Yu(t,e){var r={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(l){return function(d){return c([l,d])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,i&&(s=l[0]&2?i.return:l[0]?i.throw||((s=i.return)&&s.call(i),0):i.next)&&!(s=s.call(i,l[1])).done)return s;switch(i=0,s&&(l=[l[0]&2,s.value]),l[0]){case 0:case 1:s=l;break;case 4:return r.label++,{value:l[1],done:!1};case 5:r.label++,i=l[1],l=[0];continue;case 7:l=r.ops.pop(),r.trys.pop();continue;default:if(s=r.trys,!(s=s.length>0&&s[s.length-1])&&(l[0]===6||l[0]===2)){r=0;continue}if(l[0]===3&&(!s||l[1]>s[0]&&l[1]<s[3])){r.label=l[1];break}if(l[0]===6&&r.label<s[1]){r.label=s[1],s=l;break}if(s&&r.label<s[2]){r.label=s[2],r.ops.push(l);break}s[2]&&r.ops.pop(),r.trys.pop();continue}l=e.call(t,r);}catch(d){l=[6,d],i=0;}finally{n=s=0;}if(l[0]&5)throw l[1];return {value:l[0]?l[1]:void 0,done:true}}}function Qu(t,e,r,n){n===void 0&&(n=r),t[n]=e[r];}function Xu(t,e){for(var r in t)r!=="default"&&!e.hasOwnProperty(r)&&(e[r]=t[r]);}function vn(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return {next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function As(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),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&&(r=n.return)&&r.call(n);}finally{if(o)throw o.error}}return s}function Zu(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(As(arguments[e]));return t}function ed(){for(var t=0,e=0,r=arguments.length;e<r;e++)t+=arguments[e].length;for(var n=Array(t),i=0,e=0;e<r;e++)for(var s=arguments[e],o=0,a=s.length;o<a;o++,i++)n[i]=s[o];return n}function Nt(t){return this instanceof Nt?(this.v=t,this):new Nt(t)}function td(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=r.apply(t,e||[]),i,s=[];return i={},o("next"),o("throw"),o("return"),i[Symbol.asyncIterator]=function(){return this},i;function o(u){n[u]&&(i[u]=function(p){return new Promise(function(g,m){s.push([u,p,g,m])>1||a(u,p);})});}function a(u,p){try{c(n[u](p));}catch(g){h(s[0][3],g);}}function c(u){u.value instanceof Nt?Promise.resolve(u.value.v).then(l,d):h(s[0][2],u);}function l(u){a("next",u);}function d(u){a("throw",u);}function h(u,p){u(p),s.shift(),s.length&&a(s[0][0],s[0][1]);}}function rd(t){var e,r;return e={},n("next"),n("throw",function(i){throw i}),n("return"),e[Symbol.iterator]=function(){return this},e;function n(i,s){e[i]=t[i]?function(o){return (r=!r)?{value:Nt(t[i](o)),done:i==="return"}:s?s(o):o}:s;}}function nd(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof vn=="function"?vn(t):t[Symbol.iterator](),r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r);function n(s){r[s]=t[s]&&function(o){return new Promise(function(a,c){o=t[s](o),i(a,c,o.done,o.value);})};}function i(s,o,a,c){Promise.resolve(c).then(function(l){s({value:l,done:a});},o);}}function id(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function sd(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)Object.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function od(t){return t&&t.__esModule?t:{default:t}}function ad(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function cd(t,e,r){if(!e.has(t))throw new TypeError("attempted to set private field on non-instance");return e.set(t,r),r}var Tn,Sn,Pn=st(()=>{Tn=function(t,e){return Tn=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n;}||function(r,n){for(var i in n)n.hasOwnProperty(i)&&(r[i]=n[i]);},Tn(t,e)};Sn=function(){return Sn=Object.assign||function(e){for(var r,n=1,i=arguments.length;n<i;n++){r=arguments[n];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(e[s]=r[s]);}return e},Sn.apply(this,arguments)};});var kn=ce(be=>{Object.defineProperty(be,"__esModule",{value:true});be.MAX_HASHABLE_LENGTH=be.INIT=be.KEY=be.DIGEST_LENGTH=be.BLOCK_SIZE=void 0;be.BLOCK_SIZE=64;be.DIGEST_LENGTH=32;be.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]);be.INIT=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225];be.MAX_HASHABLE_LENGTH=Math.pow(2,53)-1;});var Rs=ce(_r=>{Object.defineProperty(_r,"__esModule",{value:true});_r.RawSha256=void 0;var _e=kn(),ld=(function(){function t(){this.state=Int32Array.from(_e.INIT),this.temp=new Int32Array(64),this.buffer=new Uint8Array(64),this.bufferLength=0,this.bytesHashed=0,this.finished=false;}return t.prototype.update=function(e){if(this.finished)throw new Error("Attempted to update an already finished hash.");var r=0,n=e.byteLength;if(this.bytesHashed+=n,this.bytesHashed*8>_e.MAX_HASHABLE_LENGTH)throw new Error("Cannot hash more than 2^53 - 1 bits");for(;n>0;)this.buffer[this.bufferLength++]=e[r++],n--,this.bufferLength===_e.BLOCK_SIZE&&(this.hashBuffer(),this.bufferLength=0);},t.prototype.digest=function(){if(!this.finished){var e=this.bytesHashed*8,r=new DataView(this.buffer.buffer,this.buffer.byteOffset,this.buffer.byteLength),n=this.bufferLength;if(r.setUint8(this.bufferLength++,128),n%_e.BLOCK_SIZE>=_e.BLOCK_SIZE-8){for(var i=this.bufferLength;i<_e.BLOCK_SIZE;i++)r.setUint8(i,0);this.hashBuffer(),this.bufferLength=0;}for(var i=this.bufferLength;i<_e.BLOCK_SIZE-8;i++)r.setUint8(i,0);r.setUint32(_e.BLOCK_SIZE-8,Math.floor(e/4294967296),true),r.setUint32(_e.BLOCK_SIZE-4,e),this.hashBuffer(),this.finished=true;}for(var s=new Uint8Array(_e.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},t.prototype.hashBuffer=function(){for(var e=this,r=e.buffer,n=e.state,i=n[0],s=n[1],o=n[2],a=n[3],c=n[4],l=n[5],d=n[6],h=n[7],u=0;u<_e.BLOCK_SIZE;u++){if(u<16)this.temp[u]=(r[u*4]&255)<<24|(r[u*4+1]&255)<<16|(r[u*4+2]&255)<<8|r[u*4+3]&255;else {var p=this.temp[u-2],g=(p>>>17|p<<15)^(p>>>19|p<<13)^p>>>10;p=this.temp[u-15];var m=(p>>>7|p<<25)^(p>>>18|p<<14)^p>>>3;this.temp[u]=(g+this.temp[u-7]|0)+(m+this.temp[u-16]|0);}var b=(((c>>>6|c<<26)^(c>>>11|c<<21)^(c>>>25|c<<7))+(c&l^~c&d)|0)+(h+(_e.KEY[u]+this.temp[u]|0)|0)|0,y=((i>>>2|i<<30)^(i>>>13|i<<19)^(i>>>22|i<<10))+(i&s^i&o^s&o)|0;h=d,d=l,l=c,c=a+b|0,a=o,o=s,s=i,i=b+y|0;}n[0]+=i,n[1]+=s,n[2]+=o,n[3]+=a,n[4]+=c,n[5]+=l,n[6]+=d,n[7]+=h;},t})();_r.RawSha256=ld;});var Ts,Ss,vs=st(()=>{Ts=t=>{let e=[];for(let r=0,n=t.length;r<n;r++){let i=t.charCodeAt(r);if(i<128)e.push(i);else if(i<2048)e.push(i>>6|192,i&63|128);else if(r+1<t.length&&(i&64512)===55296&&(t.charCodeAt(r+1)&64512)===56320){let s=65536+((i&1023)<<10)+(t.charCodeAt(++r)&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)},Ss=t=>{let e="";for(let r=0,n=t.length;r<n;r++){let i=t[r];if(i<128)e+=String.fromCharCode(i);else if(192<=i&&i<224){let s=t[++r];e+=String.fromCharCode((i&31)<<6|s&63);}else if(240<=i&&i<365){let o="%"+[i,t[++r],t[++r],t[++r]].map(a=>a.toString(16)).join("%");e+=decodeURIComponent(o);}else e+=String.fromCharCode((i&15)<<12|(t[++r]&63)<<6|t[++r]&63);}return e};});function Is(t){return new TextEncoder().encode(t)}function Ps(t){return new TextDecoder("utf-8").decode(t)}var ks=st(()=>{});var Cs={};ur(Cs,{fromUtf8:()=>ud,toUtf8:()=>dd});var ud,dd,xs=st(()=>{vs();ks();ud=t=>typeof TextEncoder=="function"?Is(t):Ts(t),dd=t=>typeof TextDecoder=="function"?Ps(t):Ss(t);});var Us=ce(wr=>{Object.defineProperty(wr,"__esModule",{value:true});wr.convertToBuffer=void 0;var fd=(xs(),at(Cs)),hd=typeof Buffer<"u"&&Buffer.from?function(t){return Buffer.from(t,"utf8")}:fd.fromUtf8;function pd(t){return t instanceof Uint8Array?t:typeof t=="string"?hd(t):ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(t)}wr.convertToBuffer=pd;});var Ds=ce(Er=>{Object.defineProperty(Er,"__esModule",{value:true});Er.isEmptyData=void 0;function gd(t){return typeof t=="string"?t.length===0:t.byteLength===0}Er.isEmptyData=gd;});var Ns=ce(Ar=>{Object.defineProperty(Ar,"__esModule",{value:true});Ar.numToUint8=void 0;function md(t){return new Uint8Array([(t&4278190080)>>24,(t&16711680)>>16,(t&65280)>>8,t&255])}Ar.numToUint8=md;});var Os=ce(Rr=>{Object.defineProperty(Rr,"__esModule",{value:true});Rr.uint32ArrayFrom=void 0;function yd(t){if(!Array.from){for(var e=new Uint32Array(t.length),r=0;r<t.length;)e[r]=t[r];return e}return Uint32Array.from(t)}Rr.uint32ArrayFrom=yd;});var Fs=ce(De=>{Object.defineProperty(De,"__esModule",{value:true});De.uint32ArrayFrom=De.numToUint8=De.isEmptyData=De.convertToBuffer=void 0;var bd=Us();Object.defineProperty(De,"convertToBuffer",{enumerable:true,get:function(){return bd.convertToBuffer}});var _d=Ds();Object.defineProperty(De,"isEmptyData",{enumerable:true,get:function(){return _d.isEmptyData}});var wd=Ns();Object.defineProperty(De,"numToUint8",{enumerable:true,get:function(){return wd.numToUint8}});var Ed=Os();Object.defineProperty(De,"uint32ArrayFrom",{enumerable:true,get:function(){return Ed.uint32ArrayFrom}});});var Ms=ce(Sr=>{Object.defineProperty(Sr,"__esModule",{value:true});Sr.Sha256=void 0;var Ls=(Pn(),at(In)),Tr=kn(),Cn=Rs(),xn=Fs(),Ad=(function(){function t(e){if(this.hash=new Cn.RawSha256,e){this.outer=new Cn.RawSha256;var r=Rd(e),n=new Uint8Array(Tr.BLOCK_SIZE);n.set(r);for(var i=0;i<Tr.BLOCK_SIZE;i++)r[i]^=54,n[i]^=92;this.hash.update(r),this.outer.update(n);for(var i=0;i<r.byteLength;i++)r[i]=0;}}return t.prototype.update=function(e){if(!((0, xn.isEmptyData)(e)||this.error))try{this.hash.update((0,xn.convertToBuffer)(e));}catch(r){this.error=r;}},t.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()},t.prototype.digest=function(){return (0, Ls.__awaiter)(this,void 0,void 0,function(){return (0, Ls.__generator)(this,function(e){return [2,this.digestSync()]})})},t})();Sr.Sha256=Ad;function Rd(t){var e=(0, xn.convertToBuffer)(t);if(e.byteLength>Tr.BLOCK_SIZE){var r=new Cn.RawSha256;r.update(e),e=r.digest();}var n=new Uint8Array(Tr.BLOCK_SIZE);return n.set(e),n}});var Dn=ce(Un=>{Object.defineProperty(Un,"__esModule",{value:true});var Td=(Pn(),at(In));(0, Td.__exportStar)(Ms(),Un);});var jn={};ur(jn,{default:()=>_f});function _f(t,e){return e=e||{},new Promise(function(r,n){var i=new XMLHttpRequest,s=[],o=[],a={},c=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:c,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 l in i.open(e.method||"get",t,true),i.onload=function(){i.getAllResponseHeaders().replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm,function(d,h,u){s.push(h=h.toLowerCase()),o.push([h,u]),a[h]=a[h]?a[h]+","+u:u;}),r(c());},i.onerror=n,i.withCredentials=e.credentials=="include",e.headers)i.setRequestHeader(l,e.headers[l]);i.send(e.body||null);})}var Kn=st(()=>{});var Ws=ce((Sg,Gs)=>{Gs.exports=self.fetch||(self.fetch=(Kn(),at(jn)).default||(Kn(),at(jn)));});function ct(t){let r=(typeof globalThis<"u"?globalThis:void 0)?.process;if(r&&typeof r.getBuiltinModule=="function")try{return r.getBuiltinModule(t)}catch{}try{if(typeof He=="function")return He(t)}catch{}return null}var dn,fn,hn=()=>dn!==void 0?dn:dn=ct("fs"),pn=()=>fn!==void 0?fn:fn=ct("path"),Le=typeof globalThis<"u"?globalThis:void 0,dr=Le?.window;function au(t){if(Buffer)return Buffer.from(t).toString("base64");let e="",r=new Uint8Array(t),n=32768;for(let i=0;i<r.length;i+=n){let s=r.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(dr)dr.global=dr,dr.global._runningInNodeJS=false;else if(Le&&(Le.global=Le,typeof Le.window>"u")){class t{constructor(){this.result=null;this.error=null;this.onload=null;this.onloadend=null;this.onerror=null;}readAsDataURL(n){n.arrayBuffer().then(i=>{let s=au(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});});}}Le.FileReader=t;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);});}}Le.XMLHttpRequest=e,Le.window={_runningInNodeJS:true,alert:r=>console.error("[Alert]",r),sessionStorage:(()=>{let r=new Map;return {getItem:n=>r.has(n)?r.get(n):null,setItem:(n,i)=>{r.set(n,String(i));},removeItem:n=>{r.delete(n);}}})(),localStorage:{getItem:r=>{let n=hn(),i=pn();if(!n||!i)return null;try{let s=i.resolve(process.cwd(),"states","localStorage",`${r}.skapi`);return n.existsSync(s)?n.readFileSync(s,"utf8"):null}catch{return null}},setItem:(r,n)=>{let i=hn(),s=pn();if(!(!i||!s))try{let o=s.resolve(process.cwd(),"states","localStorage");i.existsSync(o)||i.mkdirSync(o,{recursive:!0});let a=s.resolve(o,`${r}.skapi`);i.writeFileSync(a,n,"utf8");}catch{}},removeItem:r=>{let n=hn(),i=pn();if(!(!n||!i))try{let s=i.resolve(process.cwd(),"states","localStorage",`${r}.skapi`);n.existsSync(s)&&n.unlinkSync(s);}catch{}}},location:{href:"",origin:"",hostname:"",protocol:"",replace:r=>{}},navigator:{userAgent:`nodejs/${Le?.process?.versions?.node||"unknown"}`,mediaDevices:{getUserMedia:async r=>{throw new Error("getUserMedia is not supported in Node.js environment.")}}},addEventListener:()=>{},removeEventListener:()=>{}};}var gn=(function(){function t(r){var n=r||{},i=n.ValidationData,s=n.Username,o=n.Password,a=n.AuthParameters,c=n.ClientMetadata;this.validationData=i||{},this.authParameters=a||{},this.clientMetadata=c||{},this.username=s,this.password=o;}var e=t.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},t})();var qe=ot(br());var ye;typeof window<"u"&&window.crypto&&(ye=window.crypto);!ye&&typeof window<"u"&&window.msCrypto&&(ye=window.msCrypto);!ye&&typeof globalThis<"u"&&globalThis.crypto&&(ye=globalThis.crypto);if(!ye&&typeof He=="function")try{ye=(Es(),at(ws));}catch{}function An(){if(ye){if(typeof ye.getRandomValues=="function")try{return ye.getRandomValues(new Uint32Array(1))[0]}catch{}if(typeof ye.randomBytes=="function")try{return ye.randomBytes(4).readInt32LE()}catch{}}throw new Error("Native crypto module could not be used to get secure random number.")}function Ku(t){for(var e=t.words,r=t.sigBytes,n=[],i=0;i<r;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 Rn=(function(){function t(r,n){r=this.words=r||[],n!=null?this.sigBytes=n:this.sigBytes=r.length*4;}var e=t.prototype;return e.random=function(n){for(var i=[],s=0;s<n;s+=4)i.push(An());return new t(i,n)},e.toString=function(){return Ku(this)},t})();var Ir=ot(Dn());var J=F;function F(t,e){t!=null&&this.fromString(t,e);}function oe(){return new F(null)}var Ge,Sd=0xdeadbeefcafe,qs=(Sd&16777215)==15715070;function vd(t,e,r,n,i,s){for(;--s>=0;){var o=e*this[t++]+r[n]+i;i=Math.floor(o/67108864),r[n++]=o&67108863;}return i}function Id(t,e,r,n,i,s){for(var o=e&32767,a=e>>15;--s>=0;){var c=this[t]&32767,l=this[t++]>>15,d=a*c+l*o;c=o*c+((d&32767)<<15)+r[n]+(i&1073741823),i=(c>>>30)+(d>>>15)+a*l+(i>>>30),r[n++]=c&1073741823;}return i}function Pd(t,e,r,n,i,s){for(var o=e&16383,a=e>>14;--s>=0;){var c=this[t]&16383,l=this[t++]>>14,d=a*c+l*o;c=o*c+((d&16383)<<14)+r[n]+i,i=(c>>28)+(d>>14)+a*l,r[n++]=c&268435455;}return i}var Vs=typeof navigator<"u";Vs&&qs&&navigator.appName=="Microsoft Internet Explorer"?(F.prototype.am=Id,Ge=30):Vs&&qs&&navigator.appName!="Netscape"?(F.prototype.am=vd,Ge=26):(F.prototype.am=Pd,Ge=28);F.prototype.DB=Ge;F.prototype.DM=(1<<Ge)-1;F.prototype.DV=1<<Ge;var Nn=52;F.prototype.FV=Math.pow(2,Nn);F.prototype.F1=Nn-Ge;F.prototype.F2=2*Ge-Nn;var kd="0123456789abcdefghijklmnopqrstuvwxyz",vr=new Array,dt,we;dt=48;for(we=0;we<=9;++we)vr[dt++]=we;dt=97;for(we=10;we<36;++we)vr[dt++]=we;dt=65;for(we=10;we<36;++we)vr[dt++]=we;function Bs(t){return kd.charAt(t)}function Cd(t,e){var r=vr[t.charCodeAt(e)];return r??-1}function xd(t){for(var e=this.t-1;e>=0;--e)t[e]=this[e];t.t=this.t,t.s=this.s;}function Ud(t){this.t=1,this.s=t<0?-1:0,t>0?this[0]=t:t<-1?this[0]=t+this.DV:this.t=0;}function On(t){var e=oe();return e.fromInt(t),e}function Dd(t,e){var r;if(e==16)r=4;else if(e==8)r=3;else if(e==2)r=1;else if(e==32)r=5;else if(e==4)r=2;else throw new Error("Only radix 2, 4, 8, 16, 32 are supported");this.t=0,this.s=0;for(var n=t.length,i=false,s=0;--n>=0;){var o=Cd(t,n);if(o<0){t.charAt(n)=="-"&&(i=true);continue}i=false,s==0?this[this.t++]=o:s+r>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+=r,s>=this.DB&&(s-=this.DB);}this.clamp(),i&&F.ZERO.subTo(this,this);}function Nd(){for(var t=this.s&this.DM;this.t>0&&this[this.t-1]==t;)--this.t;}function Od(t){if(this.s<0)return "-"+this.negate().toString(t);var e;if(t==16)e=4;else if(t==8)e=3;else if(t==2)e=1;else if(t==32)e=5;else if(t==4)e=2;else throw new Error("Only radix 2, 4, 8, 16, 32 are supported");var r=(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=Bs(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)&r,a<=0&&(a+=this.DB,--o)),n>0&&(i=true),i&&(s+=Bs(n));return i?s:"0"}function Fd(){var t=oe();return F.ZERO.subTo(this,t),t}function Ld(){return this.s<0?this.negate():this}function Md(t){var e=this.s-t.s;if(e!=0)return e;var r=this.t;if(e=r-t.t,e!=0)return this.s<0?-e:e;for(;--r>=0;)if((e=this[r]-t[r])!=0)return e;return 0}function Fn(t){var e=1,r;return (r=t>>>16)!=0&&(t=r,e+=16),(r=t>>8)!=0&&(t=r,e+=8),(r=t>>4)!=0&&(t=r,e+=4),(r=t>>2)!=0&&(t=r,e+=2),(r=t>>1)!=0&&(t=r,e+=1),e}function qd(){return this.t<=0?0:this.DB*(this.t-1)+Fn(this[this.t-1]^this.s&this.DM)}function Vd(t,e){var r;for(r=this.t-1;r>=0;--r)e[r+t]=this[r];for(r=t-1;r>=0;--r)e[r]=0;e.t=this.t+t,e.s=this.s;}function Bd(t,e){for(var r=t;r<this.t;++r)e[r-t]=this[r];e.t=Math.max(this.t-t,0),e.s=this.s;}function jd(t,e){var r=t%this.DB,n=this.DB-r,i=(1<<n)-1,s=Math.floor(t/this.DB),o=this.s<<r&this.DM,a;for(a=this.t-1;a>=0;--a)e[a+s+1]=this[a]>>n|o,o=(this[a]&i)<<r;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 Kd(t,e){e.s=this.s;var r=Math.floor(t/this.DB);if(r>=this.t){e.t=0;return}var n=t%this.DB,i=this.DB-n,s=(1<<n)-1;e[0]=this[r]>>n;for(var o=r+1;o<this.t;++o)e[o-r-1]|=(this[o]&s)<<i,e[o-r]=this[o]>>n;n>0&&(e[this.t-r-1]|=(this.s&s)<<i),e.t=this.t-r,e.clamp();}function $d(t,e){for(var r=0,n=0,i=Math.min(t.t,this.t);r<i;)n+=this[r]-t[r],e[r++]=n&this.DM,n>>=this.DB;if(t.t<this.t){for(n-=t.s;r<this.t;)n+=this[r],e[r++]=n&this.DM,n>>=this.DB;n+=this.s;}else {for(n+=this.s;r<t.t;)n-=t[r],e[r++]=n&this.DM,n>>=this.DB;n-=t.s;}e.s=n<0?-1:0,n<-1?e[r++]=this.DV+n:n>0&&(e[r++]=n),e.t=r,e.clamp();}function Hd(t,e){var r=this.abs(),n=t.abs(),i=r.t;for(e.t=i+n.t;--i>=0;)e[i]=0;for(i=0;i<n.t;++i)e[i+r.t]=r.am(0,n[i],e,i,0,r.t);e.s=0,e.clamp(),this.s!=t.s&&F.ZERO.subTo(e,e);}function Gd(t){for(var e=this.abs(),r=t.t=2*e.t;--r>=0;)t[r]=0;for(r=0;r<e.t-1;++r){var n=e.am(r,e[r],t,2*r,0,1);(t[r+e.t]+=e.am(r+1,2*e[r],t,2*r+1,n,e.t-r-1))>=e.DV&&(t[r+e.t]-=e.DV,t[r+e.t+1]=1);}t.t>0&&(t[t.t-1]+=e.am(r,e[r],t,2*r,0,1)),t.s=0,t.clamp();}function Wd(t,e,r){var n=t.abs();if(!(n.t<=0)){var i=this.abs();if(i.t<n.t){e?.fromInt(0),r!=null&&this.copyTo(r);return}r==null&&(r=oe());var s=oe(),o=this.s,a=t.s,c=this.DB-Fn(n[n.t-1]);c>0?(n.lShiftTo(c,s),i.lShiftTo(c,r)):(n.copyTo(s),i.copyTo(r));var l=s.t,d=s[l-1];if(d!=0){var h=d*(1<<this.F1)+(l>1?s[l-2]>>this.F2:0),u=this.FV/h,p=(1<<this.F1)/h,g=1<<this.F2,m=r.t,b=m-l,y=e??oe();for(s.dlShiftTo(b,y),r.compareTo(y)>=0&&(r[r.t++]=1,r.subTo(y,r)),F.ONE.dlShiftTo(l,y),y.subTo(s,s);s.t<l;)s[s.t++]=0;for(;--b>=0;){var E=r[--m]==d?this.DM:Math.floor(r[m]*u+(r[m-1]+g)*p);if((r[m]+=s.am(0,E,r,b,0,l))<E)for(s.dlShiftTo(b,y),r.subTo(y,r);r[m]<--E;)r.subTo(y,r);}e!=null&&(r.drShiftTo(l,e),o!=a&&F.ZERO.subTo(e,e)),r.t=l,r.clamp(),c>0&&r.rShiftTo(c,r),o<0&&F.ZERO.subTo(r,r);}}}function zd(t){var e=oe();return this.abs().divRemTo(t,null,e),this.s<0&&e.compareTo(F.ZERO)>0&&t.subTo(e,e),e}function Jd(){if(this.t<1)return 0;var t=this[0];if((t&1)==0)return 0;var e=t&3;return e=e*(2-(t&15)*e)&15,e=e*(2-(t&255)*e)&255,e=e*(2-((t&65535)*e&65535))&65535,e=e*(2-t*e%this.DV)%this.DV,e>0?this.DV-e:-e}function Yd(t){return this.compareTo(t)==0}function Qd(t,e){for(var r=0,n=0,i=Math.min(t.t,this.t);r<i;)n+=this[r]+t[r],e[r++]=n&this.DM,n>>=this.DB;if(t.t<this.t){for(n+=t.s;r<this.t;)n+=this[r],e[r++]=n&this.DM,n>>=this.DB;n+=this.s;}else {for(n+=this.s;r<t.t;)n+=t[r],e[r++]=n&this.DM,n>>=this.DB;n+=t.s;}e.s=n<0?-1:0,n>0?e[r++]=n:n<-1&&(e[r++]=this.DV+n),e.t=r,e.clamp();}function Xd(t){var e=oe();return this.addTo(t,e),e}function Zd(t){var e=oe();return this.subTo(t,e),e}function ef(t){var e=oe();return this.multiplyTo(t,e),e}function tf(t){var e=oe();return this.divRemTo(t,e,null),e}function ft(t){this.m=t,this.mp=t.invDigit(),this.mpl=this.mp&32767,this.mph=this.mp>>15,this.um=(1<<t.DB-15)-1,this.mt2=2*t.t;}function rf(t){var e=oe();return t.abs().dlShiftTo(this.m.t,e),e.divRemTo(this.m,null,e),t.s<0&&e.compareTo(F.ZERO)>0&&this.m.subTo(e,e),e}function nf(t){var e=oe();return t.copyTo(e),this.reduce(e),e}function sf(t){for(;t.t<=this.mt2;)t[t.t++]=0;for(var e=0;e<this.m.t;++e){var r=t[e]&32767,n=r*this.mpl+((r*this.mph+(t[e]>>15)*this.mpl&this.um)<<15)&t.DM;for(r=e+this.m.t,t[r]+=this.m.am(0,n,t,e,0,this.m.t);t[r]>=t.DV;)t[r]-=t.DV,t[++r]++;}t.clamp(),t.drShiftTo(this.m.t,t),t.compareTo(this.m)>=0&&t.subTo(this.m,t);}function of(t,e){t.squareTo(e),this.reduce(e);}function af(t,e,r){t.multiplyTo(e,r),this.reduce(r);}ft.prototype.convert=rf;ft.prototype.revert=nf;ft.prototype.reduce=sf;ft.prototype.mulTo=af;ft.prototype.sqrTo=of;function cf(t,e,r){var n=t.bitLength(),i,s=On(1),o=new ft(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,c=3,l=i-1,d=(1<<i)-1;if(a[1]=o.convert(this),i>1){var h=oe();for(o.sqrTo(a[1],h);c<=d;)a[c]=oe(),o.mulTo(h,a[c-2],a[c]),c+=2;}var u=t.t-1,p,g=true,m=oe(),b;for(n=Fn(t[u])-1;u>=0;){for(n>=l?p=t[u]>>n-l&d:(p=(t[u]&(1<<n+1)-1)<<l-n,u>0&&(p|=t[u-1]>>this.DB+n-l)),c=i;(p&1)==0;)p>>=1,--c;if((n-=c)<0&&(n+=this.DB,--u),g)a[p].copyTo(s),g=false;else {for(;c>1;)o.sqrTo(s,m),o.sqrTo(m,s),c-=2;c>0?o.sqrTo(s,m):(b=s,s=m,m=b),o.mulTo(m,a[p],s);}for(;u>=0&&(t[u]&1<<n)==0;)o.sqrTo(s,m),b=s,s=m,m=b,--n<0&&(n=this.DB-1,--u);}var y=o.revert(s);return r(null,y),y}F.prototype.copyTo=xd;F.prototype.fromInt=Ud;F.prototype.fromString=Dd;F.prototype.clamp=Nd;F.prototype.dlShiftTo=Vd;F.prototype.drShiftTo=Bd;F.prototype.lShiftTo=jd;F.prototype.rShiftTo=Kd;F.prototype.subTo=$d;F.prototype.multiplyTo=Hd;F.prototype.squareTo=Gd;F.prototype.divRemTo=Wd;F.prototype.invDigit=Jd;F.prototype.addTo=Qd;F.prototype.toString=Od;F.prototype.negate=Fd;F.prototype.abs=Ld;F.prototype.compareTo=Md;F.prototype.bitLength=qd;F.prototype.mod=zd;F.prototype.equals=Yd;F.prototype.add=Xd;F.prototype.subtract=Zd;F.prototype.multiply=ef;F.prototype.divide=tf;F.prototype.modPow=cf;F.ZERO=On(0);F.ONE=On(1);function Ln(t){return qe.Buffer.from(new Rn().random(t).toString(),"hex")}var lf=/^[89a-f]/i,uf="FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200CBBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF",df="userAttributes.",We=(function(){function t(r){this.N=new J(uf,16),this.g=new J("2",16),this.k=new J(this.hexHash(""+this.padHex(this.N)+this.padHex(this.g)),16),this.smallAValue=this.generateRandomSmallA(),this.getLargeAValue(function(){}),this.infoBits=qe.Buffer.from("Caldera Derived Key","utf8"),this.poolName=r;}var e=t.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=Ln(128).toString("hex"),i=new J(n,16);return i},e.generateRandomString=function(){return Ln(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,c=this.hash(a),l=Ln(16).toString("hex");this.SaltToHashDevices=this.padHex(new J(l,16)),this.g.modPow(new J(this.hexHash(this.SaltToHashDevices+c),16),this.N,function(d,h){d&&s(d,null),o.verifierDevices=o.padHex(h),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(J.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 J(this.UHexHash,16);return s},e.hash=function(n){var i=new Ir.Sha256;i.update(n);var s=i.digestSync(),o=qe.Buffer.from(s).toString("hex");return new Array(64-o.length).join("0")+o},e.hexHash=function(n){return this.hash(qe.Buffer.from(n,"hex"))},e.computehkdf=function(n,i){var s=qe.Buffer.concat([this.infoBits,qe.Buffer.from("","utf8")]),o=new Ir.Sha256(i);o.update(n);var a=o.digestSync(),c=new Ir.Sha256(a);c.update(s);var l=c.digestSync(),d=l,h=d.slice(0,16);return h},e.getPasswordAuthenticationKey=function(n,i,s,o,a){var c=this;if(s.mod(this.N).equals(J.ZERO))throw new Error("B cannot be zero.");if(this.UValue=this.calculateU(this.largeAValue,s),this.UValue.equals(J.ZERO))throw new Error("U cannot be zero.");var l=""+this.poolName+n+":"+i,d=this.hash(l),h=new J(this.hexHash(this.padHex(o)+d),16);this.calculateS(h,s,function(u,p){u&&a(u,null);var g=c.computehkdf(qe.Buffer.from(c.padHex(p),"hex"),qe.Buffer.from(c.padHex(c.UValue),"hex"));a(null,g);});},e.calculateS=function(n,i,s){var o=this;this.g.modPow(n,this.N,function(a,c){a&&s(a,null);var l=i.subtract(o.k.multiply(c));l.modPow(o.smallAValue.add(o.UValue.multiply(n)),o.N,function(d,h){d&&s(d,null),s(null,h.mod(o.N));});});},e.getNewPasswordRequiredChallengeUserAttributePrefix=function(){return df},e.padHex=function(n){if(!(n instanceof J))throw new Error("Not a BigInteger");var i=n.compareTo(J.ZERO)<0,s=n.abs().toString(16);if(s=s.length%2!==0?"0"+s:s,s=lf.test(s)?"00"+s:s,i){var o=s.split("").map(function(c){var l=~parseInt(c,16)&15;return "0123456789ABCDEF".charAt(l)}).join(""),a=new J(o,16).add(J.ONE);s=a.toString(16),s.toUpperCase().startsWith("FF8")&&(s=s.substring(2));}return s},t})();var js=ot(br());var Pr=(function(){function t(r){this.jwtToken=r||"",this.payload=this.decodePayload();}var e=t.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(js.Buffer.from(n,"base64").toString("utf8"))}catch{return {}}},t})();function ff(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,Mn(t,e);}function Mn(t,e){return Mn=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(r,n){return r.__proto__=n,r},Mn(t,e)}var ht=(function(t){function e(r){var n=r===void 0?{}:r,i=n.AccessToken;return t.call(this,i||"")||this}return ff(e,t),e})(Pr);function hf(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,qn(t,e);}function qn(t,e){return qn=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(r,n){return r.__proto__=n,r},qn(t,e)}var pt=(function(t){function e(r){var n=r===void 0?{}:r,i=n.IdToken;return t.call(this,i||"")||this}return hf(e,t),e})(Pr);var gt=(function(){function t(r){var n=r===void 0?{}:r,i=n.RefreshToken;this.token=i||"";}var e=t.prototype;return e.getToken=function(){return this.token},t})();var Z=ot(br()),Bn=ot(Dn());var Ks="5.0.4";var pf="aws-amplify/"+Ks,Vn={userAgent:pf,isReactNative:typeof navigator<"u"&&navigator.product==="ReactNative"},$s=function(){return Vn.userAgent};var mt=(function(){function t(r){var n=r===void 0?{}:r,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=t.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()},t})();var gf=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],mf=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],kr=(function(){function t(){}var e=t.prototype;return e.getNowString=function(){var n=new Date,i=mf[n.getUTCDay()],s=gf[n.getUTCMonth()],o=n.getUTCDate(),a=n.getUTCHours();a<10&&(a="0"+a);var c=n.getUTCMinutes();c<10&&(c="0"+c);var l=n.getUTCSeconds();l<10&&(l="0"+l);var d=n.getUTCFullYear(),h=i+" "+s+" "+o+" "+a+":"+c+":"+l+" UTC "+d;return h},t})();var Ne=(function(){function t(r){var n=r===void 0?{}:r,i=n.Name,s=n.Value;this.Name=i||"",this.Value=s||"";}var e=t.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}},t})();var Ze={},yf=(function(){function t(){}return t.setItem=function(r,n){return Ze[r]=n,Ze[r]},t.getItem=function(r){return Object.prototype.hasOwnProperty.call(Ze,r)?Ze[r]:void 0},t.removeItem=function(r){return delete Ze[r]},t.clear=function(){return Ze={},Ze},t})(),Cr=(function(){function t(){try{this.storageWindow=window.localStorage,this.storageWindow.setItem("aws.cognito.test-ls",1),this.storageWindow.removeItem("aws.cognito.test-ls");}catch{this.storageWindow=yf;}}var e=t.prototype;return e.getStorage=function(){return this.storageWindow},t})();var bf=typeof navigator<"u",Hs=bf?Vn.isReactNative?"react-native":navigator.userAgent:"nodejs",Ve=(function(){function t(r){if(r==null||r.Username==null||r.Pool==null)throw new Error("Username and Pool information are required.");this.username=r.Username||"",this.pool=r.Pool,this.Session=null,this.client=r.Pool.client,this.signInUserSession=null,this.authenticationFlowType="USER_SRP_AUTH",this.storage=r.Storage||new Cr().getStorage(),this.keyPrefix="CognitoIdentityServiceProvider."+this.pool.getClientId(),this.userDataKey=this.keyPrefix+"."+this.username+".userData";}var e=t.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(),c={AuthFlow:"CUSTOM_AUTH",ClientId:this.pool.getClientId(),AuthParameters:o,ClientMetadata:a};this.getUserContextData()&&(c.UserContextData=this.getUserContextData()),this.client.request("InitiateAuth",c,function(l,d){if(l)return i.onFailure(l);var h=d.ChallengeName,u=d.ChallengeParameters;return h==="CUSTOM_CHALLENGE"?(s.Session=d.Session,i.customChallenge(u)):(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 kr,c,l,d={};this.deviceKey!=null&&(d.DEVICE_KEY=this.deviceKey),d.USERNAME=this.username,o.getLargeAValue(function(h,u){h&&i.onFailure(h),d.SRP_A=u.toString(16),s.authenticationFlowType==="CUSTOM_AUTH"&&(d.CHALLENGE_NAME="SRP_A");var p=Object.keys(n.getValidationData()).length!==0?n.getValidationData():n.getClientMetadata(),g={AuthFlow:s.authenticationFlowType,ClientId:s.pool.getClientId(),AuthParameters:d,ClientMetadata:p};s.getUserContextData(s.username)&&(g.UserContextData=s.getUserContextData(s.username)),s.client.request("InitiateAuth",g,function(m,b){if(m)return i.onFailure(m);var y=b.ChallengeParameters;s.username=y.USER_ID_FOR_SRP,s.userDataKey=s.keyPrefix+"."+s.username+".userData",c=new J(y.SRP_B,16),l=new J(y.SALT,16),s.getCachedDeviceKeyAndPassword(),o.getPasswordAuthenticationKey(s.username,n.getPassword(),c,l,function(E,w){E&&i.onFailure(E);var T=a.getNowString(),R=Z.Buffer.concat([Z.Buffer.from(s.pool.getUserPoolName(),"utf8"),Z.Buffer.from(s.username,"utf8"),Z.Buffer.from(y.SECRET_BLOCK,"base64"),Z.Buffer.from(T,"utf8")]),x=new Bn.Sha256(w);x.update(R);var O=x.digestSync(),U=Z.Buffer.from(O).toString("base64"),I={};I.USERNAME=s.username,I.PASSWORD_CLAIM_SECRET_BLOCK=y.SECRET_BLOCK,I.TIMESTAMP=T,I.PASSWORD_CLAIM_SIGNATURE=U,s.deviceKey!=null&&(I.DEVICE_KEY=s.deviceKey);var D=function(ie,ae){return s.client.request("RespondToAuthChallenge",ie,function(q,te){return q&&q.code==="ResourceNotFoundException"&&q.message.toLowerCase().indexOf("device")!==-1?(I.DEVICE_KEY=null,s.deviceKey=null,s.randomPassword=null,s.deviceGroupKey=null,s.clearCachedDeviceKeyAndPassword(),D(ie,ae)):ae(q,te)})},N={ChallengeName:"PASSWORD_VERIFIER",ClientId:s.pool.getClientId(),ChallengeResponses:I,Session:b.Session,ClientMetadata:p};s.getUserContextData()&&(N.UserContextData=s.getUserContextData()),D(N,function(M,ie){return M?i.onFailure(M):s.authenticateUserInternal(ie,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 c=Object.keys(n.getValidationData()).length!==0?n.getValidationData():n.getClientMetadata(),l={AuthFlow:"USER_PASSWORD_AUTH",ClientId:this.pool.getClientId(),AuthParameters:o,ClientMetadata:c};this.getUserContextData(this.username)&&(l.UserContextData=this.getUserContextData(this.username)),this.client.request("InitiateAuth",l,function(d,h){return d?i.onFailure(d):s.authenticateUserInternal(h,a,i)});},e.authenticateUserInternal=function(n,i,s){var o=this,a=n.ChallengeName,c=n.ChallengeParameters;if(a==="SMS_MFA")return this.Session=n.Session,s.mfaRequired(a,c);if(a==="SELECT_MFA_TYPE")return this.Session=n.Session,s.selectMFAType(a,c);if(a==="MFA_SETUP")return this.Session=n.Session,s.mfaSetup(a,c);if(a==="SOFTWARE_TOKEN_MFA")return this.Session=n.Session,s.totpRequired(a,c);if(a==="CUSTOM_CHALLENGE")return this.Session=n.Session,s.customChallenge(c);if(a==="NEW_PASSWORD_REQUIRED"){this.Session=n.Session;var l=null,d=null,h=[],u=i.getNewPasswordRequiredChallengeUserAttributePrefix();if(c&&(l=JSON.parse(n.ChallengeParameters.userAttributes),d=JSON.parse(n.ChallengeParameters.requiredAttributes)),d)for(var p=0;p<d.length;p++)h[p]=d[p].substr(u.length);return s.newPasswordRequired(l,h)}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 g=n.AuthenticationResult.NewDeviceMetadata;if(g==null)return s.onSuccess(this.signInUserSession);i.generateHashDevice(n.AuthenticationResult.NewDeviceMetadata.DeviceGroupKey,n.AuthenticationResult.NewDeviceMetadata.DeviceKey,function(m){if(m)return s.onFailure(m);var b={Salt:Z.Buffer.from(i.getSaltDevices(),"hex").toString("base64"),PasswordVerifier:Z.Buffer.from(i.getVerifierDevices(),"hex").toString("base64")};o.verifierDevices=b.PasswordVerifier,o.deviceGroupKey=g.DeviceGroupKey,o.randomPassword=i.getRandomPassword(),o.client.request("ConfirmDevice",{DeviceKey:g.DeviceKey,AccessToken:o.signInUserSession.getAccessToken().getJwtToken(),DeviceSecretVerifierConfig:b,DeviceName:Hs},function(y,E){return y?s.onFailure(y):(o.deviceKey=n.AuthenticationResult.NewDeviceMetadata.DeviceKey,o.cacheDeviceKeyAndPassword(),E.UserConfirmationNecessary===true?s.onSuccess(o.signInUserSession,E.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 c=new We(this.pool.getUserPoolName()),l=c.getNewPasswordRequiredChallengeUserAttributePrefix(),d={};i&&Object.keys(i).forEach(function(u){d[l+u]=i[u];}),d.NEW_PASSWORD=n,d.USERNAME=this.username;var h={ChallengeName:"NEW_PASSWORD_REQUIRED",ClientId:this.pool.getClientId(),ChallengeResponses:d,Session:this.Session,ClientMetadata:o};this.getUserContextData()&&(h.UserContextData=this.getUserContextData()),this.client.request("RespondToAuthChallenge",h,function(u,p){return u?s.onFailure(u):a.authenticateUserInternal(p,c,s)});},e.getDeviceResponse=function(n,i){var s=this,o=new We(this.deviceGroupKey),a=new kr,c={};c.USERNAME=this.username,c.DEVICE_KEY=this.deviceKey,o.getLargeAValue(function(l,d){l&&n.onFailure(l),c.SRP_A=d.toString(16);var h={ChallengeName:"DEVICE_SRP_AUTH",ClientId:s.pool.getClientId(),ChallengeResponses:c,ClientMetadata:i,Session:s.Session};s.getUserContextData()&&(h.UserContextData=s.getUserContextData()),s.client.request("RespondToAuthChallenge",h,function(u,p){if(u)return n.onFailure(u);var g=p.ChallengeParameters,m=new J(g.SRP_B,16),b=new J(g.SALT,16);o.getPasswordAuthenticationKey(s.deviceKey,s.randomPassword,m,b,function(y,E){if(y)return n.onFailure(y);var w=a.getNowString(),T=Z.Buffer.concat([Z.Buffer.from(s.deviceGroupKey,"utf8"),Z.Buffer.from(s.deviceKey,"utf8"),Z.Buffer.from(g.SECRET_BLOCK,"base64"),Z.Buffer.from(w,"utf8")]),R=new Bn.Sha256(E);R.update(T);var x=R.digestSync(),O=Z.Buffer.from(x).toString("base64"),U={};U.USERNAME=s.username,U.PASSWORD_CLAIM_SECRET_BLOCK=g.SECRET_BLOCK,U.TIMESTAMP=w,U.PASSWORD_CLAIM_SIGNATURE=O,U.DEVICE_KEY=s.deviceKey;var I={ChallengeName:"DEVICE_PASSWORD_VERIFIER",ClientId:s.pool.getClientId(),ChallengeResponses:U,Session:p.Session};s.getUserContextData()&&(I.UserContextData=s.getUserContextData()),s.client.request("RespondToAuthChallenge",I,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(c){return c?s(c,null):s(null,"SUCCESS")});},e.sendCustomChallengeAnswer=function(n,i,s){var o=this,a={};a.USERNAME=this.username,a.ANSWER=n;var c=new We(this.pool.getUserPoolName());this.getCachedDeviceKeyAndPassword(),this.deviceKey!=null&&(a.DEVICE_KEY=this.deviceKey);var l={ChallengeName:"CUSTOM_CHALLENGE",ChallengeResponses:a,ClientId:this.pool.getClientId(),Session:this.Session,ClientMetadata:s};this.getUserContextData()&&(l.UserContextData=this.getUserContextData()),this.client.request("RespondToAuthChallenge",l,function(d,h){return d?i.onFailure(d):o.authenticateUserInternal(h,c,i)});},e.sendMFACode=function(n,i,s,o){var a=this,c={};c.USERNAME=this.username,c.SMS_MFA_CODE=n;var l=s||"SMS_MFA";l==="SOFTWARE_TOKEN_MFA"&&(c.SOFTWARE_TOKEN_MFA_CODE=n),this.deviceKey!=null&&(c.DEVICE_KEY=this.deviceKey);var d={ChallengeName:l,ChallengeResponses:c,ClientId:this.pool.getClientId(),Session:this.Session,ClientMetadata:o};this.getUserContextData()&&(d.UserContextData=this.getUserContextData()),this.client.request("RespondToAuthChallenge",d,function(h,u){if(h)return i.onFailure(h);var p=u.ChallengeName;if(p==="DEVICE_SRP_AUTH"){a.getDeviceResponse(i);return}if(a.signInUserSession=a.getCognitoUserSession(u.AuthenticationResult),a.cacheTokens(),u.AuthenticationResult.NewDeviceMetadata==null)return i.onSuccess(a.signInUserSession);var g=new We(a.pool.getUserPoolName());g.generateHashDevice(u.AuthenticationResult.NewDeviceMetadata.DeviceGroupKey,u.AuthenticationResult.NewDeviceMetadata.DeviceKey,function(m){if(m)return i.onFailure(m);var b={Salt:Z.Buffer.from(g.getSaltDevices(),"hex").toString("base64"),PasswordVerifier:Z.Buffer.from(g.getVerifierDevices(),"hex").toString("base64")};a.verifierDevices=b.PasswordVerifier,a.deviceGroupKey=u.AuthenticationResult.NewDeviceMetadata.DeviceGroupKey,a.randomPassword=g.getRandomPassword(),a.client.request("ConfirmDevice",{DeviceKey:u.AuthenticationResult.NewDeviceMetadata.DeviceKey,AccessToken:a.signInUserSession.getAccessToken().getJwtToken(),DeviceSecretVerifierConfig:b,DeviceName:Hs},function(y,E){return y?i.onFailure(y):(a.deviceKey=u.AuthenticationResult.NewDeviceMetadata.DeviceKey,a.cacheDeviceKeyAndPassword(),E.UserConfirmationNecessary===true?i.onSuccess(a.signInUserSession,E.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,c){return a?i(a,null):o.getUserData(function(){return i(null,"SUCCESS",c)},{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 c={Name:s.UserAttributes[a].Name,Value:s.UserAttributes[a].Value},l=new Ne(c);o.push(l);}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",c=s+".refreshToken",l=s+".clockDrift";if(this.storage.getItem(o)){var d=new pt({IdToken:this.storage.getItem(o)}),h=new ht({AccessToken:this.storage.getItem(a)}),u=new gt({RefreshToken:this.storage.getItem(c)}),p=parseInt(this.storage.getItem(l),0)||0,g={IdToken:d,AccessToken:h,RefreshToken:u,ClockDrift:p},m=new mt(g);if(m.isValid())return this.signInUserSession=m,n(null,this.signInUserSession);if(!u.getToken())return n(new Error("Cannot retrieve a new session. Please authenticate."),null);this.refreshSession(u,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,c={};c.REFRESH_TOKEN=n.getToken();var l="CognitoIdentityServiceProvider."+this.pool.getClientId(),d=l+".LastAuthUser";if(this.storage.getItem(d)){this.username=this.storage.getItem(d);var h=l+"."+this.username+".deviceKey";this.deviceKey=this.storage.getItem(h),c.DEVICE_KEY=this.deviceKey;}var u={ClientId:this.pool.getClientId(),AuthFlow:"REFRESH_TOKEN_AUTH",AuthParameters:c,ClientMetadata:s};this.getUserContextData()&&(u.UserContextData=this.getUserContextData()),this.client.requestWithRetry("InitiateAuth",u,function(p,g){if(p)return p.code==="NotAuthorizedException"&&o.clearCachedUser(),a(p,null);if(g){var m=g.AuthenticationResult;return Object.prototype.hasOwnProperty.call(m,"RefreshToken")||(m.RefreshToken=n.getToken()),o.signInUserSession=o.getCognitoUserSession(m),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",c=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(c,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",c=n+"."+this.username+".clockDrift";this.storage.removeItem(i),this.storage.removeItem(s),this.storage.removeItem(o),this.storage.removeItem(a),this.storage.removeItem(c);},e.getCognitoUserSession=function(n){var i=new pt(n),s=new ht(n),o=new gt(n),a={IdToken:i,AccessToken:s,RefreshToken:o};return new mt(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(c){return c?s.onFailure(c):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,c){return a?s.onFailure(a):s.onSuccess(c)});},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(),c=this.signInUserSession.getAccessToken();if(this.isSessionRevocable(c)&&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(c,l){if(c)return i.onFailure(c);if(s.Session=l.Session,n==="SMS_MFA")return i.mfaRequired(l.ChallengeName,l.ChallengeParameters);if(n==="SOFTWARE_TOKEN_MFA")return i.totpRequired(l.ChallengeName,l.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,c){return a?s.onFailure(a):s.onSuccess(c)}):this.client.request("VerifySoftwareToken",{Session:this.Session,UserCode:n,FriendlyDeviceName:i},function(a,c){if(a)return s.onFailure(a);o.Session=c.Session;var l={};l.USERNAME=o.username;var d={ChallengeName:"MFA_SETUP",ClientId:o.pool.getClientId(),ChallengeResponses:l,Session:o.Session};o.getUserContextData()&&(d.UserContextData=o.getUserContextData()),o.client.request("RespondToAuthChallenge",d,function(h,u){return h?s.onFailure(h):(o.signInUserSession=o.getCognitoUserSession(u.AuthenticationResult),o.cacheTokens(),s.onSuccess(o.signInUserSession))});});},t})();ot(Ws());function yt(){}yt.prototype.userAgent=$s();var zs=function(e){var r=yt.category?" "+yt.category:"",n=yt.framework?" framework/"+yt.framework:"",i=""+yt.prototype.userAgent+r+n;return i};function wf(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,Ot(t,e);}function $n(t){var e=typeof Map=="function"?new Map:void 0;return $n=function(n){if(n===null||!Af(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 Ef(n,arguments,Hn(this).constructor)}return i.prototype=Object.create(n.prototype,{constructor:{value:i,enumerable:false,writable:true,configurable:true}}),Ot(i,n)},$n(t)}function Ef(t,e,r){if(Js())return Reflect.construct.apply(null,arguments);var n=[null];n.push.apply(n,e);var i=new(t.bind.apply(t,n));return r&&Ot(i,r.prototype),i}function Js(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}));}catch{}return (Js=function(){return !!t})()}function Af(t){try{return Function.toString.call(t).indexOf("[native code]")!==-1}catch{return typeof t=="function"}}function Ot(t,e){return Ot=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(r,n){return r.__proto__=n,r},Ot(t,e)}function Hn(t){return Hn=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},Hn(t)}var Rf=(function(t){function e(r,n,i,s){var o;return o=t.call(this,r)||this,o.code=n,o.name=i,o.statusCode=s,o}return wf(e,t),e})($n(Error)),Ys=(function(){function t(r,n,i){this.endpoint=n||"https://cognito-idp."+r+".amazonaws.com/";var s=i||{},o=s.credentials;this.fetchOptions=o?{credentials:o}:{};}var e=t.prototype;return e.promisifyRequest=function(n,i){var s=this;return new Promise(function(o,a){s.request(n,i,function(c,l){c?a(new Rf(c.message,c.code,c.name,c.statusCode)):o(l);});})},e.requestWithRetry=function(n,i,s){var o=this,a=5*1e3;If(function(c){return new Promise(function(l,d){o.request(n,c,function(h,u){h?d(h):l(u);});})},[i],a).then(function(c){return s(null,c)}).catch(function(c){return s(c)});},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":zs(),"Cache-Control":"no-store"},a=Object.assign({},this.fetchOptions,{headers:o,method:"POST",mode:"cors",body:JSON.stringify(i)}),c;fetch(this.endpoint,a).then(function(d){return c=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(c.ok)return s(null,d);var h=(d.__type||d.code).split("#").pop(),u=new Error(d.message||d.Message||null);return u.name=h,u.code=h,s(u)}).catch(function(d){if(c&&c.headers&&c.headers.get("x-amzn-errortype"))try{var h=c.headers.get("x-amzn-errortype").split(":")[0],u=new Error(c.status?c.status.toString():null);return u.code=h,u.name=h,u.statusCode=c.status,s(u)}catch{return s(d)}else d instanceof Error&&d.message==="Network error"&&(d.code="NetworkError");return s(d)});},t})();var xr={debug:function(){}};var Tf=function(e){var r="nonRetryable";return e&&e[r]};function Qs(t,e,r,n){if(n===void 0&&(n=1),typeof t!="function")throw Error("functionToRetry must be a function");return xr.debug(t.name+" attempt #"+n+" with args: "+JSON.stringify(e)),t.apply(void 0,e).catch(function(i){if(xr.debug("error on "+t.name,i),Tf(i))throw xr.debug(t.name+" non retryable error",i),i;var s=r(n,e,i);if(xr.debug(t.name+" retrying in "+s+" ms"),s!==false)return new Promise(function(o){return setTimeout(o,s)}).then(function(){return Qs(t,e,r,n+1)});throw i})}function Sf(t){var e=100,r=100;return function(n){var i=Math.pow(2,n)*e+r*Math.random();return i>t?false:i}}function If(t,e,r){return Qs(t,e,Sf(r))}var Pf=55,Gn=(function(){function t(r,n){var i=r||{},s=i.UserPoolId,o=i.ClientId,a=i.endpoint,c=i.fetchOptions,l=i.AdvancedSecurityDataCollectionFlag;if(!s||!o)throw new Error("Both UserPoolId and ClientId are required.");if(s.length>Pf||!/^[\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 Ys(d,a,c),this.advancedSecurityDataCollectionFlag=l!==false,this.storage=r.Storage||new Cr().getStorage(),n&&(this.wrapRefreshSessionCallback=n);}var e=t.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,c){var l=this,d={ClientId:this.clientId,Username:n,Password:i,UserAttributes:s,ValidationData:o,ClientMetadata:c};this.getUserContextData(n)&&(d.UserContextData=this.getUserContextData(n)),this.client.request("SignUp",d,function(h,u){if(h)return a(h,null);var p={Username:n,Pool:l,Storage:l.storage},g={user:new Ve(p),userConfirmed:u.UserConfirmed,userSub:u.UserSub,codeDeliveryDetails:u.CodeDeliveryDetails};return a(null,g)});},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 Ve(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 {}}},t})();function Ur(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)n!=="__proto__"&&(t[n]=r[n]);}return t}var kf={read:function(t){return t[0]==='"'&&(t=t.slice(1,-1)),t.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(t){return encodeURIComponent(t).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}};function Wn(t,e){function r(i,s,o){if(!(typeof document>"u")){o=Ur({},e,o),typeof o.expires=="number"&&(o.expires=new Date(Date.now()+o.expires*864e5)),o.expires&&(o.expires=o.expires.toUTCString()),i=encodeURIComponent(i).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var a="";for(var c in o)o[c]&&(a+="; "+c,o[c]!==true&&(a+="="+o[c].split(";")[0]));return document.cookie=i+"="+t.write(s,i)+a}}function n(i){if(!(typeof document>"u"||arguments.length&&!i)){for(var s=document.cookie?document.cookie.split("; "):[],o={},a=0;a<s.length;a++){var c=s[a].split("="),l=c.slice(1).join("=");try{var d=decodeURIComponent(c[0]);if(d in o||(o[d]=t.read(l,d)),i===d)break}catch{}}return i?o[i]:o}}return Object.create({set:r,get:n,remove:function(i,s){r(i,"",Ur({},s,{expires:-1}));},withAttributes:function(i){return Wn(this.converter,Ur({},this.attributes,i))},withConverter:function(i){return Wn(Ur({},this.converter,i),this.attributes)}},{attributes:{value:Object.freeze(e)},converter:{value:Object.freeze(t)}})}Wn(kf,{path:"/"});var f=class extends Error{constructor(e,r){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=r?.name||"SKAPI",this.code=r?.code||e[0]||"ERROR",r?.cause&&(this.cause=r.cause);}else super((e?.message||(typeof e=="string"?e:"Something went wrong.")).trim()),typeof e=="string"?(this.name=r?.name||"SKAPI",this.code=r?.code||"ERROR",r?.cause&&(this.cause=r.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=r?.name||"SKAPI",this.code=r?.code||"ERROR",this.cause=e?.cause);}};var Be="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",zn=BigInt(Be.length),xf=2*1024*1024,Uf=["aud","cognito:username","event_id","exp","iat","iss","jti","origin_jti","secret_key","token_use"],Xs={auth_time:"log",sub:"user_id"},no=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f","g","h","i","j","k","l"],io=["us31","us72","ap51","ap22","ap41","eu71","ap21","us32","us71","af51","ap31","ap43","ap23","ap42","ca01","eu01","eu72","eu51","eu73","eu11","me51","sa31"],Zs=typeof TextEncoder<"u"?new TextEncoder:null;function Df(){if(typeof globalThis<"u")return globalThis.Buffer}function Y(t){if(Zs)return Zs.encode(t);let e=unescape(encodeURIComponent(t)),r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return r}function Jn(t){if(t instanceof Uint8Array)return t;if(typeof t=="string")return Y(t);if(typeof ArrayBuffer<"u"&&t instanceof ArrayBuffer)return new Uint8Array(t);if(typeof ArrayBuffer<"u"&&ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);if(Array.isArray(t))return Uint8Array.from(t);let e=Df();if(e)return new Uint8Array(e.from(t));throw new Error("No byte conversion available in this environment.")}var v=class v{static hash(e){typeof e!="string"&&(console.warn("coercing non-string value to empty string"),e="");let r=v.sb(e),n=1732584193,i=-271733879,s=-1732584194,o=271733878,a,c,l,d;for(let h=0;h<r.length;h+=16)a=n,c=i,l=s,d=o,n=v.ff(n,i,s,o,r[h],7,-680876936),o=v.ff(o,n,i,s,r[h+1],12,-389564586),s=v.ff(s,o,n,i,r[h+2],17,606105819),i=v.ff(i,s,o,n,r[h+3],22,-1044525330),n=v.ff(n,i,s,o,r[h+4],7,-176418897),o=v.ff(o,n,i,s,r[h+5],12,1200080426),s=v.ff(s,o,n,i,r[h+6],17,-1473231341),i=v.ff(i,s,o,n,r[h+7],22,-45705983),n=v.ff(n,i,s,o,r[h+8],7,1770035416),o=v.ff(o,n,i,s,r[h+9],12,-1958414417),s=v.ff(s,o,n,i,r[h+10],17,-42063),i=v.ff(i,s,o,n,r[h+11],22,-1990404162),n=v.ff(n,i,s,o,r[h+12],7,1804603682),o=v.ff(o,n,i,s,r[h+13],12,-40341101),s=v.ff(s,o,n,i,r[h+14],17,-1502002290),i=v.ff(i,s,o,n,r[h+15],22,1236535329),n=v.gg(n,i,s,o,r[h+1],5,-165796510),o=v.gg(o,n,i,s,r[h+6],9,-1069501632),s=v.gg(s,o,n,i,r[h+11],14,643717713),i=v.gg(i,s,o,n,r[h],20,-373897302),n=v.gg(n,i,s,o,r[h+5],5,-701558691),o=v.gg(o,n,i,s,r[h+10],9,38016083),s=v.gg(s,o,n,i,r[h+15],14,-660478335),i=v.gg(i,s,o,n,r[h+4],20,-405537848),n=v.gg(n,i,s,o,r[h+9],5,568446438),o=v.gg(o,n,i,s,r[h+14],9,-1019803690),s=v.gg(s,o,n,i,r[h+3],14,-187363961),i=v.gg(i,s,o,n,r[h+8],20,1163531501),n=v.gg(n,i,s,o,r[h+13],5,-1444681467),o=v.gg(o,n,i,s,r[h+2],9,-51403784),s=v.gg(s,o,n,i,r[h+7],14,1735328473),i=v.gg(i,s,o,n,r[h+12],20,-1926607734),n=v.hh(n,i,s,o,r[h+5],4,-378558),o=v.hh(o,n,i,s,r[h+8],11,-2022574463),s=v.hh(s,o,n,i,r[h+11],16,1839030562),i=v.hh(i,s,o,n,r[h+14],23,-35309556),n=v.hh(n,i,s,o,r[h+1],4,-1530992060),o=v.hh(o,n,i,s,r[h+4],11,1272893353),s=v.hh(s,o,n,i,r[h+7],16,-155497632),i=v.hh(i,s,o,n,r[h+10],23,-1094730640),n=v.hh(n,i,s,o,r[h+13],4,681279174),o=v.hh(o,n,i,s,r[h],11,-358537222),s=v.hh(s,o,n,i,r[h+3],16,-722521979),i=v.hh(i,s,o,n,r[h+6],23,76029189),n=v.hh(n,i,s,o,r[h+9],4,-640364487),o=v.hh(o,n,i,s,r[h+12],11,-421815835),s=v.hh(s,o,n,i,r[h+15],16,530742520),i=v.hh(i,s,o,n,r[h+2],23,-995338651),n=v.ii(n,i,s,o,r[h],6,-198630844),o=v.ii(o,n,i,s,r[h+7],10,1126891415),s=v.ii(s,o,n,i,r[h+14],15,-1416354905),i=v.ii(i,s,o,n,r[h+5],21,-57434055),n=v.ii(n,i,s,o,r[h+12],6,1700485571),o=v.ii(o,n,i,s,r[h+3],10,-1894986606),s=v.ii(s,o,n,i,r[h+10],15,-1051523),i=v.ii(i,s,o,n,r[h+1],21,-2054922799),n=v.ii(n,i,s,o,r[h+8],6,1873313359),o=v.ii(o,n,i,s,r[h+15],10,-30611744),s=v.ii(s,o,n,i,r[h+6],15,-1560198380),i=v.ii(i,s,o,n,r[h+13],21,1309151649),n=v.ii(n,i,s,o,r[h+4],6,-145523070),o=v.ii(o,n,i,s,r[h+11],10,-1120210379),s=v.ii(s,o,n,i,r[h+2],15,718787259),i=v.ii(i,s,o,n,r[h+9],21,-343485551),n=v.ad(n,a),i=v.ad(i,c),s=v.ad(s,l),o=v.ad(o,d);return v.rh(n)+v.rh(i)+v.rh(s)+v.rh(o)}static rh(e){let r="";for(let n=0;n<=3;n++)r+=v.alphabet.charAt(e>>n*8+4&15)+v.alphabet.charAt(e>>n*8&15);return r}static ad(e,r){let n=(e&65535)+(r&65535);return (e>>16)+(r>>16)+(n>>16)<<16|n&65535}static rl(e,r){return e<<r|e>>>32-r}static cm(e,r,n,i,s,o){return v.ad(v.rl(v.ad(v.ad(r,e),v.ad(i,o)),s),n)}static ff(e,r,n,i,s,o,a){return v.cm(r&n|~r&i,e,r,s,o,a)}static gg(e,r,n,i,s,o,a){return v.cm(r&i|n&~i,e,r,s,o,a)}static hh(e,r,n,i,s,o,a){return v.cm(r^n^i,e,r,s,o,a)}static ii(e,r,n,i,s,o,a){return v.cm(n^(r|~i),e,r,s,o,a)}static sb(e){let r,n=(e.length+8>>6)+1,i=new Array(n*16);for(r=0;r<n*16;r++)i[r]=0;for(r=0;r<e.length;r++)i[r>>2]|=e.charCodeAt(r)<<r%4*8;return i[r>>2]|=128<<r%4*8,i[n*16-2]=e.length*8,i}};v.alphabet="0123456789abcdef";var he=v;function so(t){if(t===0)return Be[0];let e="";for(;t>0;)e=Be[t%62]+e,t=Math.floor(t/62);return e}function Se(t){return t.split("").reverse().reduce((e,r,n)=>e+Be.indexOf(r)*62**n,0)}function et(t=6){let e="",r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n=r.length,i=0;for(;i<t;)e+=r.charAt(Math.floor(Math.random()*n)),i+=1;return e}function Yn(){return typeof window>"u"||!!window?._runningInNodeJS}function X(){return !Yn()&&typeof document<"u"&&typeof document.createElement=="function"}function Dr(t){let e;try{e=JSON.stringify(t);}catch{throw new f("Invalid data type.",{code:"INVALID_REQUEST"})}if(new Blob([e]).size>xf)throw new f("Data should not exceed 2MB",{code:"INVALID_REQUEST"})}function eo(t){return t===""||t==="on"||t==="true"}function to(t){return t==="false"}function ro(t,e,r){e.name&&r(t,e.name,e.value);}var Nr=X(),Nf=typeof SubmitEvent<"u",Of=typeof HTMLFormElement<"u";function $(t,e,r){let n={},i=[];function s(c,l,d){if(e?.ignoreEmpty&&d==="")return;if(e?.nullIfEmpty&&d===""&&(d=null),typeof r=="function"){let p=r(l,d);p!==void 0&&(d=p);}let h=l.split("[").map(p=>{let g=p.replace("]",""),m=Number(g);return !isNaN(m)&&!g.includes(".")?g=m:(g[0]==='"'&&g[g.length-1]==='"'||g[0]==="'"&&g[g.length-1]==="'")&&(g=g.replace(/"/g,"").replace(/'/g,"")),g}),u=c;if(typeof h[0]=="number")throw new f("Form key cannot start with an array index.",{code:"INVALID_REQUEST"});for(let p=0;p<h.length;p++){let g=h[p];p<h.length-1?(u[g]===void 0&&(typeof h[p+1]=="number"?u[g]=[]:u[g]={}),u=u[g]):u[g]===void 0?u[g]=d:Array.isArray(u[g])?u[g].push(d):u[g]=[u[g],d];}}function o(c,l,d){if(d instanceof File)c.push({name:l,file:d});else if(d instanceof FileList&&d&&d.length>0)for(let h=0;h<=d.length-1;h++){let u=d.item(h);u&&c.push({name:l,file:u});}}let a=c=>{c.name&&(c.type==="number"?c.value&&s(n,c.name,Number(c.value)):c.type==="checkbox"||c.type==="radio"?c.checked?c.type==="checkbox"&&c.value===""||eo(c.value)?s(n,c.name,true):to(c.value)?s(n,c.name,false):c.value&&s(n,c.name,c.value):c.type==="checkbox"&&(eo(c.value)?s(n,c.name,false):to(c.value)&&s(n,c.name,true)):c.type==="file"?c.files&&c.files.length>0&&o(i,c.name,c.files):s(n,c.name,c.value));};if(Nr&&(t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement))return a(t),Dr(n),{data:n,files:i};if(Nr&&t instanceof FormData){for(let c of t.entries()){let l=c[0],d=c[1];if(d instanceof File||d instanceof FileList)o(i,l,d);else if(d instanceof Blob){let h=d;if(h.type==="application/json")try{let u=JSON.parse(h.text());s(n,l,u);}catch{s(n,l,h);}}else s(n,l,d);}return Dr(n),{data:n,files:i}}if(Nr&&Nf&&t instanceof SubmitEvent&&(t=t.target),Nr&&Of&&t instanceof HTMLFormElement){let c=t.querySelectorAll("input"),l=t.querySelectorAll("select"),d=t.querySelectorAll("textarea");for(let h=0;h<l.length;h++)ro(n,l[h],s);for(let h=0;h<d.length;h++)ro(n,d[h],s);for(let h=0;h<c.length;h++)a(c[h]);return Dr(n),{data:n,files:i}}return Dr(t),{data:t,files:i}}function Ft(t){let e={};for(let r in t){let n=t[r];if(!Uf.includes(r))if(Xs[r])e[Xs[r]]=n;else if(r.includes("custom:"))e[r.replace("custom:","")]=n;else if(r==="address"){let i=n;if(i&&typeof i=="object"&&Object.keys(i).length){if(i?.formatted)try{e[r]=JSON.parse(i.formatted);}catch{e[r]=i.formatted;}}else e[r]=i;}else e[r]=n;}for(let r of ["address_public","birthdate_public","email_public","gender_public","phone_number_public","access_group"])r.includes("_public")?e.hasOwnProperty(r.split("_")[0])?e[r]=e.hasOwnProperty(r)?!!Number(e[r]):false:delete e[r]:e[r]=e.hasOwnProperty(r)?Number(e[r]):0;for(let r of ["email","phone_number"])e.hasOwnProperty(r)?e[r+"_verified"]=e[r+"_verified"]===true:delete e[r+"_verified"];return e}function Qn(t){if(t=Kf(t),t.split("-").length===7){let e=t.split("-"),r,n;try{r=io[no.indexOf(e[1][0])],n=e.slice(2).join("-");}catch{throw new Error("INVALID_PARAMETER: Service ID is invalid: "+t)}if(!r)throw new Error("INVALID_PARAMETER: Service ID is invalid: "+t);return {service:r+e[0]+e[1].slice(1),owner:n}}return {service:t,owner:""}}function Xn(t,e){let r=io.indexOf(t.slice(0,4)),n=no[r],s=`${t.slice(4,-4)}-${n}${t.slice(-4)}-${e}`;return jf(s)}function Ff(t){let e=0n;for(let r of t){let n=Be.indexOf(r);if(n<0)throw new Error(`INVALID_PARAMETER: Invalid base62 character: ${r}`);e=e*zn+BigInt(n);}return e}function Lf(t,e=1){if(t<0n)throw new Error("INVALID_PARAMETER: Negative values are not supported.");if(t===0n)return "0".repeat(Math.max(1,e));let r="",n=t;for(;n>0n;){let i=Number(n%zn);r=Be[i]+r,n/=zn;}return r.length<e&&(r="0".repeat(e-r.length)+r),r}function Mf(t){if(t===0n)return Uint8Array.from([0]);let e=[],r=t;for(;r>0n;)e.push(Number(r&0xffn)),r>>=8n;return e.reverse(),Uint8Array.from(e)}function qf(t){let e=0n;for(let r of t)e=(e<<8n)+BigInt(r);return e}function Vf(t){let e=String(t).replace(/-/g,"");if(!/^[0-9a-fA-F]{32}$/.test(e))throw new Error("INVALID_PARAMETER: Invalid UUID format.");let r=new Uint8Array(16);for(let n=0;n<16;n++)r[n]=parseInt(e.slice(n*2,n*2+2),16);return r}function Bf(t){let e=Array.from(Jn(t),r=>r.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 jf(t){let e=String(t);if(e.split("-").length===2)return e;let r=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(!r)throw new Error("INVALID_PARAMETER: Input must match <base62>-<base62>-<uuid>.");let[,n,i,s]=r;if(n.length<2)throw new Error("INVALID_PARAMETER: The first part must contain at least 2 characters.");if(i.length>=Be.length)throw new Error("INVALID_PARAMETER: The middle section is too long to encode.");let o=n.slice(0,2),a=n.slice(2),c=i+o,l=Be[i.length]+a+c,d=Vf(s),h=Lf(qf(d));return `${l}-${h}`}function Kf(t){let e=String(t);if(e.split("-").length!==2)return e;let r=e.split("-");if(r.length!==2||!r[0]||!r[1])throw new Error("INVALID_PARAMETER: Corrupt compressed token: "+e);let[n,i]=r,s=Be.indexOf(n[0]);if(s<0)throw new Error("INVALID_PARAMETER: Corrupt compressed token: "+e);let o=n.slice(1),a=s+2;if(o.length<a)throw new Error("INVALID_PARAMETER: Corrupt compressed token: "+e);let c=o.slice(0,o.length-a),l=o.slice(o.length-a),d=l.slice(s),h=l.slice(0,s),u=d+c;if(!/^[0-9A-Za-z]+$/.test(u)||!/^[0-9A-Za-z]+$/.test(h))throw new Error("INVALID_PARAMETER: Corrupt compressed token: "+e);let p=Ff(i),g=Mf(p);if(g.length>16)throw new Error("INVALID_PARAMETER: Corrupt compressed token: "+e);let m=new Uint8Array(16);m.set(g,16-g.length);let b=Bf(m);return `${u}-${h}-${b}`}function Lt(t){if(typeof TextDecoder<"u")return new TextDecoder().decode(t);let e="";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return decodeURIComponent(escape(e))}function Zn(...t){let e=0;for(let i of t)e+=i.length;let r=new Uint8Array(e),n=0;for(let i of t)r.set(i,n),n+=i.length;return r}function Mt(t,e,r=[],n=null){let i=["string","number","boolean","object","array","function","null","undefined"];function s(g){return g!==null&&typeof g=="object"&&!Array.isArray(g)}function o(g){return s(g)}function a(g){return Array.isArray(g)}function c(g){return typeof g=="string"&&i.indexOf(g)!==-1}function l(g){return Array.isArray(g)?"array":g===null?"null":typeof g}function d(g){try{return JSON.stringify(g)}catch{return String(g)}}function h(g){if(c(g))return `Type<${g}>`;if(typeof g=="function")return "custom validator";try{return JSON.stringify(g,(m,b)=>typeof b=="function"?"custom validator":b)}catch{return String(g)}}function u(g,m){return m==="array"?Array.isArray(g):m==="object"?s(g):m==="null"?g===null:m==="undefined"?typeof g>"u":typeof g===m}function p(g){return n===null?g:`${n}[${g}]`}if(typeof e>"u")throw new Error('Argument "struct" is required.');if(typeof e=="function")return e(t);if(o(e)){if(!s(t))throw new Error(`Data schema does not match:
|
|
207
|
+
`+JSON.stringify(t,null,2));for(let g of Object.keys(e)){let m=p(g);if(Object.prototype.hasOwnProperty.call(t,g))t[g]=Mt(t[g],e[g],r,m);else {if(r.indexOf(m)!==-1)throw new Error(`Key "${m}" is required.`);let b=e[g];a(b)&&b.length>1&&typeof b[b.length-1]=="function"&&(t[g]=b[b.length-1]());}}return t}if(a(e)){let g=false;if(e.length===1&&!a(e[0])&&!o(e[0])){let m=e[0];if(!Array.isArray(t))throw new Error(`Type <${l(t)}> is invalid in "${n}". Expected a list.`);for(let b=0;b<t.length;b++){let y=t[b];if(c(m)){if(!u(y,m))throw new Error(`Type <${l(y)}> is invalid in "${n}". Expected a list of Type <${m}>.`)}else if(typeof m=="function")t[b]=m(y);else if(y!==m)throw new Error(`Value ${d(y)} is invalid in "${n}". Expected a list of ${d(m)}.`)}g=true;}else if(Array.isArray(t)&&e.every(b=>!a(b)&&b!=="array")){for(let b=0;b<t.length;b++){let y=false,E="";for(let w of e)try{t[b]=Mt(t[b],w,r,n),y=!0;break}catch(T){typeof w=="function"&&(E=T?.message||String(T));}if(!y&&E)throw new Error(E);if(!y){let w=e.map(h).join(", ");throw new Error(`${d(t[b])} is invalid in "${n}". allowed types or values are: ${w}.`)}}g=true;}else {let b="";for(let y of e)try{t=Mt(t,y,r,n),g=!0;break}catch(E){typeof y=="function"&&(b=E?.message||String(E));}if(!g&&b)throw new Error(b)}if(!g){let m=e.map(h).join(", ");throw new Error(`${d(t)} is invalid in "${n}". allowed types or values are: ${m}.`)}return t}if(c(e)&&u(t,e)||t===e)return t;throw new Error(`${d(t)} is invalid in "${n}". allowed type or value is: ${h(e)}.`)}function $f(t,e="User ID"){let r=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;if(t){if(typeof t!="string")throw new f(`${e} should be type: string.`,{code:"INVALID_PARAMETER"});if(!t.match(r))throw new f(`${e} is invalid.`,{code:"INVALID_PARAMETER"})}else throw new f(`${e} is empty.`,{code:"INVALID_PARAMETER"});return t}function Hf(t){if(t&&(typeof t!="string"||t.charAt(0)!=="+"||isNaN(Number(t.substring(1)))))throw new f('"phone_number" is invalid. The format should be "+00123456789". Type: string.',{code:"INVALID_PARAMETER"});return t||""}function Gf(t){if(t){if(typeof t!="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(t.length!==10||t.split("-").length!==3||!e.test(t))throw new f('"birthdate" is invalid. The format should be "yyyy-mm-dd". Type: string.',{code:"INVALID_PARAMETER"})}}return t||""}function Wf(t){if(t){if(typeof t!="string")throw new f('"password" should be type: string.',{code:"INVALID_PARAMETER"});if(t.length<6)throw new f('"password" should be at least 6 characters.',{code:"INVALID_PARAMETER"});if(t.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 t}function zf(t,e="email"){if(t){if(typeof t!="string")throw new f(`"${e}"should be type: string.`,{code:"INVALID_PARAMETER"});if(t.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(t)&&(t=t.trim(),t.split("@")[1].split(".").length>=2))return t.toLowerCase()}else throw new f(`"${e}" is required.`,{code:"INVALID_PARAMETER"});throw new f(`"${t}" is an invalid email.`,{code:"INVALID_PARAMETER"})}function Jf(t){let e=typeof window<"u",r=(()=>{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]==="/"&&r){if(r.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=r+s;}else if(s[0]==="."&&r){if(r.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(t)?t.map(i=>n(i)):n(t)}var Yf=/^[a-z0-9]{2,20}$/,Qf=/[a-z]/,Xf=/^[0-9]+e[0-9]+$/,Zf=["tp","admin","public","authorized","newsletter","forward","all","true","false","null"];function eh(t,e){if(t==null){if(e?.allowNull)return null;throw new f('"group" is required.',{code:"INVALID_PARAMETER"})}if(!e?.nameOnly){if(t==="public")return 0;if(t==="authorized")return 1;if(typeof t=="number"){if(!Number.isInteger(t)||t<0||t>99)throw new f('"group" should be an integer between 0 and 99.',{code:"INVALID_PARAMETER"});return t}}if(typeof t!="string"||!Yf.test(t)||!Qf.test(t)||Xf.test(t)||Zf.includes(t))throw new f("Newsletter group name must be 2-20 lowercase alphanumeric characters, contain a letter, and not be a reserved name.",{code:"INVALID_PARAMETER"});return t}function th(t,e,r=[],n){let i=$(t,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 Mt(o,e,r)}catch(a){throw new f(a.message,{code:"INVALID_PARAMETER"})}}var _={UserId:$f,PhoneNumber:Hf,Birthdate:Gf,Password:Wf,Email:zf,Url:Jf,newsletterGroup:eh,Params:th};var ue="skapi.enc.v1",co=6e5,qt=12,Or=null,bt=null;function lo(){return new f("Encryption requires Web Crypto, which needs a secure context (https, or localhost) in the browser, or Node 18 or newer. A page served over plain http has crypto.getRandomValues but crypto.subtle is undefined.",{code:"NOT_SUPPORTED"})}function uo(){if(bt)return bt;let t=typeof globalThis<"u"?globalThis:void 0;if(t?.crypto?.subtle&&typeof t.crypto.getRandomValues=="function")return bt=t.crypto,bt;try{let e=typeof globalThis<"u"?globalThis:void 0,r=null;if(e?.process&&typeof e.process.getBuiltinModule=="function"&&(r=e.process.getBuiltinModule("crypto")),!r&&typeof He=="function"&&(r=He("crypto")),r?.webcrypto?.subtle)return bt=r.webcrypto,bt}catch{}throw lo()}function Ee(){if(Or)return Or;let t=uo();if(!t.subtle)throw lo();return Or=t.subtle,Or}function ti(){try{return Ee(),!0}catch{return false}}function de(t){let e=uo(),r=new Uint8Array(t),n=65536;for(let i=0;i<t;i+=n)e.getRandomValues(r.subarray(i,Math.min(i+n,t)));return r}function j(t){let e=Jn(t),r;if(typeof Buffer<"u"&&typeof Buffer.from=="function")r=Buffer.from(e).toString("base64");else if(typeof btoa=="function"){let n="";for(let s=0;s<e.length;s+=32768)n+=String.fromCharCode.apply(null,Array.from(e.subarray(s,s+32768)));r=btoa(n);}else throw new f("No base64 encoder available in this environment.",{code:"NOT_SUPPORTED"});return r.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function H(t){if(typeof t!="string")throw new f("Expected a base64url string.",{code:"INVALID_PARAMETER"});let e=t.replace(/-/g,"+").replace(/_/g,"/"),r=e.length%4;if(r===2)e+="==";else if(r===3)e+="=";else if(r===1)throw new f("Malformed base64url string.",{code:"INVALID_PARAMETER"});if(typeof Buffer<"u"&&typeof Buffer.from=="function"){let n=Buffer.from(e,"base64");return new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}if(typeof atob=="function"){let n=atob(e),i=new Uint8Array(n.length);for(let s=0;s<n.length;s++)i[s]=n.charCodeAt(s);return i}throw new f("No base64 decoder available in this environment.",{code:"NOT_SUPPORTED"})}async function Fr(t){let e=await Ee().digest("SHA-256",t);return new Uint8Array(e)}async function jt(t,e,r,n){let i=Ee(),s=await i.importKey("raw",t,"HKDF",false,["deriveBits"]),o=await i.deriveBits({name:"HKDF",hash:"SHA-256",salt:e,info:r},s,n*8);return new Uint8Array(o)}async function wt(t,e,r,n){let i=Ee(),s=Y(t.normalize("NFC")),o=await i.importKey("raw",s,"PBKDF2",false,["deriveBits"]),a=new Uint8Array(await i.deriveBits({name:"PBKDF2",salt:e,iterations:r,hash:"SHA-256"},o,256)),c=await jt(a,e,n,32);B(a),B(s);let l=await ve(c);return B(c),l}async function ve(t){return Ee().importKey("raw",t,{name:"AES-GCM"},false,["encrypt","decrypt"])}async function fo(){let t=de(32),e=await ve(t);return {bytes:t,key:e}}async function Ae(t,e,r){let n=de(qt),i=await Ee().encrypt({name:"AES-GCM",iv:n,additionalData:r,tagLength:128},t,e);return {iv:n,ct:new Uint8Array(i)}}async function Ie(t,e,r,n){let i=await Ee().decrypt({name:"AES-GCM",iv:e,additionalData:n,tagLength:128},t,r);return new Uint8Array(i)}var Lr={name:"ECDH",namedCurve:"P-256"};async function ho(){let t=Ee(),e=await t.generateKey(Lr,true,["deriveBits"]),r=new Uint8Array(await t.exportKey("raw",e.publicKey)),n=new Uint8Array(await t.exportKey("pkcs8",e.privateKey)),i=await ri(n);return {pubRaw:r,pkcs8:n,priv:i}}async function ri(t){return Ee().importKey("pkcs8",t,Lr,false,["deriveBits"])}async function po(t){if(t.length!==65||t[0]!==4)throw new f("Malformed public key: expected a 65 byte uncompressed P-256 point.",{code:"INVALID_PARAMETER"});return Ee().importKey("raw",t,Lr,false,[])}async function ni(t){return j(await Fr(t))}async function go(t,e,r,n){let i=Ee(),s=await po(t),o=await i.generateKey(Lr,true,["deriveBits"]),a=new Uint8Array(await i.deriveBits({name:"ECDH",public:s},o.privateKey,256)),c=await jt(a,new Uint8Array(32),r,32);B(a);let l=await ve(c);B(c);let{iv:d,ct:h}=await Ae(l,e,n);return {epk:new Uint8Array(await i.exportKey("raw",o.publicKey)),iv:d,ct:h}}async function mo(t,e,r,n,i,s){let o=Ee(),a=await po(e),c=new Uint8Array(await o.deriveBits({name:"ECDH",public:a},t,256)),l=await jt(c,new Uint8Array(32),i,32);B(c);let d=await ve(l);return B(l),Ie(d,r,n,s)}function B(t){t&&t.length&&t.fill(0);}function rh(t,e){if(t.length!==e.length)return false;let r=0;for(let n=0;n<t.length;n++)r|=t[n]^e[n];return r===0}function ii(t){return Y(JSON.stringify(t))}function Kt(t,e,r){return Zn(t,new Uint8Array([0]),Y(e),new Uint8Array([0]),Y(r))}var tt="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Vt=16,oo=26,ao=28;function yo(t){let e=2166136261;for(let r=0;r<t.length;r++)e^=t[r],e=e*16777619>>>0;return e&1023}function bo(t){if(t.length!==Vt)throw new f(`A recovery code needs exactly ${Vt} bytes.`,{code:"INVALID_PARAMETER"});let e="",r=0,n=0;for(let s=0;s<t.length;s++)for(r=r<<8|t[s],n+=8;n>=5;)n-=5,e+=tt[r>>n&31];n>0&&(e+=tt[r<<5-n&31]);let i=yo(t);return e+=tt[i>>5&31]+tt[i&31],(e.match(/.{1,4}/g)||[]).join("-")}function _o(t){if(typeof t!="string")throw new f("Recovery code should be a string.",{code:"INVALID_PARAMETER"});let e=t.toUpperCase().replace(/[\s\-_]/g,"").replace(/O/g,"0").replace(/[IL]/g,"1");if(e.length!==ao)throw new f(`That does not look like a recovery code: expected ${ao} characters, got ${e.length}.`,{code:"ENCRYPTION_BAD_RECOVERY_CODE"});let r=e.slice(0,oo),n=e.slice(oo),i=0,s=0,o=[];for(let l=0;l<r.length;l++){let d=tt.indexOf(r[l]);if(d<0)throw new f(`That does not look like a recovery code: "${r[l]}" is not a valid character.`,{code:"ENCRYPTION_BAD_RECOVERY_CODE"});i=i<<5|d,s+=5,s>=8&&(s-=8,o.push(i>>s&255));}let a=new Uint8Array(o.slice(0,Vt)),c=yo(a);if(n!==tt[c>>5&31]+tt[c&31])throw new f("That recovery code has a typo in it: the check characters do not match.",{code:"ENCRYPTION_BAD_RECOVERY_CODE"});return a}async function si(t,e,r){let n=await jt(t,e,r,32),i=await ve(n);return B(n),i}var ei=[83,75,69,78,67,70],wo=2,Bt=56,Eo=16,nh=4*1024*1024;function oi(t){if(!t||t.length<Bt)return false;for(let e=0;e<ei.length;e++)if(t[e]!==ei[e])return false;return true}function rt(t,e,r){t[e]=r>>>24&255,t[e+1]=r>>>16&255,t[e+2]=r>>>8&255,t[e+3]=r&255;}function _t(t,e){return (t[e]<<24>>>0)+(t[e+1]<<16)+(t[e+2]<<8)+t[e+3]}function ih(t,e,r){let n=Math.floor(r/4294967296);rt(t,e,n),rt(t,e+4,r>>>0);}function sh(t,e){return _t(t,e)*4294967296+_t(t,e+4)}async function Ao(t,e,r,n,i,s){let o=Y(`${ue}|binfile|${r}|${n}|${i}|${s}`),a=await jt(t,e,o,32),c=await ve(a);return B(a),c}async function Ro(t){return (await Fr(Zn(Y(`${ue}|dekid`),t))).subarray(0,8)}function To(t,e,r){return ii([`${ue}|binchunk`,j(t),e,r])}function oh(t,e,r,n,i,s){let o=new Uint8Array(Bt+s.length);return o.set(ei,0),o[6]=wo,o[7]=s.length?1:0,rt(o,8,t),rt(o,12,e),o.set(r,16),ih(o,32,n),o.set(i,40),rt(o,48,s.length),rt(o,52,0),s.length&&o.set(s,Bt),o}async function So(t,e,r,n,i=nh){let s=de(Eo),o=await Ao(t,s,r.service,r.owner,r.recordOwner,r.recordId),a=await Ro(t),c=n?Y(JSON.stringify(n)):new Uint8Array(0);if(c.length>4096)throw new f("Encrypted file metadata is too large.",{code:"INVALID_PARAMETER"});let l=e.length===0?1:Math.ceil(e.length/i),d=oh(i,l,s,e.length,a,c),h=await Fr(d),u=[],p=d.length;for(let b=0;b<l;b++){let y=e.subarray(b*i,Math.min((b+1)*i,e.length)),E=await Ae(o,y,To(h,b,l));u.push(E),p+=4+E.iv.length+E.ct.length;}let g=new Uint8Array(p);g.set(d,0);let m=d.length;for(let b of u)rt(g,m,b.iv.length+b.ct.length),m+=4,g.set(b.iv,m),m+=b.iv.length,g.set(b.ct,m),m+=b.ct.length;return g}function ah(t){if(!oi(t))throw new f("This file is not an encrypted skapi file.",{code:"INVALID_PARAMETER"});let e=_t(t,48),r=Bt+e;if(t.length<r)throw new f("Encrypted file header is truncated.",{code:"INVALID_REQUEST"});let n=null;return e&&(n=JSON.parse(Lt(t.subarray(Bt,r)))),{version:t[6],chunkBytes:_t(t,8),count:_t(t,12),fileId:t.subarray(16,16+Eo),plainLen:sh(t,32),dekId:t.subarray(40,48),meta:n,headerLen:r}}async function vo(t,e,r){let n=ah(e);if(n.version!==wo)throw new f(`This file was encrypted by a different version of the SDK (container v${n.version}).`,{code:"NOT_SUPPORTED"});if(!n.count||!n.chunkBytes)throw new f("Encrypted file header is malformed.",{code:"INVALID_PARAMETER"});let i=await Ro(t);if(!rh(i,n.dekId))throw new f("This file was encrypted under a previous data key for this record, so it can no longer be opened. It was most likely left behind by an interrupted access change.",{code:"ENCRYPTION_FILE_STALE_KEY"});let s=await Ao(t,n.fileId,r.service,r.owner,r.recordOwner,r.recordId),o=await Fr(e.subarray(0,n.headerLen)),a=[],c=n.headerLen,l=0;for(let u=0;u<n.count;u++){if(c+4>e.length)throw new f("Encrypted file is truncated.",{code:"INVALID_REQUEST"});let p=_t(e,c);if(c+=4,p<qt+16||c+p>e.length)throw new f("Encrypted file is truncated.",{code:"INVALID_REQUEST"});let g=await Ie(s,e.subarray(c,c+qt),e.subarray(c+qt,c+p),To(o,u,n.count));c+=p,a.push(g),l+=g.length;}let d=new Uint8Array(l),h=0;for(let u of a)d.set(u,h),h+=u.length;return {bytes:d,meta:n.meta}}var ch="__skapi__keyring",$t="__skapi_enc__",Po=1,lh="skapi-enc",Je="keys",ci=new WeakMap;function ko(t){if(!t)return null;if(t===true&&(t={}),typeof t!="object")throw new f('"options.encryption" should be a boolean or an object.',{code:"INVALID_PARAMETER"});let e=typeof t.iterations=="number"?t.iterations:co;if(e<1e5)throw new f('"encryption.iterations" must be at least 100000.',{code:"INVALID_PARAMETER"});let r=t.trustPolicy==="strict"?"strict":"tofu";return {enabled:true,iterations:e,trustPolicy:r,persistDevice:t.persistDevice!==false,minPasswordLength:typeof t.minPasswordLength=="number"?t.minPasswordLength:0,withheld:t.withheld==="sentinel"?"sentinel":"null",recovery:t.recovery==="none"?"none":"code",table:typeof t.table=="string"&&t.table?t.table:ch}}function V(){return ci.get(this)||null}function Co(t){if(!t){ci.delete(this);return}ci.set(this,{cfg:t,status:"locked",reason:"NO_SESSION_KEY",user_id:"",scope:"",mk:null,ikPriv:null,pubRaw:null,fpr:"",keyringRecordId:"",pins:{},dek:new Map,roll:new Set,passthrough:new Map,rawRead:false,ready:null,unlocking:false,pendingRecoveryCode:"",peerPub:new Map,peerInflight:new Map});}function li(){let t=V.call(this);if(t){t.user_id&&wi.call(this,t).catch(()=>{}),t.ready=null,t.unlocking=false,t.pendingRecoveryCode="";for(let[,e]of t.dek)B(e.bytes);t.dek.clear(),t.roll.clear(),t.passthrough.clear(),t.peerPub.clear(),t.peerInflight.clear(),t.pins={},t.mk=null,t.ikPriv=null,t.pubRaw=null,t.fpr="",t.keyringRecordId="",t.user_id="",t.status="locked",t.reason="NO_SESSION_KEY";}}function xo(){let t=V.call(this);return t?{status:t.status,reason:t.status==="unlocked"?void 0:t.reason,user_id:t.user_id||void 0,fingerprint:t.fpr||void 0}:{status:"disabled"}}function Uo(t,e){return typeof e=="string"&&e===t.cfg.table}function Et(){return `${this.service}/${this.owner}`}function ui(t,e,r,n){let[i,s]=t.split("/");return ii([ue,i,s,e,r,n])}function Do(t,e,r,n,i){let[s,o]=t.split("/");return Y(`${ue}|dekwrap|${s}|${o}|${e}|${r}|${n}|${i}`)}function di(t){return t.anch==="uid"?t.uid:t.anch==="rid"?t.rid:""}function qr(t){return !!t&&typeof t=="object"&&!Array.isArray(t)&&typeof t[$t]=="number"&&typeof t.ct=="string"&&typeof t.iv=="string"&&typeof t.own=="string"&&typeof t.anch=="string"&&!!t.k&&typeof t.k=="object"&&!Array.isArray(t.k)}var No="__skapi_no_access__";function pe(t,e,r){if(t.withheld!=="sentinel")return null;let n={[No]:true,reason:e};return r&&(n.recipients=r),Object.freeze(n)}function fi(t){return !!t&&typeof t=="object"&&t[No]===true}var uh=256*1024,Wt="__skenc_ct__",Oo="payload.bin",dh=`/${Wt}/${Oo}`;function hi(t,e){return t===Wt&&e===Oo}async function fh(t,e,r){let n=e?.table,i=typeof n=="string"?n:n?.name;if(n&&(typeof n=="string"||n.access_group!==void 0))return {group:typeof n=="string"?0:Io(n.access_group),table:i,record:null};if(!r)return {group:n?.access_group!==void 0?Io(n.access_group):0,table:i,record:null};let s=t.dek.get(r);if(s)return {group:s.access_group,table:i,record:null};let o=await ze.call(this,r);if(!o)throw new f(`Record "${r}" not found.`,{code:"NOT_EXISTS"});return {group:o.table.access_group,table:o.table.name,record:o}}function hh(t){return this.getFile(t,{dataType:"blob"})}async function ze(t){let e=/^[a-zA-Z0-9]+$/.test(t)?{record_id:t}:{unique_id:t};return (await this.getRecords(e,{limit:1}))?.list?.[0]||null}function Io(t){return t==="private"||t==="*"||t==="**"?"private":t==="public"?0:t==="authorized"?1:t==="admin"?99:typeof t=="number"?t:0}function ai(t,e,r){let n=this.user?.user_id;if(!(!t||!t.user_id||!n||t.user_id===n))throw new f(`Record "${e}" belongs to another user (${t.user_id}), so ${r} would either seal it under the wrong key or strand its contents. Encryption only operates on records you own, no matter what access level you hold.`,{code:"ENCRYPTION_NOT_RECORD_OWNER"})}async function pi(t,e,r){let n=V.call(this);if(!n)return {send:t,plain:t,encrypted:false,omit:false};let i=e?.record_id||"",s=i,o=e?.unique_id||"";if(i&&n.passthrough.has(i)){let q=n.passthrough.get(i);return n.passthrough.delete(i),{send:q,plain:t,encrypted:true,omit:false}}let{group:a,table:c,record:l}=await fh.call(this,n,e,s);if(a!=="private"){let q=true;if(!r&&i){let se=l||await ze.call(this,i);if(se&&se.encrypted){if(ai.call(this,se,i,"making it non-private"),se.encrypted.status==="failed")throw new f(`Cannot make record "${i}" non-private: its current contents could not be decrypted (${se.encrypted.reason}), so they cannot be written back in the clear. Unlock encryption, or supply the record's data with the access group change.`,{code:"ENCRYPTION_LOCKED"});let Dt=!!se.bin&&Object.keys(se.bin).some(lr=>(se.bin[lr]||[]).some(Xi=>Xi&&Xi.encrypted));if(!Dt&&s){let lr=n.dek.get(s);lr&&(B(lr.bytes),n.dek.delete(s));}return {send:se.data,plain:se.data,encrypted:false,omit:false,files:Dt?"decrypt":void 0}}}let te=l;i&&!te&&(te=await ze.call(this,i).catch(()=>null)),te&&te.encrypted&&ai.call(this,te,i,"making it non-private");let cr=!!te&&!!te.bin&&Object.keys(te.bin).some(se=>(te.bin[se]||[]).some(Dt=>Dt&&Dt.encrypted));if(cr&&(q=false),q&&s){let se=n.dek.get(s);se&&(B(se.bytes),n.dek.delete(s));}return {send:t,plain:t,encrypted:false,omit:!r,files:cr?"decrypt":void 0}}if(Uo(n,c))return {send:t,plain:t,encrypted:false,omit:false};if(n.ready&&!n.unlocking)try{await n.ready;}catch{}if(!r)return {send:t,plain:t,encrypted:false,omit:true};if(fi.call(this,t))throw new f("This record's data could not be decrypted by this session, so it cannot be written back. Writing it would replace the record with the placeholder.",{code:"ENCRYPTION_CANNOT_REWRITE_WITHHELD"});if(n.status!=="unlocked"||!n.mk)throw new f("Encryption is enabled but locked, so this private record cannot be written. Call unlockEncryption({ password }) first, or the user must log in with their password.",{code:"ENCRYPTION_LOCKED"});if(t&&typeof t=="object"&&!Array.isArray(t)&&Object.prototype.hasOwnProperty.call(t,$t))throw new f(`"${$t}" is a reserved key in record data.`,{code:"INVALID_PARAMETER"});if(e?.service&&e.service!==this.service||e?.owner&&e.owner!==this.owner)throw new f("Encrypted records cannot be written to another project. The encryption key is derived per project, so a record written under one service and read under another could never be decrypted. Construct a separate Skapi instance for that project.",{code:"INVALID_REQUEST"});let d=this.user?.user_id;if(!d)throw new f("User login is required to write an encrypted record.",{code:"INVALID_REQUEST"});let h=Et.call(this),u=false;if(i&&n.roll.has(i)){u=true,n.roll.delete(i);let q=n.dek.get(i);n.dek.delete(i),q&&B(q.bytes);}let p=l;i&&!p&&!n.dek.has(i)&&(p=await ze.call(this,i).catch(()=>null)),p&&ai.call(this,p,i,"making it private");let g=!!p&&!p.encrypted&&!!p.bin&&Object.keys(p.bin).some(q=>(p.bin[q]||[]).some(te=>te&&!te.encrypted)),m=null;if(i&&!u&&(m=n.dek.get(i)||null,!m)){let q=p||l||await ze.call(this,i);if(q&&(s=q.record_id||i,m=n.dek.get(s)||null,!o&&q.unique_id&&(o=q.unique_id),!m&&q.encrypted?.status==="failed"))throw new f(`Cannot update encrypted record "${i}": its current contents could not be decrypted (${q.encrypted.reason}), so its existing key wraps cannot be preserved. Updating anyway would revoke everyone it is shared with.`,{code:"ENCRYPTION_LOCKED"})}s===i&&m&&m.rid&&(s=m.rid),!o&&m&&m.anch==="uid"&&m.uid&&(o=m.uid);let b,y,E;if(m){if(m.own&&m.own!==d)throw new f(`Record "${i}" belongs to another user (${m.own}). Encryption only operates on records you own.`,{code:"ENCRYPTION_NOT_RECORD_OWNER"});b=m.bytes,y=m.key,E=Object.assign({},m.recipients);}else {let q=await fo();b=q.bytes,y=q.key,E={};}let w=o?"uid":s?"rid":"new",T=w==="uid"?o:w==="rid"?s:"",R=ui(h,d,w,T),x=Kt(R,d,"mk"),O=await Ae(n.mk,b,x);E[d]={t:"mk",iv:j(O.iv),ct:j(O.ct)},m&&(m.anch!==w||di(m)!==T)&&(E=await ph.call(this,n,b,E,h,d,w,T,R));let U=Y(JSON.stringify(t===void 0?null:t)),I=await Ae(y,U,R);B(U);let D={[$t]:Po,enc:"A256GCM",kw:"ECDH-ES+A256GCM",anch:w,uid:o,rid:s,own:d,iv:j(I.iv),ct:j(I.ct),k:E},N,M,ie=D.ct;s&&ie.length>uh&&(N=H(ie),D.ct="",D.ct_ref=dh,m&&m.ctRef&&(M=m.ctRef));let ae=JSON.stringify(D).length;if(ae>2*1024*1024)throw new f(`Encrypted record data is too large: once encrypted and base64 encoded it becomes ${ae} bytes, over the ${2*1024*1024} byte limit. Encryption costs about 33% plus roughly 230 bytes per additional recipient.`,{code:"ENCRYPTED_DATA_TOO_LARGE"});return s&&n.dek.set(s,{bytes:b,key:y,recipients:E,anch:w,uid:o,rid:s,own:d,access_group:"private"}),{send:D,plain:t,encrypted:true,omit:false,spill:N,retireCt:M,dek:{bytes:b,key:y,recipients:E,anch:w,uid:o,rid:s,own:d,access_group:"private"},files:g?"encrypt":void 0}}function Fo(t,e){let r=V.call(this);!r||!e||!t||r.dek.has(t)||r.dek.set(t,Object.assign({},e,{rid:t}));}async function ph(t,e,r,n,i,s,o,a){let c=Object.keys(r).filter(h=>h!==i);if(!c.length)return r;let l=await Ei.call(this,c),d={[i]:r[i]};for(let h of c){let u=l[h];u&&(d[h]=await Lo.call(this,e,u,n,o,i,h,a));}return d}async function Lo(t,e,r,n,i,s,o){let a=Do(r,n,i,s,e.fpr),c=Kt(o,s,e.fpr),l=await go(e.pubRaw,t,a,c);return {t:"ecdh",epk:j(l.epk),iv:j(l.iv),ct:j(l.ct),fpr:e.fpr}}async function Mo(t,e){if(!qr(t))return {value:t};if(e.access_group!=="private")return {value:t};let r=V.call(this);if(!r)return {value:null,flag:{status:"failed",reason:"ENCRYPTION_DISABLED"}};if(r.rawRead)return {value:t};if(Uo(r,e.table_name))return {value:t};if(t[$t]!==Po)return {value:pe(r.cfg,"UNSUPPORTED_VERSION"),flag:{status:"failed",reason:"UNSUPPORTED_VERSION"}};if(r.ready&&!r.unlocking)try{await r.ready;}catch{}if(t.own!==e.user_id)return {value:pe(r.cfg,"BINDING_MISMATCH"),flag:{status:"failed",reason:"BINDING_MISMATCH"}};if(t.uid&&e.unique_id&&t.uid!==e.unique_id)return {value:pe(r.cfg,"BINDING_MISMATCH"),flag:{status:"failed",reason:"BINDING_MISMATCH"}};if(t.rid&&e.record_id&&t.rid!==e.record_id)return {value:pe(r.cfg,"BINDING_MISMATCH"),flag:{status:"failed",reason:"BINDING_MISMATCH"}};let n=this.user?.user_id,i=n?t.k[n]:null;if(!i)return {value:pe(r.cfg,"NOT_A_RECIPIENT",Object.keys(t.k)),flag:{status:"failed",reason:"NOT_A_RECIPIENT",recipients:Object.keys(t.k)}};if(r.status!=="unlocked"||!r.mk)return {value:pe(r.cfg,"NO_SESSION_KEY"),flag:{status:"failed",reason:"NO_SESSION_KEY"}};let s=Et.call(this),o=di(t),a=ui(s,t.own,t.anch,o),c;try{if(i.t==="mk")c=await Ie(r.mk,H(i.iv),H(i.ct),Kt(a,n,"mk"));else if(i.t==="ecdh"){if(!r.ikPriv)return {value:pe(r.cfg,"NO_SESSION_KEY"),flag:{status:"failed",reason:"NO_SESSION_KEY"}};c=await mo(r.ikPriv,H(i.epk),H(i.iv),H(i.ct),Do(s,o,t.own,n,i.fpr),Kt(a,n,i.fpr));}else return {value:pe(r.cfg,"UNSUPPORTED_VERSION"),flag:{status:"failed",reason:"UNSUPPORTED_VERSION"}}}catch{return {value:pe(r.cfg,"BAD_KEY"),flag:{status:"failed",reason:"BAD_KEY"}}}let l;try{if(t.ct_ref){if(!e.ctUrl)return B(c),{value:pe(r.cfg,"DATA_UNAVAILABLE"),flag:{status:"failed",reason:"DATA_UNAVAILABLE"}};let p=await hh.call(this,e.ctUrl);l=new Uint8Array(await p.arrayBuffer());}else l=H(t.ct);}catch{return B(c),{value:pe(r.cfg,"DATA_UNAVAILABLE"),flag:{status:"failed",reason:"DATA_UNAVAILABLE"}}}let d,h;try{h=await ve(c),d=await Ie(h,H(t.iv),l,a);}catch{return B(c),{value:pe(r.cfg,"CORRUPT"),flag:{status:"failed",reason:"CORRUPT"}}}let u;try{u=JSON.parse(Lt(d));}catch{return B(d),B(c),{value:pe(r.cfg,"CORRUPT"),flag:{status:"failed",reason:"CORRUPT"}}}if(B(d),e.record_id){let p=r.dek.get(e.record_id);p?(p.bytes=c,p.key=h,p.recipients=t.k,p.anch=t.anch,p.uid=t.uid,p.own=t.own,p.access_group="private",p.ctRef=t.ct_ref||""):r.dek.set(e.record_id,{bytes:c,key:h,recipients:t.k,anch:t.anch,uid:t.uid,rid:e.record_id,own:t.own,access_group:"private",ctRef:t.ct_ref||""});}else B(c);return {value:u,flag:{status:"encrypted",recipients:Object.keys(t.k)}}}function Ht(t,e){let[r,n]=t.split("/");return Y(`${ue}|kek|${r}|${n}|${e}`)}function Gt(t,e,r,n){let[i,s]=t.split("/");return Y(`${ue}|mk|${i}|${s}|${e}|PBKDF2-SHA256|${r}|${n}`)}function qo(t,e){let[r,n]=t.split("/");return Y(`${ue}|recovery|${r}|${n}|${e}`)}function Vo(t,e,r){let[n,i]=t.split("/");return Y(`${ue}|rk|${n}|${i}|${e}|HKDF-SHA256|${r}`)}function Bo(t,e){let[r,n]=t.split("/");return Y(`${ue}|self|${r}|${n}|${e}`)}function jo(t,e){let[r,n]=t.split("/");return Y(`${ue}|ik|${r}|${n}|${e}`)}async function Vr(t){let r=((await this.getRecords({table:{name:t.cfg.table,access_group:"private"},index:{name:"$user_id",value:this.user.user_id,condition:"="}},{limit:2}))?.list||[]).filter(n=>n.user_id===this.user.user_id);return r.length?(r.sort((n,i)=>n.uploaded-i.uploaded),r[0]):null}async function gi(t,e,r){let n=de(Vt),i=bo(n),s=de(16),o=j(s),a=await si(n,s,qo(t,e)),c=await Ae(a,r,Vo(t,e,o));return B(n),{code:i,wrap:{id:j(de(6)),p:"recovery",kdf:{a:"HKDF-SHA256",s:o},iv:j(c.iv),ct:j(c.ct),created:Date.now()}}}async function gh(t,e,r,n){let i=_o(n),s=(r||[]).filter(o=>o.p==="recovery");s.sort((o,a)=>(a.created||0)-(o.created||0));for(let o of s)try{let a=await si(i,H(o.kdf.s),qo(t,e)),c=await Ie(a,H(o.iv),H(o.ct),Vo(t,e,o.kdf.s));return B(i),c}catch{}return B(i),null}async function mh(t,e,r,n,i){let s=de(16),o=j(s),a=await wt(n,s,t.cfg.iterations,Ht(e,r)),c=await Ae(a,i,Gt(e,r,t.cfg.iterations,o));return {id:j(de(6)),p:"password",kdf:{a:"PBKDF2-SHA256",it:t.cfg.iterations,s:o},iv:j(c.iv),ct:j(c.ct),created:Date.now()}}async function yh(t,e){let r=this.user.user_id,n=t.scope,i=de(16),s=j(i),o=await wt(e,i,t.cfg.iterations,Ht(n,r)),a=de(32),c=await Ae(o,a,Gt(n,r,t.cfg.iterations,s)),l=await ve(a),d=await ho(),h=await Ae(l,d.pkcs8,jo(n,r));B(d.pkcs8);let u=null;t.cfg.recovery==="code"&&(u=await gi(n,r,a));let p=await Ae(l,a,Bo(n,r));B(a);let g=await ni(d.pubRaw),m=Date.now(),b=[{id:j(de(6)),p:"password",kdf:{a:"PBKDF2-SHA256",it:t.cfg.iterations,s},iv:j(c.iv),ct:j(c.ct),created:m}];u&&b.push(u.wrap);let y={v:1,alg:"ECDH-P-256",user_id:r,wraps:b,ik:{iv:j(h.iv),ct:j(h.ct)},self:{iv:j(p.iv),ct:j(p.ct)},pub:j(d.pubRaw),fpr:g,pins:null,created:m,updated:m};await this.postRecord({v:1,alg:"ECDH-P-256",user_id:r,pub:j(d.pubRaw),fpr:g,created:m},{table:{name:t.cfg.table,access_group:"authorized"},index:{name:"pubkey",value:r}});let E=await this.postRecord(y,{table:{name:t.cfg.table,access_group:"private"}}),w=await Vr.call(this,t);if(w&&w.record_id!==E.record_id){await Ko.call(this,t,w,e);return}t.mk=l,t.ikPriv=d.priv,t.pubRaw=d.pubRaw,t.fpr=g,t.keyringRecordId=E.record_id,u&&(t.pendingRecoveryCode=u.code),t.user_id=r,t.pins={},t.status="unlocked",t.reason="";}async function Ko(t,e,r){let n=this.user.user_id,i=t.scope,s=e.data;if(e.user_id!==n||s&&s.user_id&&s.user_id!==n)throw new f("The encryption keyring does not belong to this user.",{code:"ENCRYPTION_KEYRING_CORRUPT"});let a=(Array.isArray(s?.wraps)?s.wraps:[]).filter(d=>d.p==="password");if(!a.length)throw new f("The keyring has no password wrap.",{code:"ENCRYPTION_KEYRING_CORRUPT"});a.sort((d,h)=>(h.created||0)-(d.created||0));let c=null;for(let d of a)try{let h=H(d.kdf.s),u=await wt(r,h,d.kdf.it,Ht(i,n));c=await Ie(u,H(d.iv),H(d.ct),Gt(i,n,d.kdf.it,d.kdf.s));break}catch{}if(!c)throw new f("Incorrect password: the encryption keyring could not be opened.",{code:"ENCRYPTION_BAD_PASSWORD"});let l=await ve(c);B(c),await mi.call(this,t,e,l);}async function mi(t,e,r){let n=this.user.user_id,i=e.data,s=await Ie(r,H(i.ik.iv),H(i.ik.ct),jo(t.scope,n)),o=await ri(s);B(s);let a={};if(i.pins&&typeof i.pins=="object"&&i.pins.ct)try{let c=await Ie(r,H(i.pins.iv),H(i.pins.ct),Y(`${ue}|pins|${t.scope}|${n}`));a=JSON.parse(Lt(c)),B(c);}catch{a={};}t.mk=r,t.ikPriv=o,t.pubRaw=H(i.pub),t.fpr=i.fpr,t.keyringRecordId=e.record_id,t.user_id=n,t.pins=a,t.status="unlocked",t.reason="";}async function Br(t){let e=V.call(this);if(!e||!this.user?.user_id)return;if(!ti()){e.status="locked",e.reason="NO_WEB_CRYPTO";return}if(this.user?.is_openid){e.status="locked",e.reason="OPENID_UNSUPPORTED";return}if(e.cfg.minPasswordLength&&t.length<e.cfg.minPasswordLength){e.status="locked",e.reason="WEAK_PASSWORD";return}e.scope=Et.call(this);let r=await Vr.call(this,e);r?await Ko.call(this,e,r,t):await yh.call(this,e,t),e.cfg.persistDevice&&await zo.call(this,e).catch(()=>{});}async function $o(t){await this.__connection;let e=V.call(this);if(!e)throw new f("Encryption is not enabled for this instance.",{code:"INVALID_REQUEST"});if(!this.user?.user_id)throw new f("User login is required.",{code:"INVALID_REQUEST"});if(!t?.password||typeof t.password!="string")throw new f('"password" is required.',{code:"INVALID_PARAMETER"});if(await Br.call(this,t.password),e.status!=="unlocked")throw new f(`Encryption could not be unlocked: ${e.reason}`,{code:"ENCRYPTION_LOCKED"});return {status:e.status}}async function Ho(t){this.__projectIdInput&&await this.__projectIdInput;let e=V.call(this);return e?(t?.forgetDevice&&await wi.call(this,e).catch(()=>{}),li.call(this),this.__cached_requests={},{status:e.status}):{status:"disabled"}}async function Go(t,e){let r=V.call(this);if(!r)return;if(r.status!=="unlocked"||!r.mk)throw new f("Encryption must be unlocked before changing the password, or the encryption keyring would be left wrapped under a password that no longer exists. Call unlockEncryption({ password }) first.",{code:"ENCRYPTION_LOCKED"});let i=(await this.getRecords({record_id:r.keyringRecordId},{limit:1}))?.list?.[0];if(!i)throw new f("The encryption keyring could not be read, so the password change was stopped before it could strand it.",{code:"ENCRYPTION_KEYRING_CORRUPT"});let s=this.user.user_id,o=i.data,a=(o.wraps||[]).filter(m=>m.p==="password");a.sort((m,b)=>(b.created||0)-(m.created||0));let c=null;for(let m of a)try{let b=await wt(t,H(m.kdf.s),m.kdf.it,Ht(r.scope,s));c=await Ie(b,H(m.iv),H(m.ct),Gt(r.scope,s,m.kdf.it,m.kdf.s));break}catch{}if(!c)throw new f("Incorrect current password: the encryption keyring was not re-wrapped.",{code:"ENCRYPTION_BAD_PASSWORD"});let l=de(16),d=j(l),h=await wt(e,l,r.cfg.iterations,Ht(r.scope,s)),u=await Ae(h,c,Gt(r.scope,s,r.cfg.iterations,d));B(c);let p=Date.now(),g=(o.wraps||[]).concat([{id:j(de(6)),p:"password",kdf:{a:"PBKDF2-SHA256",it:r.cfg.iterations,s:d},iv:j(u.iv),ct:j(u.ct),created:p}]);await this.postRecord(Object.assign({},o,{wraps:g,updated:p}),{record_id:r.keyringRecordId});}async function Wo(){let t=V.call(this);if(!t||t.status!=="unlocked"||!t.keyringRecordId)return;let r=(await this.getRecords({record_id:t.keyringRecordId},{limit:1}))?.list?.[0];if(!r)return;let n=r.data,i=(n.wraps||[]).filter(o=>o.p==="password").sort((o,a)=>(a.created||0)-(o.created||0)),s=(n.wraps||[]).filter(o=>o.p!=="password");i.length<=1||await this.postRecord(Object.assign({},n,{wraps:[i[0]].concat(s),updated:Date.now()}),{record_id:t.keyringRecordId});}function yi(){return typeof indexedDB<"u"&&!!indexedDB}function bi(){return new Promise((t,e)=>{let r=indexedDB.open(lh,1);r.onupgradeneeded=()=>{let n=r.result;n.objectStoreNames.contains(Je)||n.createObjectStore(Je);},r.onsuccess=()=>t(r.result),r.onerror=()=>e(r.error);})}function _i(t){return `${t.scope}#${this.user?.user_id}`}async function zo(t){if(!yi()||!t.mk)return;let e=await bi();await new Promise((r,n)=>{let i=e.transaction(Je,"readwrite");i.objectStore(Je).put({mk:t.mk,keyringRecordId:t.keyringRecordId,saved:Date.now()},_i.call(this,t)),i.oncomplete=()=>r(),i.onerror=()=>n(i.error);}),e.close();}async function bh(t){if(!yi())return null;let e=await bi(),r=await new Promise((n,i)=>{let o=e.transaction(Je,"readonly").objectStore(Je).get(_i.call(this,t));o.onsuccess=()=>n(o.result||null),o.onerror=()=>i(o.error);});return e.close(),r&&r.mk?r:null}async function wi(t){if(!yi())return;let e=await bi();await new Promise((r,n)=>{let i=e.transaction(Je,"readwrite");i.objectStore(Je).delete(_i.call(this,t)),i.oncomplete=()=>r(),i.onerror=()=>n(i.error);}),e.close();}function Jo(){let t=V.call(this);!t||t.ready||(t.unlocking=true,t.ready=_h.bind(this)().catch(()=>false).then(()=>{t.unlocking=false;}));}async function _h(){let t=V.call(this);if(!t||!this.user?.user_id||!t.cfg.persistDevice||!ti())return false;t.scope=Et.call(this);try{let e=await bh.call(this,t);if(!e)return !1;let r=await Vr.call(this,t);return r?(await mi.call(this,t,r,e.mk),!0):(await wi.call(this,t).catch(()=>{}),!1)}catch{return t.status="locked",t.reason="NO_SESSION_KEY",false}}async function Ei(t){let e=V.call(this);if(!e)throw new f("Encryption is not enabled for this instance.",{code:"INVALID_REQUEST"});let r={},n=[],i=false;for(let s of t){let o=e.peerPub.get(s);o?r[s]=o:n.push(s);}return await Promise.all(n.map(async s=>{let o=e.peerInflight.get(s);o||(o=(async()=>{let l=((await this.getRecords({table:{name:e.cfg.table,access_group:"authorized"},index:{name:"$user_id",value:s,condition:"="}},{limit:10}))?.list||[]).filter(p=>p.user_id===s&&p.data?.pub);if(!l.length)return null;l.sort((p,g)=>g.uploaded-p.uploaded);let d=H(l[0].data.pub),h=await ni(d),u=e.pins[s];if(u&&u!==h)throw new f(`The public key for user "${s}" has changed since it was first seen. This is expected if they reset their account, and is what a key substitution attack also looks like. Verify the new fingerprint out of band, then call pinPeerKey({ user_id, fingerprint }).`,{code:"ENCRYPTION_PEER_KEY_CHANGED"});if(!u){if(e.cfg.trustPolicy==="strict")throw new f(`No pinned key for user "${s}" and trustPolicy is "strict". Pin it first with pinPeerKey().`,{code:"ENCRYPTION_PEER_NOT_PINNED"});e.pins[s]=h,i=true;}return {pubRaw:d,fpr:h}})().finally(()=>e.peerInflight.delete(s)),e.peerInflight.set(s,o));let a=await o;a&&e.peerPub.set(s,a),r[s]=a;})),i&&await Zo.call(this,e).catch(()=>{}),r}async function Yo(t,e){let r=Et.call(this),n=t.dek.get(e);if(n)return {entry:n,scope:r};let i=await ze.call(this,e);if(!i)throw new f(`Record "${e}" not found.`,{code:"NOT_EXISTS"});if(i.encrypted?.status==="failed"&&i.encrypted.reason==="DATA_UNAVAILABLE")throw new f(`Cannot change sharing on record "${e}": its data could not be read, so whether it is encrypted is unknown. Retry once the record reads normally.`,{code:"ENCRYPTION_DATA_UNAVAILABLE"});if(!i.encrypted)return null;if(i.user_id!==this.user?.user_id)throw new f("Only the record owner can share or revoke an encrypted record, because adding or removing a key wrap means writing the record.",{code:"ENCRYPTION_GRANT_REQUIRES_OWNER"});let s=t.dek.get(i.record_id)||t.dek.get(e);if(!s)throw new f(`Cannot change sharing on record "${e}": its data could not be decrypted`+(i.encrypted.reason?` (${i.encrypted.reason})`:"")+".",{code:"ENCRYPTION_LOCKED"});return {entry:s,scope:r}}async function Ai(t,e){let r=V.call(this);if(!r)return;let n=await Yo.call(this,r,t);if(!n)return;let{entry:i,scope:s}=n,o=this.user.user_id;if(i.own!==o)throw new f("Only the record owner can share an encrypted record, because adding a key wrap means writing the record.",{code:"ENCRYPTION_GRANT_REQUIRES_OWNER"});let a=await Ei.call(this,e),c=e.filter(u=>!a[u]);if(c.length)throw new f(`These users have no encryption key yet, so they cannot be given access: ${c.join(", ")}. A user's key is created the first time they log in with encryption enabled.`,{code:"ENCRYPTION_RECIPIENT_HAS_NO_KEY"});let l=di(i),d=ui(s,i.own,i.anch,l),h=Object.assign({},i.recipients);for(let u of e)u!==o&&(h[u]=await Lo.call(this,i.bytes,a[u],s,l,i.own,u,d));await Eh.call(this,r,t,i,h);}async function Qo(t,e){let r=V.call(this);if(!r)return;let n=await Yo.call(this,r,t);if(!n)return;let{entry:i}=n,s=this.user.user_id;if(i.own!==s)throw new f("Only the record owner can revoke access to an encrypted record.",{code:"ENCRYPTION_GRANT_REQUIRES_OWNER"});let o=Object.keys(i.recipients).filter(l=>l===s?true:e?!e.includes(l):false).filter(l=>l!==s),a=await ze.call(this,t);if(!a)throw new f(`Record "${t}" not found.`,{code:"NOT_EXISTS"});wh(a,t);let c={};if(o.length){c=await Ei.call(this,o);let l=o.filter(d=>!c[d]);if(l.length)throw new f(`Cannot revoke on record "${t}": these users keep access but their encryption keys could not be read, so re-sharing after the key roll would fail and lock them out: ${l.join(", ")}.`,{code:"ENCRYPTION_RECIPIENT_HAS_NO_KEY"})}r.roll.add(a.record_id||t),await this.postRecord(a.data,{record_id:a.record_id||t,table:{name:a.table.name,access_group:"private"}}),o.length&&await Ai.call(this,a.record_id||t,o);}function wh(t,e){if(t?.encrypted?.status==="failed")throw new f(`Cannot change sharing on record "${e}": its current data could not be read (${t.encrypted.reason}), so re-writing the record would destroy it.`,{code:"ENCRYPTION_DATA_UNAVAILABLE"})}async function Eh(t,e,r,n){let i=await Ah.call(this,e);if(!i)throw new f(`Cannot change sharing on record "${e}": its stored envelope could not be read.`,{code:"ENCRYPTION_DATA_UNAVAILABLE"});r.recipients=n,t.dek.set(e,r);let s=Object.assign({},i,{k:n});t.passthrough.set(e,s),await this.postRecord(void 0,{record_id:e});}async function Ah(t){let e=V.call(this);if(!e)return null;e.rawRead=true;let r;try{r=(await this.getRecords({record_id:t},{limit:1}))?.list?.[0];}finally{e.rawRead=false;}return r&&qr(r.data)?r.data:null}async function Xo(t){this.__projectIdInput&&await this.__projectIdInput;let e=V.call(this);if(!e||e.status!=="unlocked")throw new f("Encryption is locked.",{code:"ENCRYPTION_LOCKED"});e.pins[t.user_id]=t.fingerprint,e.peerPub.delete(t.user_id),await Zo.call(this,e);}async function Zo(t){if(!t.mk||!t.keyringRecordId)return;let r=(await this.getRecords({record_id:t.keyringRecordId},{limit:1}))?.list?.[0];if(!r)return;let n=await Ae(t.mk,Y(JSON.stringify(t.pins)),Y(`${ue}|pins|${t.scope}|${t.user_id}`));await this.postRecord(Object.assign({},r.data,{pins:{iv:j(n.iv),ct:j(n.ct)},updated:Date.now()}),{record_id:t.keyringRecordId});}function ea(){let t=V.call(this);if(!t||!t.pendingRecoveryCode)return null;let e=t.pendingRecoveryCode;return t.pendingRecoveryCode="",e}async function ta(t){await this.__connection;let e=V.call(this);if(!e)throw new f("Encryption is not enabled for this instance.",{code:"INVALID_REQUEST"});if(!this.user?.user_id)throw new f("User login is required. Reset the password and log in first, then use the recovery code.",{code:"INVALID_REQUEST"});if(!t?.code||typeof t.code!="string")throw new f('"code" is required.',{code:"INVALID_PARAMETER"});e.scope=Et.call(this);let r=this.user.user_id,n=await Vr.call(this,e);if(!n)throw new f("This account has no encryption keyring, so there is nothing to recover.",{code:"NOT_EXISTS"});let i=await gh(e.scope,r,n.data?.wraps||[],t.code);if(!i)throw new f("That recovery code did not open the keyring. Check it against the copy you saved when encryption was set up.",{code:"ENCRYPTION_BAD_RECOVERY_CODE"});let s=await ve(i);await mi.call(this,e,n,s);let o=false,a=null,c=(n.data?.wraps||[]).slice();if(t.password&&(c=c.filter(l=>l.p!=="password"),c.push(await mh(e,e.scope,r,t.password,i)),o=true),e.cfg.recovery==="code"){let l=await gi(e.scope,r,i);c=c.filter(d=>d.p!=="recovery"),c.push(l.wrap),a=l.code;}return B(i),await this.postRecord(Object.assign({},n.data,{wraps:c,updated:Date.now()}),{record_id:n.record_id}),e.cfg.persistDevice&&await zo.call(this,e).catch(()=>{}),{status:e.status,repaired:o,recoveryCode:a}}async function ra(){await this.__connection;let t=V.call(this);if(!t)throw new f("Encryption is not enabled for this instance.",{code:"INVALID_REQUEST"});if(t.status!=="unlocked"||!t.mk)throw new f("Encryption must be unlocked to issue a recovery code. Only someone who can already decrypt can create one.",{code:"ENCRYPTION_LOCKED"});if(t.cfg.recovery!=="code")throw new f('Recovery codes are disabled for this instance ("recovery" is "none").',{code:"INVALID_REQUEST"});let r=(await this.getRecords({record_id:t.keyringRecordId},{limit:1}))?.list?.[0];if(!r)throw new f("The encryption keyring could not be read.",{code:"ENCRYPTION_KEYRING_CORRUPT"});let n=r.data?.self;if(!n||!n.ct)throw new f("This keyring predates recovery-code rotation and cannot issue a new code. Use unlockWithRecoveryCode() with the existing code, which issues a replacement.",{code:"ENCRYPTION_KEYRING_CORRUPT"});let i=await Ie(t.mk,H(n.iv),H(n.ct),Bo(t.scope,t.user_id)),s=await gi(t.scope,t.user_id,i);B(i);let o=(r.data.wraps||[]).filter(a=>a.p!=="recovery").concat([s.wrap]);return await this.postRecord(Object.assign({},r.data,{wraps:o,updated:Date.now()}),{record_id:t.keyringRecordId}),{recoveryCode:s.code}}var Mr="__skenc__",na="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function Rh(t){if(t===0)return "0";let e="";for(;t>0;)e=na[t%62]+e,t=Math.floor(t/62);return e}function Th(t){let e=0;for(let r of t){let n=na.indexOf(r);if(n<0)return NaN;e=e*62+n;}return e}function jr(t){if(typeof t!="string")return null;let e=t.lastIndexOf(Mr);if(e<0)return null;let r=Th(t.slice(e+Mr.length));return Number.isFinite(r)?{key:t.slice(0,e),plainSize:r}:null}function Ri(t){try{let e=String(t).split("?")[0].split("/").slice(3);if(e.length<12||e[4]!=="records"||e[7]!=="bin")return null;let r=jr(e[10]);return r?{recordId:e[5],recordOwner:e[3],filename:e[e.length-1],plainSize:r.plainSize}:null}catch{return null}}function ia(t,e){return {service:this.service,owner:this.owner,recordOwner:e,recordId:t}}async function sa(t,e,r){let n=V.call(this);if(!n||!t)return {key:e,file:r,encrypted:false};let i=n.dek.get(t);if(!i)return {key:e,file:r,encrypted:false};if(jr(e))throw new f(`"${Mr}" is reserved in an upload form key.`,{code:"INVALID_PARAMETER"});if(e===Wt)return {key:e,file:r,encrypted:false};let s=new Uint8Array(await r.arrayBuffer()),o={n:r.name,t:r.type||"",lm:r.lastModified||0},a=await So(i.bytes,s,ia.call(this,t,i.own),o);return B(s),{key:`${e}${Mr}${Rh(r.size)}`,file:new File([a],r.name,{type:"application/octet-stream"}),encrypted:true}}async function oa(t,e){let r=V.call(this),n=Ri(t);if(!r||!n)return e;let i=r.dek.get(n.recordId);if(!i)throw new f(`Cannot open this file: the data key for record "${n.recordId}" is not available. Read the record first, and make sure encryption is unlocked.`,{code:"ENCRYPTION_LOCKED"});let s=new Uint8Array(await e.arrayBuffer());if(!oi(s))throw new f("This file is marked as encrypted but its contents are not an encrypted container.",{code:"ENCRYPTION_FILE_CORRUPT"});let o=await vo(i.bytes,s,ia.call(this,n.recordId,n.recordOwner)),a=o.meta&&o.meta.t||"application/octet-stream";return new Blob([o.bytes],{type:a})}function Sh(t){let e=[];for(let r in t?.bin||{})for(let n of t.bin[r]||[])n&&n.encrypted&&e.push({formKey:r,url:n.url,filename:n.filename});return e}function vh(t){let e=[];for(let r in t?.bin||{})for(let n of t.bin[r]||[])n&&!n.encrypted&&e.push({formKey:r,url:n.url,filename:n.filename});return e}async function Ti(t,e,r){let n=V.call(this);if(!n)return [];let i=await ze.call(this,t);if(!i)return [];let s=e==="decrypt"?Sh(i):vh(i);if(!s.length)return [];let o=[],a=new FormData,c=false;for(let l of s){let d=i.bin[l.formKey].find(u=>u.url===l.url);if(!d||typeof d.getFile!="function")continue;let h=await d.getFile("blob");h&&(a.append(l.formKey,new File([h],l.filename,{type:h.type||"application/octet-stream"})),o.push(l.url),c=true);}if(!c)return [];if(e==="decrypt"){let l=n.dek.get(t);l&&(B(l.bytes),n.dek.delete(t));}return await this.uploadFiles(a,{record_id:t,progress:r}),o}var W=null;function zt(t){let e={tkid:"ticket_id",cond:"condition",stmp:"timestamp",upd:"updated",acts:"actions",actn:"action",cnt:"count",ttl:"time_to_live",plch:"placeholder",hash:"hash",desc:"description",pmc:"limit_per_user",fail:"failed",rv:"rules_version",on:"enabled"},r={};for(let n in t)if(n==="tkid"){let i=t[n].split("#");if(i.length===1){r.ticket_id=i[0];continue}r.ticket_id=i[1],r.consume_id=i[2],r.user_id=i.slice(3).join("#");let s=i[2].slice(-4);if(r.is_test=s===":CHK",!t.stmp){let o=i[2].slice(0,-4);/^[0-9]+$/.test(o)?r.timestamp=parseInt(o,10):r.timestamp=Se(i[2].slice(0,-4));}}else e[n]?r[e[n]]=t[n]:r[n]=t[n];return r}async function ca(t){if(!t?.ticket_id)throw new f("Ticket ID is required.",{code:"INVALID_PARAMETER"});if(!/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(t.ticket_id))throw new f('Invalid "ticket_id". Use letters, digits, "_" and "-" (up to 64 chars, starting with a letter or digit).',{code:"INVALID_PARAMETER"});if(!t.method)throw new f('Method is required. Should be either "GET" or "POST"',{code:"INVALID_PARAMETER"});let e=String(t.method).toUpperCase();if(e!=="GET"&&e!=="POST")throw new f('Method should be either "GET" or "POST".',{code:"INVALID_PARAMETER"});let r=!!t.auth;if(r&&e==="GET")throw new f("Signed-in consumption is POST only.",{code:"INVALID_PARAMETER"});await this.__connection;let n=r?"tpa":e==="GET"?"tg":"tp",i=`https://${this.service.slice(0,4)}.${this.customApiDomain}/${n}/${this.service}/${t.ticket_id}`,s=await P.bind(this)(i,t.data||{},{method:e,auth:r},{ignoreService:true});if(s&&typeof s=="object"&&s.stage)throw new f(s.message,{code:s.code,cause:s});return !s||typeof s!="object"||Array.isArray(s)||typeof s.tkid!="string"?s:zt(s)}async function la(t,e){await this.__connection;let r=await P.bind(this)("ticket",Object.assign({exec:"list"},t||{}),{auth:true,fetchOptions:e});return r.list=r.list.map(zt),r}async function ua(t){if(!t?.ticket_id)throw new f("Ticket ID is required.",{code:"INVALID_PARAMETER"});let e=t.before===void 0||t.before===null?Date.now():t.before;if(typeof e!="number"||!Number.isInteger(e)||e<=0)throw new f('"before" should be a time in milliseconds since the epoch.',{code:"INVALID_PARAMETER"});return P.bind(this)("register-ticket",{exec:"clearlog",ticket_id:t.ticket_id,before:e},{auth:true})}async function da(t,e){await this.__connection;let r=await P.bind(this)("ticket",Object.assign({exec:"consumed"},t||{}),{auth:true,fetchOptions:e});return r.list=r.list.map(zt),r}async function fa(t){let e=await P.bind(this)("register-ticket",Object.assign({exec:"reg"},t),{auth:true});return e&&typeof e=="object"&&e.ticket&&(e.ticket=zt(e.ticket)),e}async function ha(t){return P.bind(this)("register-ticket",Object.assign({exec:"unreg"},t),{auth:true})}async function pa(t){if(!t?.ticket_id)throw new f('"ticket_id" is required.',{code:"INVALID_PARAMETER"});if(typeof t.enabled!="boolean")throw new f('"enabled" should be true or false.',{code:"INVALID_PARAMETER"});let e=await P.bind(this)("register-ticket",{exec:"update",ticket_id:t.ticket_id,enabled:t.enabled},{auth:true});return e?.ticket&&(e.ticket=zt(e.ticket)),e}var Ih=3600;async function At(){if(await this.__connection,this.session){let t=Math.floor(Date.now()/1e3),r=this.session.getIdToken().getExpiration();if(r<t+Ih){this.log("request:requesting new token",null);try{await re.bind(this)().getSession({refreshToken:!0}),this.log("request:received new tokens",{exp:this.session?.idToken?.payload?.exp,currentTime:t,expiresIn:r-t,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:t,expiresIn:r-t,token:this.session.accessToken.jwtToken,refreshToken:this.session.refreshToken.token});return this.session?.idToken?.jwtToken}else throw this.log("request:no session",null),je.bind(this)(),new f("User login is required.",{code:"INVALID_REQUEST"})}function aa(t,e){return new Promise((r,n)=>{e.refreshSession(t.getRefreshToken(),(i,s)=>{this.log("getSession:refreshSessionCallback",{refreshErr:i,refreshedSession:s}),i?(je.bind(this)(),n(i)):s.isValid()?r(s):(je.bind(this)(),n(new f("Invalid session.",{code:"INVALID_REQUEST"})));});})}function re(){if(!this.userPool)throw new f("User pool is missing",{code:"INVALID_REQUEST"});let t=()=>{let s=W.getSignInUserSession().getIdToken().payload||null,o=Ft(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:c=false,skipUserUpdateEventTrigger:l=false}=s||{};if(c&&l&&(l=false),W=this.userPool.getCurrentUser(),!W){this.log("getSession:cognitoUser",W),je.bind(this)(),a(null);return}let d=h=>{let u=h.getIdToken().payload;if(this.log("getSession:respond:sessionAttribute",u),u["custom:service"]!==this.service)throw this.log("getSession:respond","invalid service, signing out"),je.bind(this)(),new f("Invalid session.",{code:"INVALID_REQUEST"});return this.session=h,t(),l||this._runOnUserUpdateListeners(this.user),this.session};W.getSession((h,u)=>{if(this.log("getSession:getSessionCallback",{err:h,session:u}),!u){je.bind(this)(),a(new f("Current session does not exist.",{code:"INVALID_REQUEST"}));return}if(h){aa.bind(this)(u,W).then(y=>o(d(y))).catch(a);return}let p=Math.floor(Date.now()/1e3),g=u.getIdToken(),m=g.getExpiration(),b=m<p;if(this.log("getSession:currentTime",p),this.log("getSession:idTokenExp",m),this.log("getSession:isExpired",b),this.log("getSession:existingBearerToken",this.bearerToken),this.bearerToken=g.getJwtToken(),b||c||!u.isValid())aa.bind(this)(u,W).then(y=>o(d(y))).catch(a);else try{o(d(u));}catch(y){a(y);}});}),r=(s,o)=>{let a=o||s.includes(this.service+"-")?s:this.service+"-"+he.hash(s);return {cognitoUser:new Ve({Username:a,Pool:this.userPool}),cognitoUsername:a}};return {getSession:e,authenticateUser:(s,o,a=false,c=false)=>new Promise((l,d)=>{this.__request_signup_confirmation=null,this.__disabledAccount=null;let h=r(s,a),u=h.cognitoUsername,p=new gn({Username:u,Password:o});h.cognitoUser.authenticateUser(p,{newPasswordRequired:(g,m)=>{this.__disabledAccount=null,this.__request_signup_confirmation=u,g["custom:signup_ticket"]==="PASS"||g["custom:signup_ticket"]==="MEMBER"||g["custom:signup_ticket"]==="OIDPASS"?h.cognitoUser.completeNewPasswordChallenge(o,{},{onSuccess:b=>{W=h.cognitoUser,e().then(async y=>{if(V.call(this))try{await Br.bind(this)(o);}catch(E){this.log("encryption:ensureKeyring:failed",E);}l(this.user);});},onFailure:b=>{d(new f(b.message||"Failed to authenticate user.",{code:b.code}));}}):d(new f("User's signup confirmation is required.",{code:"SIGNUP_CONFIRMATION_NEEDED"}));},onSuccess:g=>e({skipUserUpdateEventTrigger:true}).then(async m=>{if(this.__disabledAccount=null,V.call(this))try{await Br.bind(this)(o);}catch(b){this.log("encryption:ensureKeyring:failed",b);}this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user),l(this.user);}),onFailure:g=>{let m=[],{parsed:b,code:y}=Kr(g),E=typeof g?.message=="string"?g.message:"";if(y==="NotAuthorizedException"?E.includes("User is disabled.")?(this.__disabledAccount=u,m=["This account is disabled.","USER_IS_DISABLED"]):c?m=["The account already exists.","ACCOUNT_EXISTS"]:m=["Incorrect username or password.","INCORRECT_USERNAME_OR_PASSWORD"]:y==="UserNotFoundException"?m=["Incorrect username or password.","INCORRECT_USERNAME_OR_PASSWORD"]:y==="UserNotConfirmedException"?(this.__request_signup_confirmation=u,m=["User's signup confirmation is required.","SIGNUP_CONFIRMATION_NEEDED"]):(y==="TooManyRequestsException"||y==="LimitExceededException")&&(m=["Too many attempts. Please try again later.","REQUEST_EXCEED"]),b.code==="SIGNUP_CONFIRMATION_NEEDED"&&(this.__request_signup_confirmation=u),m.length){let w=m[1],T=m[0];d(new f(T,{code:w,cause:g}));}else d(b);}});}),createCognitoUser:r,signup:(s,o,a)=>new Promise((c,l)=>{this.userPool.signUp(s,o,a,null,(d,h)=>{if(d){let{parsed:u,code:p}=Kr(d),g=[];p==="UsernameExistsException"?g=["The account already exists.","EXISTS"]:p==="InvalidPasswordException"?g=["Invalid password. Password must be at least 6 characters.","INVALID_PARAMETER"]:p==="InvalidParameterException"?g=[u.message||"Invalid parameter.","INVALID_PARAMETER"]:p==="TooManyRequestsException"||p==="LimitExceededException"?g=["Too many attempts. Please try again later.","REQUEST_EXCEED"]:p==="CodeDeliveryFailureException"?g=["Failed to deliver verification code.","CODE_DELIVERY_FAILURE"]:p==="UserLambdaValidationException"&&(g=[u.message||"Signup validation failed.",u.code==="EXISTS"?"EXISTS":"INVALID_REQUEST"]),g.length?l(new f(g[0],{code:g[1],cause:d})):l(u);return}c(h);});})}}function Kr(t){let e=typeof t?.code=="string"&&t.code.trim()?t.code.trim():"ERROR",n=((typeof t?.message=="string"?t.message:typeof t=="string"?t:"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:t}),code:e}}async function ga(t){await this.__authConnection;let e=t?.refreshToken||false;if(!e)return this.user;try{return await re.bind(this)().getSession(Object.assign({skipUserUpdateEventTrigger:!e,refreshToken:e},t)),this.user}catch{return null}}async function ma(t){await this.__connection,t=_.Params(t,{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:t.token,id:t.id,merge:t.merge};t.template?.welcome&&(e.template_welcome=t.template.welcome);let r=await P.bind(this)("openid-logger",e),n=r.logger.split("#"),i=this.service+"-"+n[0],s=n[1];return {userProfile:await re.bind(this)().authenticateUser(i,s,true,true),openid:r.openid}}function Ph(t){let e=typeof globalThis<"u"?globalThis:void 0;if(e?.Buffer)return e.Buffer.from(t,"base64").toString("utf8");if(typeof atob=="function"){let r=atob(t),n=new Uint8Array(r.length);for(let i=0;i<r.length;i++)n[i]=r.charCodeAt(i);return typeof TextDecoder<"u"?new TextDecoder().decode(n):r}throw new Error("No base64 decoder available in this environment")}function kh(t){let e=t.split(".");if(e.length!==3)throw new Error("Invalid JWT format");let n=e[1].replace(/-/g,"+").replace(/_/g,"/"),i=Ph(n);return JSON.parse(i)}async function ya(t){await this.__authConnection,this.log("loginWithToken:params",t),t=_.Params(t,{idToken:"string",accessToken:"string",refreshToken:"string"},["idToken"]);let e=kh(t.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 r=Math.floor(Date.now()/1e3);if(e.exp&&e.exp<r)throw new f("Token has expired.",{code:"INVALID_REQUEST"});if(this.__user=Ft(e),this.session=null,t.accessToken&&t.refreshToken)try{if(this.session=new mt({IdToken:new pt({IdToken:t.idToken}),AccessToken:new ht({AccessToken:t.accessToken}),RefreshToken:new gt({RefreshToken:t.refreshToken})}),this.log("loginWithToken:session",this.session),this.log("loginWithToken:CognitoUser",Ve),this.log("loginWithToken:userPool",this.userPool),Ve&&this.userPool){this.log("loginWithToken:cognito:username",e["cognito:username"]);let n={Username:e["cognito:username"],Pool:this.userPool};this.log("loginWithToken:cognitoUserParams",n),W=new Ve(n),W.setSignInUserSession(this.session),this.log("loginWithToken:cognitoUserRestored",{cognitoUserType:typeof W,cognitoUserKeys:Object.keys(W||{}),cognitoUser:W});}}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 ne(){return await this.__connection,this.__user?.service===this.service?this.__user?.owner===this.host:(await Jt.bind(this)(),false)}async function je(t=false){let e=null;W&&(t?e=new Promise((n,i)=>{W.globalSignOut({onSuccess:s=>{this.log("globalSignOut:success",s),n(s);},onFailure:s=>{this.log("globalSignOut:error",s),i(s);}});}):W.signOut()),li.bind(this)();let r={session:null,__startKeyHistory:{},__cached_requests:{},__user:null};e&&(e=await e);for(let n in r)this[n]=r[n];return this._runOnUserUpdateListeners(null),this._runOnLoginListeners(null),e}async function Jt(t){await this.__connection;let{data:e}=$(t);return await je.bind(this)(e?.global),"SUCCESS: The user has been logged out."}async function ba(){if(!this.__request_signup_confirmation)throw new f("Least one login attempt is required.",{code:"INVALID_REQUEST"});return await P.bind(this)("confirm-signup",{username:this.__request_signup_confirmation})}async function _a(t=false){if(typeof t=="string")t=_.Url(t);else if(typeof t!="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 P.bind(this)("recover-account",{username:this.__disabledAccount,redirect:t}),"SUCCESS: Recovery e-mail has been sent."}async function Si(t){let e=_.Params(t,{username:"string",email:"string",password:"string"},["password"]);await this.__authConnection;let r=null;if(e.email)try{r=_.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"});let n=e.username||e.email;try{return await re.bind(this)().authenticateUser(n,e.password)}catch(i){if((i?.code==="UserNotFoundException"||i?.code==="NotAuthorizedException")&&r&&r!==n)return await re.bind(this)().authenticateUser(r,e.password);throw i}}async function wa(t,e){await this.__authConnection;let r={username:"string",password:l=>_.Password(l),email:l=>_.Email(l),name:"string",address:l=>{if(!l)return "";if(typeof l=="string")return l;if(typeof l=="object")return JSON.stringify(l)},gender:"string",birthdate:l=>l?_.Birthdate(l):"",phone_number:l=>l?_.PhoneNumber(l):"",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:l=>l?_.Url(l):"",profile:l=>l?_.Url(l):"",family_name:"string",given_name:"string",middle_name:"string",nickname:"string",website:l=>l?_.Url(l):""},n=_.Params(t||{},r,["email","password"]);await Jt.bind(this)(),e=_.Params(e||{},{email_subscription:l=>{let d=l;if(typeof l=="number"||typeof l=="string"&&l!=="public"&&l!=="authorized"){let h=_.newsletterGroup(l);if(typeof h=="number"&&h!==0&&h!==1)throw new f('"option.email_subscription" takes 0 (public), 1 (authorized), true, false or the name of a newsletter group.',{code:"INVALID_PARAMETER"});d=h;}else if(typeof l!="boolean"&&typeof l!="string")throw new f('"option.email_subscription" takes 0 (public), 1 (authorized), true, false or the name of a newsletter group.',{code:"INVALID_PARAMETER"});if(d!==false&&!e?.signup_confirmation)throw new f('"option.signup_confirmation" is required for email subscription.',{code:"INVALID_PARAMETER"});return d},signup_confirmation:l=>{let d=l;if(typeof l=="string")d=_.Url(l);else if(typeof l=="boolean")d=l;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:l=>{if(typeof l=="boolean"){if(e.signup_confirmation&&l)throw new f('"login" is not allowed when "option.signup_confirmation" is true.',{code:"INVALID_PARAMETER"});return l}throw new f('"option.login" should be type: boolean.',{code:"INVALID_PARAMETER"})},template:l=>{if(typeof l!="object"||l===null)throw new f('"option.template" should be type: <object>.',{code:"INVALID_PARAMETER"});if(l.signup_confirmation!==void 0){if(typeof l.signup_confirmation!="string"||!l.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(l.welcome!==void 0&&(typeof l.welcome!="string"||!l.welcome))throw new f('"option.template.welcome" should be a non-empty <string> (template message_id).',{code:"INVALID_PARAMETER"});return l}});let i=e?.login||false;if(n.signup_confirmation=e?.signup_confirmation||false,n.email_subscription=e?.email_subscription===void 0||e?.email_subscription===null?false:e.email_subscription,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=re.bind(this)().createCognitoUser(n.username||n.email);for(let l of ["email_public","address_public","gender_public","birthdate_public","phone_number_public"])n[l]=n[l]?"1":"0";n.access_group&&(n.access_group=n.access_group.toString());let o=(await P.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(":"),c=[new Ne({Name:"custom:signup",Value:o[0]}),new Ne({Name:"locale",Value:a.split("#")[1]}),new Ne({Name:"custom:signup_ticket",Value:a})];for(let l in r){let d=["email_public","address_public","gender_public","birthdate_public","phone_number_public","misc","service","owner"];n[l]!==""&&(l==="username"||l==="password"||l==="access_group"||(d.includes(l)?c.push(new Ne({Name:"custom:"+l,Value:n[l]})):c.push(new Ne({Name:l,Value:n[l]}))));}return await re.bind(this)().signup(s.cognitoUsername,n.password,c),n.signup_confirmation?(W=s.cognitoUser,this.__request_signup_confirmation=s.cognitoUsername,"SUCCESS: The account has been created. User's signup confirmation is required."):i?Si.bind(this)({email:n.username||n.email,password:n.password}):"SUCCESS: The account has been created."}async function Ea(){await this.__connection;let t=await P.bind(this)("remove-account",{disable:this.__user.user_id},{auth:true});return await Jt.bind(this)(),t}async function Aa(t){await this.__connection;let e=_.Params(t,{email:i=>_.Email(i),code:["number","string"],new_password:i=>_.Password(i)},["email","code","new_password"]),r=e.code,n=e.new_password;return typeof r=="number"&&(r=r.toString()),new Promise(async(i,s)=>{re.bind(this)().createCognitoUser(e.email).cognitoUser.confirmPassword(r,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 Ra(t,e,r){await this.__connection;let n;if(!W)throw new f("The user has to be logged in.",{code:"INVALID_REQUEST"});if(t==="email"||t==="phone_number"){if(!this.__user.hasOwnProperty(t))throw new f(`No ${t==="email"?"e-mail":"phone number"} to verify`,{code:"INVALID_REQUEST"});if(this.__user?.[`${t}_verified`])return `SUCCESS: "${t}" is verified.`;n=(e?_.Params(e,{code:"string"}):{}).code||"";}else return;let i,s=r?.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 c={onSuccess:l=>{n?re.bind(this)().getSession({refreshToken:true}).then(()=>{this.__user&&(this.__user[t+"_verified"]=true),o(`SUCCESS: "${t}" is verified.`);}).catch(d=>{a(d);}):o("SUCCESS: Verification code has been sent.");},onFailure:l=>{a(new f(l.message||"Failed to request verification code.",{code:l?.code}));}};n?W?.verifyAttribute(t,n,c):(c.inputVerificationCode=null,W?.getAttributeVerificationCode(t,c,i));})}function Ta(t,e){return Ra.bind(this)("phone_number",t,e)}function Sa(t,e){return Ra.bind(this)("email",t,e)}async function va(t,e){await this.__connection;let r=_.Params(t,{email:i=>_.Email(i)},["email"]),n;if(e?.template!==void 0){if(typeof e.template!="object"||e.template===null||Array.isArray(e.template))throw new f('"template" should be type: <object>.',{code:"INVALID_PARAMETER"});if(e.template.verification!==void 0)throw new f('"template.verification" is not an option of forgotPassword(). Use "template.forgot_password" (template message_id).',{code:"INVALID_PARAMETER"});let i=e.template.forgot_password;if(i!==void 0){if(typeof i!="string"||!i)throw new f('"template.forgot_password" should be a non-empty <string> (template message_id).',{code:"INVALID_PARAMETER"});n={template_forgot_password:i};}}return new Promise(async(i,s)=>{re.bind(this)().createCognitoUser(r.email).cognitoUser.forgotPassword({onSuccess:a=>{i("SUCCESS: Verification code has been sent.");},onFailure:a=>{let{parsed:c,code:l}=Kr(a),d={UserNotFoundException:"NOT_EXISTS",InvalidParameterException:"INVALID_PARAMETER",NotAuthorizedException:"INVALID_REQUEST",LimitExceededException:"REQUEST_EXCEED",TooManyRequestsException:"REQUEST_EXCEED",CodeDeliveryFailureException:"CODE_DELIVERY_FAILURE"}[l]||c.code||l||"ERROR";s(new f(c.message,{code:d,cause:a}));}},n);})}async function Ia(t){if(await this.__connection,!this.session)throw new f("User login is required.",{code:"INVALID_REQUEST"});let e=_.Params(t,{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 _.Password(e.current_password),_.Password(e.new_password),V.call(this)&&await Go.bind(this)(e.current_password,e.new_password),new Promise((r,n)=>{W.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}=Kr(i);n(o);}return}V.call(this)&&Wo.bind(this)().catch(o=>this.log("encryption:prune:failed",o)),r("SUCCESS: Password has been changed.");});})}async function Pa(t){if(await this.__connection,!this.session)throw new f("User login is required.",{code:"INVALID_REQUEST"});let e=_.Params(t||{},{user_id:i=>_.UserId(i),email:i=>_.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?_.Birthdate(i):"",phone_number:i=>i?_.PhoneNumber(i):"",email_public:"boolean",phone_number_public:"boolean",address_public:"boolean",gender_public:"boolean",birthdate_public:"boolean",misc:"string",picture:i=>i?_.Url(i):"",profile:i=>i?_.Url(i):"",family_name:"string",given_name:"string",middle_name:"string",nickname:"string",website:i=>i?_.Url(i):""});if(e&&typeof e=="object"&&!Object.keys(e).length)return this.user;let r=[["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 r)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 P.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 Ne({Name:s,Value:e[s]}));return await new Promise((s,o)=>{W?.updateAttributes(i,(a,c)=>{a&&o([a?.code||a?.name,a?.message||"Failed to update user settings."]),s(c);});}),await re.bind(this)().getSession({refreshToken:true}),this.user}return this.user}async function ka(t,e){t=$(t).data,t||(t={searchFor:"timestamp",condition:">",value:0},e||(e={}),e.ascending=false),await this.__connection;let r={user_id:s=>_.UserId(s),email:"string",phone_number:"string",locale:s=>{if(typeof s!="string"||typeof s=="string"&&s.length>5)throw new f('Value of "locale" should be a country code.',{code:"INVALID_PARAMETER"});return s},name:"string",address:"string",gender:"string",birthdate:s=>_.Birthdate(s),subscribers:"number",timestamp:"number",access_group:"number",approved:"string"},n=["searchFor","value"],i=(s,o)=>{let a=r[t.searchFor];if(typeof a=="function")return a(s);if(typeof s!==a)throw new f(`${o} does not match the type of "${t.searchFor}" index.`,{code:"INVALID_PARAMETER"});return s};if(t=_.Params(t,{searchFor:["user_id","name","email","phone_number","address","gender","birthdate","locale","subscribers","timestamp","access_group","approved"],condition:[">",">=","=","<","<=","gt","gte","eq","lt","lte",()=>"="],value:s=>Array.isArray(s)?s.map(o=>i(o,"Value")):i(s,"Value"),range:s=>i(s,"Range")},n),t?.condition&&t?.condition!=="="&&t.hasOwnProperty("range"))throw new f("Conditions does not apply on range search.",{code:"INVALID_PARAMETER"});if(Array.isArray(t.value)&&(t.condition!=="="||t.range))throw new f(`Conditions are not allowed on a list of "${t.searchFor}" values. Search for a single value to use a condition or range.`,{code:"INVALID_PARAMETER"});if(typeof t?.value=="string"&&!t?.value)throw new f("Value should not be an empty string.",{code:"INVALID_PARAMETER"});if(typeof t?.searchFor=="string"&&!t?.searchFor)throw new f('"searchFor" should not be an empty string.',{code:"INVALID_PARAMETER"});return P.bind(this)("get-users",t,{auth:true,fetchOptions:e})}async function Ca(t){await this.__connection;let e=await P.bind(this)("last-verified-email",t,{auth:true});return e.includes("SUCCESS")?(await re.bind(this)().getSession({refreshToken:true}),this.user):e}var Ch="1.2.1",xh=class{constructor(t){xe(this,"version",Ch);xe(this,"items",[]);xe(this,"nextJobId",1);xe(this,"breakWhenError",false);xe(this,"batchSize",1);xe(this,"onProgress");xe(this,"activeCount",0);xe(this,"currentCycleCompleted",[]);xe(this,"stopProcessing",false);if(this.breakWhenError=!!t?.breakWhenError,this.batchSize=t?.batchSize??1,typeof this.batchSize!="number"||this.batchSize<1)throw new Error("batchSize must be at least 1");if(t?.onProgress)if(typeof t.onProgress=="function")this.onProgress=t.onProgress;else throw new Error("onProgress must be a function")}get batchToProcess(){return Math.ceil(this.items.length/this.batchSize)}add(t){let e=Array.isArray(t)?t:[t],r=[];for(let n of e){if(typeof n!="function")throw new Error("Each job must be a function that returns a Promise");let i=String(this.nextJobId++);this.items.push({id:i,job:n}),r.push(i);}return this.processNext(),r}setBatchSize(t){if(typeof t!="number"||t<1)throw new Error("batchSize must be at least 1");this.batchSize=t;}remove(t){let e=String(t),r=this.items.findIndex(n=>n.id===e);return r===-1?false:(this.items.splice(r,1),true)}processNext(){if(this.stopProcessing||this.items.length===0||this.activeCount>0)return;let t=this.items.splice(0,this.batchSize);this.activeCount=t.length,this.currentCycleCompleted=new Array(t.length),t.forEach((e,r)=>{Promise.resolve().then(()=>e.job()).then(n=>(this.finalizeJob(r,n,false),n)).catch(n=>(this.finalizeJob(r,n,true),n));});}finalizeJob(t,e,r){if(this.currentCycleCompleted[t]=e,this.activeCount-=1,r&&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=[];}},Yt=xh;var Rt=null,Da=typeof SubmitEvent<"u",Uh=typeof HTMLFormElement<"u",Xt=X(),vi=0;function Na(t){if(!t)return null;let e=Number(t);if(Number.isFinite(e))return Math.max(0,e*1e3);let r=Date.parse(t);return Number.isNaN(r)?null:Math.max(0,r-Date.now())}var Pi=6,xa=6e4;function Oa(t,e){let r=t>0?t:Math.min(xa,500*Math.pow(2,e));r=Math.min(xa,r);let n=Math.floor(Math.random()*Math.min(1e3,Math.max(50,r*.25)));return r+n}function Fa(t){return new f(`Too many requests: ${t} still answered 429 after ${Pi} retries.`,{code:"TOO_MANY_REQUESTS"})}function Ii(t,e){return e>0?t/e*100:0}var Ua=t=>{let{auth:e,type:r,endpoints:n,stable:i}=t,s=n[0],o=n[1];if(vi++,r==="admin"){let a=Object.entries(s).filter(([c,l])=>c.includes(e?"_private":"_public")&&c!=="get_users_private"&&c!=="service_public"&&typeof l=="string").map(([,c])=>c);if(!a.length)throw new f("No available admin gateways.",{code:"INVALID_REQUEST"});return a[vi%a.length]}if(r==="record"){let a=Object.entries(o).filter(([c,l])=>c.includes(e?"record_private":"record_public")&&typeof l=="string").map(([,c])=>c);if(!a.length)throw new f("No available record gateways.",{code:"INVALID_REQUEST"});return i?a[0]:a[vi%a.length]}throw new f("Invalid gateway type.",{code:"INVALID_REQUEST"})};async function Dh(t,e,r){let n=await Promise.all([this.admin_endpoint,this.record_endpoint]),i=n[0],s=n[1],o=t.split("?"),a=o.length>1?"?"+o[1]:"";switch(t=o[0],t){case "get-users":return i.get_users_private+t+a;case "service":return i.service_public+t+a;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 "send-inquiry":case "register-newsletter-group":case "delete-newsletter-group":case "newsletter-group-endpoint":case "invitation-list":case "csr":case "csr-poll":case "csr-cancel":case "csr-finalize":return Ua.bind(this)({auth:e,type:"admin",endpoints:n})+t+a;case "post-record":return (e?s.post_private:s.post_public)+t+a;case "get-records":return (e?s.get_private:s.get_public)+t+a;case "del-files":case "del-records":return s.del_private+t+a;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 "get-signed-urls":case "extract-file-text":case "grid-query":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 Ua.bind(this)({auth:e,type:"record",endpoints:n,stable:r})+t+a;default:return _.Url(t)+a}}var Qt={};function La(){Rt&&(Rt.terminate(),Rt=null);}async function P(t,e=null,r,n){this.log("request",{url:t,data:e,options:r,_etc:n||{}}),r=r||{};let{auth:i=false,method:s="post",bypassAwaitConnection:o=false}=r;s=s.toUpperCase();let a=null,c=null,l=await Dh.bind(this)(t,!!i,!!r.stableGateway),d=e?.service||this.service,h=e?.owner||this.owner;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 u=r?.tokenHeaders?.idToken===true;(i||u)&&(c=await At.bind(this)());let p={},{fetchMore:g=false,progress:m}=r?.fetchOptions||{};if(r?.fetchOptions&&Object.keys(r.fetchOptions).length){for(let I of ["limit","startKey","ascending"])if(r.fetchOptions.hasOwnProperty(I)){if(I==="startKey"&&r.fetchOptions[I]===null)continue;p[I]=r.fetchOptions[I];}p=_.Params(p,{limit:I=>{if(typeof I!="number")throw new f("Fetch limit should be a number.",{code:"INVALID_REQUEST"});if(I>1e3)throw new f("Fetch limit should be below 1000.",{code:"INVALID_REQUEST"});return I},startKey:I=>I,ascending:"boolean"});}let b=n?.ignoreService?{}:{service:d,owner:h};Object.assign(b,p),e=$(e).data,e?e&&typeof e=="object"&&(e=Object.assign(b,e)):e=b;let y=`${s}:${i?"auth":"public"}:${t}`,E=(()=>{if(e&&typeof e=="object"&&Object.keys(e).length&&!(Xt&&e instanceof FormData)){let I=function(D){return typeof D=="object"&&D!==null?Object.keys(D).sort().reduce((N,M)=>(typeof D[M]=="object"&&D[M]!==null?N[M]=I(D[M]):N[M]=D[M],N),{}):D};return he.hash(y+"/"+JSON.stringify(I(e)))}return he.hash(y+"/"+d)})(),{requestKey:w,requestKeyWithStartKey:T}=Nh.bind(this)({params:e,url:t,fetchMore:g,hashedParams:E});if(!w||w&&typeof w=="object")return w;if(this.log("requestKey",T),typeof T=="string"&&Qt[T]instanceof Promise)return this.log("request:returning pending",T),Qt[T];let R={Accept:"*/*"};if(Object.prototype.hasOwnProperty.call(r,"contentType")&&r.contentType!==void 0){let I=r.contentType===null?"application/x-www-form-urlencoded":r.contentType;I&&(R["Content-Type"]=I);}else R["Content-Type"]="application/json";if(c&&(R.Authorization=c),r?.tokenHeaders){let I=(M,ie)=>typeof M=="string"?M:M===true?ie:null,D=I(r.tokenHeaders.accessToken,this.session?.accessToken?.jwtToken||null),N=I(r.tokenHeaders.idToken,this.bearerToken||this.session?.idToken?.jwtToken||c||null);D&&(R["X-Access-Token"]=D),N&&(R["X-Id-Token"]=N);}let O={public_identifier:this.__public_identifier,service:d,owner:h,resolves_offloaded_data:true};R["Content-Meta"]=JSON.stringify(O),r.revalidate&&(R["Cache-Control"]="no-cache",R.Pragma="no-cache");let U={headers:R};if(r?.responseType&&(U.responseType=r.responseType),s==="GET"){if(e){let I=[];if(Xt&&e instanceof FormData?I=Array.from(e.entries()).map(([D,N])=>{let M=typeof N=="string"?N:N.name;return encodeURIComponent(D)+"="+encodeURIComponent(M)}):I=Object.keys(e).map(D=>{let N=e[D];return typeof N!="string"&&(N=JSON.stringify(N)),encodeURIComponent(D)+"="+encodeURIComponent(N)}),I.length){let D=l.includes("?")?l.endsWith("?")||l.endsWith("&")?"":"&":"?";l+=D+I.join("&");}}U.body=null;}else if(Xt&&e instanceof FormData)U.body=e;else if(R["Content-Type"]==="application/x-www-form-urlencoded"&&e&&typeof e=="object"){let I=new URLSearchParams;for(let D of Object.keys(e)){let N=e[D];I.append(D,typeof N=="string"?N:JSON.stringify(N));}U.body=I.toString();}else typeof e=="string"?U.body=e:U.body=e?JSON.stringify(e):null;if(U.method=s,Rt===null){let I={batchSize:this.requestBatchSize,breakWhenError:false,onProgress:D=>{this.onBatchProcess.forEach(N=>N(D));}};Rt=new Yt(I);}return this.log("request-opt",U),new Promise((I,D)=>{Rt.add([async()=>{let N=Ma.bind(this)(l,U,m);Qt[T]=N;try{let M=Fh.bind(this)({hashedParam:w,requestKeyWithStartKey:T,url:t,fetched:await N});return delete Qt[T],this.log("request:end",M),I(M),M}catch(M){throw delete Qt[T],this.log("request:err",M),D(M),M}}]);})}function Nh(t){let{params:e={},url:r,fetchMore:n=false,hashedParams:i}=t||{};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?.[r]?.[i]&&delete this.__cached_requests[r][i],this.__startKeyHistory?.[r]?.[i]){if(Array.isArray(this.__startKeyHistory[r][i])&&this.__startKeyHistory[r][i].length)for(let c of this.__startKeyHistory[r][i]){let l=i+he.hash(c);this.__cached_requests?.[r]&&this.__cached_requests?.[r]?.[l]&&delete this.__cached_requests[r][l];}delete this.__startKeyHistory[r][i];}return {requestKeyWithStartKey:i,requestKey:i}}if(!Array.isArray(this.__startKeyHistory?.[r]?.[i]))return {requestKeyWithStartKey:i,requestKey:i};let s=this.__startKeyHistory[r][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+=he.hash(o),e.startKey=JSON.parse(o);}return this.__cached_requests?.[r]?.[a]?{requestKey:this.__cached_requests[r][a],requestKeyWithStartKey:a}:{requestKeyWithStartKey:a,requestKey:i}}function Oh(t){let e=r=>r&&typeof r=="object"&&r.encrypted?Object.assign({},r,{data:null}):r;return Array.isArray(t)?t.map(e):t&&typeof t=="object"?Array.isArray(t.list)?Object.assign({},t,{list:t.list.map(e)}):e(t):t}function Ma(t,e,r,n=0){return new Promise((i,s)=>{let o=new XMLHttpRequest;o.open(e.method||"GET",t);for(var a in e.headers||{})o.setRequestHeader(a,e.headers[a]);e.responseType&&(o.responseType=e.responseType),o.onload=()=>{if(o.status<400)if(e.responseType=="json"||e.responseType=="blob")i(o.response);else {let c=o.responseText;try{c=JSON.parse(c);}catch{}i(c);}else if(o.status===429){let c=o.getResponseHeader("Retry-After"),l=Na(c);if(l!==null){if(n>=Pi){s(Fa(`"${t.split("?")[0]}"`));return}setTimeout(()=>{Ma(t,e,r,n+1).then(i,s);},Oa(l,n));}else s("Too many requests");}else {let c=o.status,l=["INVALID_CORS","INVALID_REQUEST","SERVICE_DISABLED","INVALID_PARAMETER","ERROR","EXISTS","NOT_EXISTS"],d=e.responseType=="blob"?o.response:o.responseText;try{d=JSON.parse(d);}catch{}if(typeof d=="string"){let h=d.split(":"),u=h.splice(0,1)[0].trim(),p=h.join(":").trim();s(new f(p||d,{code:l.includes(u)?u:"ERROR"}));}else if(typeof d=="object"&&(d?.message||d?.stage||d?.code)){let h=d?.code||(c?c.toString():null)||"ERROR",u=d.message,p=d?.cause;p===void 0&&d.stage&&(p=d),typeof u=="string"&&(u=u.trim()),u||(u=String(h)),s(new f(u,{cause:p,code:h}));}else s(d);}},o.onerror=()=>s("Network error"),o.onabort=()=>s("Aborted"),o.ontimeout=()=>s("Timeout"),typeof r=="function"&&(o.onprogress=c=>{r({status:"download",progress:Ii(c.loaded,c.total),loaded:c.loaded,total:c.total,abort:()=>o.abort()});},o.upload&&(o.upload.onprogress=c=>{r({status:"upload",progress:Ii(c.loaded,c.total),loaded:c.loaded,total:c.total,abort:()=>o.abort()});})),o.send(e.body);})}function Fh(t){let{hashedParam:e,requestKeyWithStartKey:r,url:n,fetched:i}=t;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][r]=i,Object.assign({startKeyHistory:this.__startKeyHistory[n][e]},i)}function Lh(t){if(t instanceof f)return t;if(typeof t=="string"){let e=t.trim();if(e==="Network error")return new f("Network error",{code:"NETWORK_ERROR"});if(e==="Aborted")return new f("Aborted",{code:"ABORTED"});if(e==="Timeout")return new f("Timeout",{code:"TIMEOUT"});if(e==="Too many requests")return new f("Too many requests",{code:"TOO_MANY_REQUESTS"});let r=/<Code>([^<]+)<\/Code>/.exec(e)?.[1]?.trim()||"",n=/<Message>([^<]+)<\/Message>/.exec(e)?.[1]?.trim()||"";return r||n?new f(n||r,{code:r||"UPLOAD_FAILED",cause:e}):new f(e.length>300?e.slice(0,300):e||"Upload failed.",{code:"UPLOAD_FAILED",cause:e})}if(t&&typeof t=="object"){let e=t.code||t.Code,r=t.message||t.Message;if(e||r)return new f(String(r||e),{code:String(e||"UPLOAD_FAILED"),cause:t})}return new f("Upload failed.",{code:"UPLOAD_FAILED",cause:t})}var Mh=5,qh=100;function Vh(t){let e=String(t?.code??"");if(e==="404"||e==="501")return true;let r=String(t?.message??t??"");return /missing authentication token/i.test(r)||/not implemented/i.test(r)||e==="403"&&/not found/i.test(r)}function Bh(t,e){let r=Array.isArray(t?.list)?t.list:[],n=Array.isArray(t?.failed)?t.failed:[],i=new Array(e);for(let s of n)s&&Number.isInteger(s.index)&&s.index>=0&&s.index<e&&(i[s.index]=new f(String(s.message||"Upload permit refused."),{code:String(s.code||"ERROR")}));for(let s=0;s<e;s++){if(i[s])continue;let o=r[s];o&&typeof o.url=="string"?i[s]={fields:o.fields||null,url:o.url,cdn:o.cdn}:i[s]=new f("No upload permit was answered for this file.",{code:"ERROR"});}return i}async function Zt(t,e){await this.__connection;let{record_id:r,service:n=this.service,progress:i,timeout:s,throwOnFileError:o=false}=e;if(!r)throw new f('"record_id" is required.',{code:"INVALID_PARAMETER"});if(s!=null){if(typeof s!="number"||!Number.isFinite(s)||s<0)throw new f('"timeout" should be a number of milliseconds, 0 or more.',{code:"INVALID_PARAMETER"})}else s=0;if(Da&&t instanceof SubmitEvent&&(t=t.target),Uh&&t instanceof HTMLFormElement&&(t=new FormData(t)),!Xt||!(t instanceof FormData))throw new f('"fileList" should be a FormData or HTMLFormElement.',{code:"INVALID_PARAMETER"});let c={reserved_key:et(),service:n,request:"post"};e?.record_id&&(c.id=e.record_id);let l,d=(w,T,R,x,O=0)=>new Promise((U,I)=>{l=new XMLHttpRequest,l.open("POST",w),s>0&&(l.timeout=s),l.onload=()=>{let D=l.responseText;try{D=JSON.parse(D);}catch{}if(l.status>=200&&l.status<300)U(D);else if(l.status===429){let N=l.getResponseHeader("Retry-After"),M=Na(N);if(M!==null){if(O>=Pi){I(Fa(`the upload of "${x}" to "${w}"`));return}setTimeout(()=>{d(w,T,R,x,O+1).then(U,I);},Oa(M,O));}else I("Too many requests");}else I(D);},l.onerror=()=>I("Network error"),l.onabort=()=>I("Aborted"),l.ontimeout=()=>I(new f(`Upload timeout: "${x}" was not finished within ${s} ms.`,{code:"TIMEOUT"})),l.upload&&typeof R=="function"&&(l.upload.onprogress=R),l.send(T);});function h(w){let T="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";if(w===0)return T[0];let R="";for(;w>0;)R=T[w%62]+R,w=Math.floor(w/62);return R}let u=[],p=[],g=[],m=[],b=[];for(let[w,T]of t.entries())T instanceof File&&b.push([w,T]);let y=b.length>=Mh&&!this.__bulkPermitsUnavailable,E=0;for(;E<b.length;){let w=b.slice(E,E+(y?qh:1));E+=w.length;let T=[];for(let[x,O]of w){let U=await sa.bind(this)(r,x,O);T.push({file:O,uploadFile:U.file,params:{key:U.key+"/"+U.file.name,sizeKey:h(U.file.size),contentType:U.file.type||null}});}let R=null;if(y)try{let x=await P.bind(this)("get-signed-urls",Object.assign({files:T.map(O=>O.params)},c),{auth:!!this.__user});R=Bh(x,T.length);}catch(x){if(!Vh(x))throw x;this.__bulkPermitsUnavailable=true,y=false;}if(!R){R=[];for(let x of T){let{fields:O=null,url:U,cdn:I}=await P.bind(this)("get-signed-url",Object.assign(x.params,c),{auth:!!this.__user});R.push({fields:O,url:U,cdn:I});}}for(let x=0;x<T.length;x++){let{file:O,uploadFile:U}=T[x],I=R[x];if(I instanceof f){if(m.push(""),p.push(O),g.push({file:O,name:O.name,error:I}),o)throw I;continue}m.push(I.cdn);let D=new FormData;for(let N in I.fields||{})D.append(N,I.fields[N]);D.append("file",U);try{await d(I.url,D,typeof i=="function"?N=>i({status:"upload",progress:Ii(N.loaded,N.total),currentFile:O,completed:u,failed:p,loaded:N.loaded,total:N.total,abort:()=>l.abort()}):null,O.name),u.push(O);}catch(N){p.push(O);let M=Lh(N);if(g.push({file:O,name:O.name,error:M}),o)throw M}}}return {completed:u,failed:p,errors:g,bin_endpoints:m}}var $r={};function C(t){let{preventMultipleCalls:e=false}=t||{};return function(r,n,i){let s=i.value;i.value=function(...o){let a=o[0],c=true,l=null,d="",h={},u=false;if(Da&&a instanceof SubmitEvent){a.preventDefault();let y=window.location.href;l=a.target;let E=new URL(l.action);d=E.href;let w=d?d.match(/(?<=\{).*?(?=\})/g):"";if(w)for(let T of w){if(!T)continue;let R=l.querySelector(`[name="${T}"]`);if(R)if(R.type==="file")for(let x=0;x<=R.files.length-1;x++)R.files[x]&&(h[T]||(h[T]=[]),h[T].push(new Promise((O,U)=>{let I=new FileReader;I.onload=function(){O(I.result);},I.readAsDataURL(R.files[x]),I.onerror=U;})));else d=d.replace(`{${T}}`,R.value);}l.getAttribute("action")===null?c=false:u=E.href===y;}let p=async y=>{if(d)for(let E in h)h[E].length&&(d=d.replace(`{${E}}`,(await Promise.all(h[E])).join(",")));if(l&&c){let E=V.call(this)?Oh(y):y;window.sessionStorage.setItem(`${this.service}:${he.hash(d)}`,JSON.stringify(E)),u?window.location.replace(d):window.location.href=d;}return y},g,m=y=>{throw y instanceof f?y.name=n+"()":y=y instanceof Error?y:new f(y,{name:n+"()"}),y},b=async()=>{try{if(this.__projectIdInput&&await this.__projectIdInput,g=s.bind(this)(...o),g instanceof Promise){let y=await g;return p(y)}return p(g)}catch(y){throw m(y)}};if(e){let y=`${n}:${this?.__public_identifier||""}:${this?.service||""}:${this?.owner||""}`;return $r?.[y]||($r[y]=b().finally(()=>{delete $r[y];})),$r[y]}return b()};}}async function qa(){await this.__connection;let t=`${this.service}:${he.hash(window.location.href.split("?")[0])}`,e=window.sessionStorage.getItem(t);if(window.sessionStorage.removeItem(t),e!==null){try{e=JSON.parse(e);}catch{}return e}return null}var jh=256,Kh=256,$h=256,Va=256,Hh="\u{10FFFF}",Gh=/[\u0000-\u001F\u007F]|\u{10FFFF}/u,Wh={"/":"%2F","!":"%21","*":"%2A","#":"%23"},zh={"%2F":"/","%21":"!","%2A":"*","%23":"#"};function Jh(t){return t.replace(/%/g,"%25").replace(/[\/!*#]/g,r=>Wh[r]||r)}function Pe(t){return typeof t!="string"?t:t.replace(/%(2F|21|2A|23)/gi,r=>{let n=r.toUpperCase();return zh[n]||r}).replace(/%25/gi,"%")}function Oe(t,e,r={}){let{allowEmpty:n=false,maxLength:i,blockKeyDelimiters:s=false,disallowLeadingDollar:o=false,onlyAlphanumeric:a=false}=r;if(typeof t!="string")throw new f(`"${e}" should be type: <string>.`,{code:"INVALID_PARAMETER"});if(a&&/[^a-zA-Z0-9]/.test(t))throw new f(`"${e}" should only contain alphanumeric characters.`,{code:"INVALID_PARAMETER"});if(!n&&t.length===0)throw new f(`"${e}" is required.`,{code:"INVALID_PARAMETER"});if(i&&t.length>i)throw new f(`"${e}" should be <= ${i} characters.`,{code:"INVALID_PARAMETER"});if(Gh.test(t)||t.includes(Hh))throw new f(`"${e}" cannot include control characters or unsupported sentinel characters.`,{code:"INVALID_PARAMETER"});if(s&&(t=Jh(t),i&&t.length>i))throw new f(`"${e}" should be <= ${i} characters. "/", "!", "*", "#" and "%" count as 3 characters each.`,{code:"INVALID_PARAMETER"});if(o&&t.startsWith("$"))throw new f(`"${e}" cannot start with "$".`,{code:"INVALID_PARAMETER"});return t}function Tt(t,e="table.name",r={}){return Oe(t,e,{allowEmpty:r.allowEmpty===true,maxLength:jh,blockKeyDelimiters:true})}function Gr(t,e="tag",r={}){return Oe(t,e,{allowEmpty:r.allowEmpty===true,maxLength:Kh,blockKeyDelimiters:true})}function er(t,e="index.name",r={}){return Oe(t,e,{allowEmpty:r.allowEmpty===true,maxLength:$h,blockKeyDelimiters:true,disallowLeadingDollar:true})}function Ba(t,e="index.value"){return Oe(t,e,{allowEmpty:true,maxLength:Va})}function ki(t){return typeof t=="string"&&t.slice(-1)==="."}function Ci(t,e){return Oe(t,e,{allowEmpty:true,maxLength:Va,blockKeyDelimiters:true})}function ja(t){if(!t.record_id&&!t.unique_id)return null;let e={};return t?.service&&(e.service=t.service),t?.owner&&(e.owner=t.owner),t?.record_id?e.record_id=Oe(t.record_id,"record_id",{allowEmpty:false,onlyAlphanumeric:true}):t?.unique_id&&(e.unique_id=t.unique_id),e}function xi(t){if(t===void 0)return 0;if(typeof t=="number"){if(t>99||t<0)throw new f('"table.access_group" value should be within a range of 0 ~ 99.',{code:"INVALID_REQUEST"})}else if(typeof t=="string"){if(t={"*":"private",private:"private",public:0,authorized:1,admin:99}[t],t===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&&t)throw new f("Unsigned users have no access to records with access group.",{code:"INVALID_REQUEST"});return t}var Hr=4503599627370496;function Wr(t){if(typeof t=="number"){if(t>Hr||t<-Hr)throw new f(`Number value should be within range -${Hr} ~ +${Hr}`,{code:"INVALID_PARAMETER"});return t}if(typeof t=="boolean")return t;if(typeof t=="string")return Ba(t,"index.value");throw new f('"index.value" should be type: <number | boolean | string>.',{code:"INVALID_PARAMETER"})}function Ka(t,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 t)throw new f('"index.range" type should match the type of "index.value".',{code:"INVALID_PARAMETER"});return typeof t=="string"?ki(e.index.name)?Ci(t,"index.range"):Ba(t,"index.range"):t}var zr={},Yh=10080*60,Qh=3600,$a=2;function Xh(t,e){if(!e)return String($a);let r=Math.max(60,t-300)*1e3;return "g"+$a+"w"+Math.floor(Date.now()/r)}function Zh(t){if(!this.user?.user_id)return false;let e=t[6]==="**"?"**":parseInt(t[6]),r=this.user?.access_group??-1;return !(this.user.user_id!==t[3]&&(e==="**"||r<e))}function ep(t){if(typeof t=="string"){if(t.startsWith("!J%"))try{return JSON.parse(t.substring(3))}catch{return t}return t==="!D%{}"?{}:t==="!L%[]"?[]:t}if(t&&typeof t=="object"&&!Array.isArray(t)&&typeof t.__json__=="string"&&Object.keys(t).length===1)try{return JSON.parse(t.__json__)}catch{}return t}async function Jr(t){return typeof t=="string"?t:t&&typeof t.text=="function"?await t.text():await new Promise((e,r)=>{try{let n=new FileReader;n.onload=()=>e(n.result),n.onerror=()=>r(n.error||new Error("Failed to read blob")),n.readAsText(t);}catch(n){r(n);}})}function Di(t){return !!t&&typeof t=="object"&&!Array.isArray(t)&&typeof t.__data__=="string"&&Object.keys(t).length===1&&t.__data__.endsWith("/__data__/__json__.json")}var St=new Map,tp=1024,rp=/^[0-9A-Za-z]+\/[0-9A-Za-z]+\/__data__\/__json__\.json$/,Ga=/^[0-9A-Za-z_-]+$/,np=/^(\d{2}|\*\*)$/;function Wa(t){if(typeof t!="string")return null;let e=t.split("?")[0].split("/");if(e.length<15||e[0]!=="https:"||e[1]!==""||!e[2])return null;let r=e.slice(3);return r[0]!=="publ"&&r[0]!=="auth"||r[4]!=="records"||r[7]!=="bin"||!Ga.test(r[1])?null:{origin:e.slice(0,3).join("/"),service:r[1]}}function ip(t){let e=Wa(t);!e||St.get(e.service)===e.origin||(St.size>=tp&&!St.has(e.service)&&St.clear(),St.set(e.service,e.origin));}function Ha(t,e){if(typeof e!="string"||!rp.test(e))return null;let r=typeof t.usr_tbl=="string"?t.usr_tbl.split("/"):null,n=typeof t.tbl=="string"?t.tbl.split("/"):null,i=null,s=null;if(typeof t.srvc=="string"){let d=t.srvc.split("!")[0].split("/");d.length===2&&(i=d[0],s=d[1]);}i||(i=r?.[2]||n?.[1]||null,i&&i===this.service&&(s=this.owner));let o=typeof t.usr=="string"&&t.usr?t.usr:r?.[0]||null,a=r?.[3]||n?.[2]||null,c=t.rec;for(let d of [i,s,o,c])if(typeof d!="string"||!Ga.test(d))return null;if(typeof a!="string"||!np.test(a))return null;let l=null;if(Array.isArray(t.bin))for(let d of t.bin){let h=Wa(d);if(h&&h.service===i){l=h.origin;break}}return l=l||St.get(i)||null,l?`${l}/${a==="00"?"publ":"auth"}/${i}/${s}/${o}/records/${c}/${a}/bin/${e}`:null}async function nt(t,e,r=false,n=false,i=false){let s={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:{}},o=false,a=[],c=null;function l(u){let p=u=="**"?"private":parseInt(u);return p=p==0?"public":p==1?"authorized":p==99?"admin":p,p}let d={ip:u=>{let p=u.split("#"),g=p[0];p.length>1&&(s.unique_id=p.slice(1).join("#")),g.slice(-1)==="R"?(s.readonly=true,g=g.slice(0,-1)):s.readonly=false,/^\d{1,3}-\d{1,3}-\d{1,3}-\d{1,3}$/.test(g)&&(g=g.split("-").join("."),o=true),s.ip=g;},rec:u=>{if(!u)return;s.record_id=u;let p=u.substring(0,u.length-9),g=Se(p);s.uploaded=g;},usr:u=>{s.user_id=u;},tbl:u=>{if(u&&!s.table.name){let p=u.split("/");s.table.name=Pe(p[0]),s.table.access_group=l(p[2]),p?.[3]&&(s.table.subscription.is_subscription_record=true);}},usr_tbl:u=>{let p=u.split("/");s.user_id||(s.user_id=p[0]),s.table.name||(s.table.name=Pe(p[1]),s.table.access_group=l(p[3]),p?.[4]&&(s.table.subscription.is_subscription_record=true));},idx:u=>{if(!u)return;let p=u.split("!"),g=Pe(p.splice(0,1)[0]),m=sp("!"+p.join("!"));s.index={name:g,value:m};},ref:u=>{u&&(s.reference=u.split("/")[0]);},tags:u=>{s.tags=Array.isArray(u)?u.map(p=>Pe(p)):u;},upd:u=>{s.updated=u;},acpt_mrf:u=>{s.source.prevent_multiple_referencing=!u;},ref_limt:u=>{s.source.referencing_limit=u;},rfd:u=>{s.referenced_count=u;},bin:async u=>{let p={},g=s?.reference||null;if(Array.isArray(u)){let m=await Promise.all(u.map(async b=>{try{let y=b.split("/").slice(3).join("/"),E=y.split("/");if(E.length<12)return null;let w=E[E.length-1],T=E[10];if(T==="__data__"&&w==="__json__.json")return {isDataFile:!0,rawUrl:b};if(hi(T,w))return {isDataFile:!0,rawUrl:b};let R=jr(T),x=E[9],O=E[8],U=l(E[6]),I=b,D=U!=="public"&&Zh.call(this,E)?{expires:Qh,browserCache:Yh}:null;if(U!=="public"&&!i)try{I=await Ke.bind(this)(b,{dataType:"endpoint",_ref:g});}catch(M){console.error("Error getting signed url for private file:",M),I=b;}let N={access_group:U,filename:w,url:I,path:y,size:R?R.plainSize:Se(x),uploaded:Se(O),getFile:(M,ie)=>{let ae={dataType:M||"download",progress:ie,_ref:g},q=()=>Ke.bind(this)(I,Object.assign({},ae,{_update:N}));return D?Ke.bind(this)(b,Object.assign({},ae,D)).catch(()=>q()):q()}};return R&&(N.encrypted=!0,N.stored_size=Se(x)),{pathKey:R?R.key:T,obj:N}}catch{return null}}));for(let b of m)if(b&&!b.isDataFile){if(p[b.pathKey]){p[b.pathKey].push(b.obj);continue}p[b.pathKey]=[b.obj];}}s.bin=p;},prv_acs:u=>{for(let p in u)["notify_subscribers","upload_to_feed","feed_referencing_records","notify_referencing_records"].includes(p)?s.table.subscription[p]=u[p]:p==="referencing_index_restrictions"&&Array.isArray(u[p])?s.source[p]=u[p].map(m=>m&&typeof m=="object"&&typeof m.name=="string"?Object.assign({},m,{name:Pe(m.name)}):m):s.source[p]=u[p];},data:async u=>{let p={access_group:s.table.access_group,table_name:s.table.name,user_id:s.user_id,record_id:s.record_id,unique_id:s.unique_id,ctUrl:c},g=()=>{V.call(this)&&(s.encrypted={status:"failed",reason:"DATA_UNAVAILABLE"});},m=async y=>{if(n||!V.call(this)&&!qr(y))return y;let E=await Mo.bind(this)(y,p);return E.flag&&(s.encrypted=E.flag),E.value},b=ep(u);if(b!==u){s.data=await m(b);return}if(Di(u)){let y=u.__data__,E=a.find(w=>w.endsWith(y))||null;if(!E&&!r){await Promise.resolve();let w=Ha.call(this,t,y),T=false,R;if(w)try{let x=await Ke.bind(this)(w,{dataType:"blob",_ref:s.reference||null});R=JSON.parse(await Jr(x)),T=!0;}catch{}if(T){s.data=await m(R);return}g();}if(E){if(r){s.data=u;return}try{let w=await Ke.bind(this)(E,{dataType:"blob",_ref:s.reference||null}),T=await Jr(w);s.data=await m(JSON.parse(T));}catch(w){let T=Ha.call(this,t,y),R=false,x;if(T&&T!==E)try{let O=await Ke.bind(this)(T,{dataType:"blob",_ref:s.reference||null});x=JSON.parse(await Jr(O)),R=!0;}catch{}if(R){s.data=await m(x);return}console.error("Failed to fetch offloaded record data:",w),s.data=null,g();}return}}s.data=await m(u);}};if(t.record_id)return t;if(Array.isArray(t.bin))for(let u of t.bin)try{if(typeof u!="string")continue;ip(u);let p=u.split("/").slice(3);p.length>=12&&p[10]==="__data__"&&p[p.length-1]==="__json__.json"&&a.push(u),p.length>=12&&hi(p[10],p[p.length-1])&&(c=u);}catch{}let h=[];for(let u in d)if(t.hasOwnProperty(u)){let p=d[u](t[u]);p instanceof Promise&&h.push(p);}return o&&(s.user_id="anonymous:"+s.user_id),await Promise.all(h),s}function sp(t){let e=t.substring(3);switch(t.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 t}}async function za(t){let{endpoints:e}=t;if(typeof e=="string"&&(e=[e]),!Array.isArray(e))throw new f('"endpoints" should be type: array | string.',{code:"INVALID_PARAMETER"});let r=await P.bind(this)("del-files",{endpoints:e,storage:"records"},{auth:true,method:"post"}),n=[];for(let i in r)n.push(nt.bind(this)(r[i]));return Promise.all(n)}async function Ke(t,e){if(typeof t!="string")throw new f('"url" should be type: string.',{code:"INVALID_PARAMETER"});let r=t,n=t.split("?"),i=n.shift()||"",s=n.length?"?"+n.join("?"):"",o=_.Url(i);t=o+s;let a=false,c=o.split("/"),d=c[2].split("."),h=null;d.length===3&&d[1]==="skapi"&&(h=d[0],a=true);let u=c.slice(3),p=false;if(!a&&(u[0]==="auth"||u[0]==="publ"))try{_.UserId(u[2]),_.UserId(u[3]),p=u[0]=="auth",a=!0;}catch{throw new f("Invalid file url.",{code:"INVALID_PARAMETER"})}let g=h?null:u[1];if(e=_.Params(e,{expires:["number",()=>0],browserCache:["number",()=>0],refresh:["boolean",()=>false],dataType:["base64","blob","endpoint","text","info",()=>"download"],progress:["function","undefined",null],_ref:[null,"string"],_update:w=>w}),e?.dataType==="info")return {url:t,filename:u[u.length-1],fileKey:u[u.length-2],access_group:u[6]==="**"?"private":u[6]==="01"?"authorized":u[6]==="00"?"public":parseInt(u[6]),uploader:u[3],record_id:u[4]==="records"?u[5]:"N/A",filesize:Se(u[9]),uploaded:Se(u[8])};let m=t.split("/").slice(-1)[0],b=e.expires;if(b){if(!a)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 w={request:h?"get-host":"get",id:h||u[5],key:r.split("?")[0],expires:b};g&&(w.service=g);let T=e.browserCache,R={auth:true};if(T){if(T<0)throw new f('"config.browserCache" should be > 0. (seconds)',{code:"INVALID_PARAMETER"});R.method="get",R.stableGateway=true,w.browser_cache=T;let x=this.session?.idToken?.payload?.sub||this.user?.user_id;x&&(w.uid=x),w.nocache=Xh(b,e.refresh);}t=(await P.bind(this)("get-signed-url",w,R)).url;}else if(p){let w=Math.floor(Date.now()/1e3);if(!this.bearerToken&&(!this.session?.idToken?.payload?.exp||this.session.idToken.payload.exp<w)){this.log("getFile:requesting new token",null);try{await re.bind(this)().getSession({refreshToken:!0}),this.log("getFile:received new tokens",{exp:this.session?.idToken?.payload?.exp,currTime:w,expiresIn:this.session?.idToken?.payload?.exp-w,token:this.session?.accessToken?.jwtToken,refreshToken:this.session?.refreshToken?.token});}catch(O){throw this.log("getFile:new token error",O),new f("User login is required.",{code:"INVALID_REQUEST"})}}let T=this.bearerToken||this.session?.idToken?.jwtToken;if(!T||!this.user?.user_id)throw new f("User login is required.",{code:"INVALID_REQUEST"});t+=`${t.includes("?")?"&":"?"}t=${encodeURIComponent(T)}`;let R=u[6]==="**"?"**":parseInt(u[6]),x=this.user?.access_group??-1;if(this.user.user_id!==u[3]&&(R==="**"||x<R)){let O=u[5];if(this.__private_access_key[O]&&typeof this.__private_access_key[O]=="string")t+=`&p=${encodeURIComponent(this.__private_access_key[O])}`;else if(this.owner!==this.host)try{let U=await this.requestPrivateRecordAccessKey({record_id:O,reference_id:e?._ref});t+=`&p=${encodeURIComponent(U)}`;}catch{}}}if((V.call(this)?Ri(t):null)&&e?.dataType!=="endpoint"&&e?.dataType!=="info"){let w=await P.bind(this)(t,null,{method:"get",contentType:null,responseType:"blob",fetchOptions:{progress:e?.progress}},{ignoreService:true}),T=await oa.bind(this)(t,w);if(e?.dataType==="blob")return T;if(e?.dataType==="text")return await Jr(T);if(e?.dataType==="base64")return await new Promise((O,U)=>{let I=new FileReader;I.onloadend=()=>O(I.result),I.onerror=()=>U(I.error),I.readAsDataURL(T);});let R=URL.createObjectURL(T),x=document.createElement("a");return x.href=R,document.body.appendChild(x),x.setAttribute("download",m),x.click(),document.body.removeChild(x),setTimeout(()=>URL.revokeObjectURL(R),6e4),null}if(e?.dataType==="endpoint")return e._update&&(e._update.url=t),t;if(e?.dataType==="download"){let w=document.createElement("a");return w.href=t,document.body.appendChild(w),w.setAttribute("download",m),w.target="_blank",w.click(),document.body.removeChild(w),null}return new Promise(async(w,T)=>{try{let R=await P.bind(this)(t,null,{method:"get",contentType:null,responseType:e?.dataType==="text"?"text":"blob",fetchOptions:{progress:e?.progress}},{ignoreService:!0});if(e?.dataType==="base64"){let x=new FileReader;x.onloadend=()=>w(x.result),x.readAsDataURL(R);}else w(R);}catch(R){if(e?.browserCache&&!e?.refresh)try{w(await Ke.bind(this)(r,Object.assign({},e,{refresh:!0})));return}catch(x){T(x);return}T(R);}})}function Yr(t,e){return `${t||this.service}/${e||this.owner}`}function Ui(t,e){let r=this.__my_unique_ids[t];return r?r[e]:void 0}function Ja(t,e,r){this.__my_unique_ids[t]||(this.__my_unique_ids[t]={}),this.__my_unique_ids[t][e]=r;}function op(t,e){this.__my_unique_ids[t]&&delete this.__my_unique_ids[t][e];}function Ya(t,e){return !e||e.table===void 0?t:Object.assign({},t,{table:e.table})}async function tr(t){if(await this.__connection,!this.__user&&this.connection?.opt?.require_login===true)throw new f(`This project requires users to sign in before reading its database, so "${t}" is not available to a signed-out visitor.`,{code:"REQUIRE_LOGIN"})}async function Qa(t,e=false){t=$(t,{ignoreEmpty:true}).data||{};let r=Yr.bind(this)(t?.service,t?.owner),n="",i=ja(t);if(i){if(t=i,n=t.record_id||t.unique_id,typeof n=="string"){typeof this.__private_access_key?.[n]=="string"&&(t.private_key=this.__private_access_key?.[n]||void 0);let s=Ui.bind(this)(r,n);s&&(e?op.bind(this)(r,n):t.record_id=s);}}else {let s=await ne.bind(this)(),o=t?.reference,a=false;typeof o=="object"&&Object.keys(o).length&&(o?.record_id||o?.unique_id?(n=o.record_id||o.unique_id,n&&typeof this.__private_access_key?.[n]=="string"&&(t.private_key=this.__private_access_key?.[n]||void 0),t.reference=n):o?.user_id&&(a=o.user_id===this.user?.user_id,t.reference=o.user_id)),typeof t?.table=="string"&&(t.table={name:t.table,access_group:0}),t.index&&t.index.hasOwnProperty("range")&&t.index.hasOwnProperty("condition")&&delete t.index.range;let c=l=>({table:{name:d=>Tt(d,"table.name"),access_group:xi.bind(this),subscription:d=>_.UserId(d,'User ID in "subscription"')},reference:"string",index:{name:["$updated","$uploaded","$referenced_count","$user_id",d=>er(d,"index.name")],value:d=>{let h={$updated:"number",$uploaded:"number",$referenced_count:"number",$user_id:_.UserId};if(h.hasOwnProperty(l.index.name)){let u=h[l.index.name];if(typeof u=="function")return u(d);if(u!==typeof d)throw new f(`"index.value" should be type: ${u}.`,{code:"INVALID_PARAMETER"});return d}return typeof d=="string"&&!d?"":typeof d=="string"&&ki(l.index.name)?Ci(d,"index.value"):Wr(d)},condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq"],range:d=>Ka(d,l)},tag:d=>{if(d==null)return d;if(typeof d=="string")return Gr(d,"tag");throw new f('"tag" should be type: string.',{code:"INVALID_PARAMETER"})},private_key:"string"});t=_.Params(t||{},c(t),a||s?[]:["table"],{ignoreEmpty:true});}return {query:t,is_reference_fetch:n}}async function Xa(t,e){await this.__connection,await tr.call(this,"getRecords");let r=await Qa.bind(this)(t),n=r.is_reference_fetch,i=await P.bind(this)("get-records",r.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(nt.bind(this)(i.list[o]));return i.list=await Promise.all(s),i}function Ni(t){let e="",r=[],n=Yr.bind(this)(t?.service,t?.owner),i=_.Params(t||{},{record_id:o=>{let a=typeof o=="string"?Ui.bind(this)(n,o):void 0;return a||Oe(o,"record_id",{allowEmpty:false})},unique_id:["string",null],readonly:"boolean",table:{name:o=>Tt(o,"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:xi.bind(this)},notification:o=>{if(o==null)return o;if(typeof o!="object"||Array.isArray(o))throw new f('"notification" should be an object with "title" and "body".',{code:"INVALID_PARAMETER"});for(let a of ["title","body"])if(typeof o[a]!="string"||!o[a].trim())throw new f(`"notification.${a}" is required.`,{code:"INVALID_PARAMETER"});return {title:o.title,body:o.body}},source:{referencing_limit:o=>{if(o===null)return null;if(typeof o=="number"){if(0>o)throw new f('"reference_limit" should be >= 0',{code:"INVALID_PARAMETER"});if(o>4503599627370546)throw new f('"reference_limit" should be <= 4503599627370546',{code:"INVALID_PARAMETER"});return o}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:o=>{if(o===void 0)return;if(!o||Array.isArray(o)&&!o.length)return null;let a={name:l=>er(l,'"name" in "index_restrictions"'),value:l=>Wr(l),condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne",()=>null],range:l=>{if(l!==null&&typeof o.value!=typeof l)throw new f('Index restriction "range" type should match the type of "value".',{code:"INVALID_PARAMETER"});if(!o.hasOwnProperty("value"))throw new f('Index restriction "value" is required.',{code:"INVALID_PARAMETER"});return l}};Array.isArray(o)||(o=[o]);let c=o.map(l=>_.Params(l,a,["name"]));if(c.length)for(let l of c)l.condition&&l.hasOwnProperty("range")&&delete l.range;return c}},reference:o=>{if(o===null)return {record_id:null};if(o){if(typeof o=="string"){e=o;let a=Ui.bind(this)(n,o);return a||o}if(typeof o!="object")throw new f('"reference" should be type: <string | object>.',{code:"INVALID_PARAMETER"});return _.Params(o,{unique_id:"string",record_id:a=>a==null?a:(e=a,typeof this.__private_access_key?.[a]=="string"&&(t.reference_private_key=this.__private_access_key[a]||void 0),Oe(a,"reference.record_id",{allowEmpty:false,onlyAlphanumeric:true}))})}},index:[null,{name:o=>er(o,"index.name"),value:o=>Wr(o)}],tags:o=>{if(o==null)return o;if(typeof o=="string"&&(o=o.split(",").map(a=>a.trim())),!Array.isArray(o))throw new f('"tag" should be type: <string | string[]>.',{code:"INVALID_PARAMETER"});return o.map(a=>Gr(a,"tag"))},remove_bin:o=>{if(!o)return null;let a=[];if(Array.isArray(o))for(let c of o)if(typeof c=="string")a.push(c.split("?")[0]);else if(c.url&&c.size&&c.filename){let d=c.url.split("/").slice(0,3).join("/")+"/"+c.path;a.push(d);}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 a},progress:"function",data:o=>o},[],{precall:o=>{let a=o?.data||{};if(!a?.record_id&&!a.table)throw new f('"table.name" is required.',{code:"INVALID_PARAMETER"});typeof a.table=="string"&&(a.table={name:a.table},a?.record_id||(a.table.access_group=0)),o.files&&(r=o.files);}}),s=t.progress||null;if(delete i.progress,!this.__user){let o=!!(i.table?.subscription?.is_subscription_record||i.table?.subscription?.upload_to_feed||i.table?.subscription?.notify_subscribers||i.table?.subscription?.feed_referencing_records||i.table?.subscription?.notify_referencing_records);if(i.record_id)throw new f("Public users cannot update existing records.",{code:"INVALID_REQUEST"});if(i.table.access_group!=="public"&&i.table.access_group!==0)throw new f("Public users can only post records to public tables.",{code:"INVALID_REQUEST"});if(o)throw new f("Public users cannot post subscription records.",{code:"INVALID_REQUEST"});if(i.remove_bin)throw new f("Public users cannot remove files from records.",{code:"INVALID_REQUEST"});if(i.unique_id)throw new f("Public users cannot set unique_id for records.",{code:"INVALID_REQUEST"})}return {config:i,progress:s,is_reference_post:e,files:r}}async function Oi(t){if(await this.__connection,!Array.isArray(t)||!t.length)throw new f('"params" should be a non-empty array.',{code:"INVALID_PARAMETER"});let e=[],r,n,i=null,s={},o={},c={_is_bulk_:await Promise.all(t.map(async(g,m)=>{if(!g||typeof g!="object"||Array.isArray(g))throw new f(`"params[${m}]" should be type: <object>.`,{code:"INVALID_PARAMETER"});o[m]={has:g.data!==void 0,value:g.data};let b=Ni.bind(this)(g),y=b.config;if(V.call(this)){let E=Object.prototype.hasOwnProperty.call(y,"data"),w=await pi.bind(this)(y.data,Ya(g,y),E);w.encrypted&&(y.data=w.send,s[m]=w.plain);}if(b.is_reference_post&&e.push(b.is_reference_post),typeof y.progress=="function"&&i===null&&(i=y.progress),y.service!==void 0){if(r===void 0)r=y.service;else if(r!==y.service)throw new f('All bulk params should share the same "service" value.',{code:"INVALID_PARAMETER"})}if(y.owner!==void 0){if(n===void 0)n=y.owner;else if(n!==y.owner)throw new f('All bulk params should share the same "owner" value.',{code:"INVALID_PARAMETER"})}return delete y.progress,delete y.service,delete y.owner,y})),service:"",owner:""};r!==void 0&&(c.service=r),n!==void 0&&(c.owner=n);let l={auth:!!this.__user,method:"post"},d={};Object.keys(d).length&&Object.assign(l,{fetchOptions:d});let h=await P.bind(this)("post-record",c,l),u=await Promise.all(h.map((g,m)=>nt.bind(this)(g,"called from postRecord",o[m]?.has===true,s.hasOwnProperty(m))));for(let g=0;g<u.length;g++)s.hasOwnProperty(g)&&u[g]&&!u[g].error?(u[g].data=s[g],u[g].encrypted={status:"encrypted"}):o[g]?.has&&u[g]&&!h[g]?.error&&Di(h[g]?.data)&&(u[g].data=o[g].value);let p=Yr.bind(this)(r,n);for(let g=0;g<h.length;g++){let m=h[g],b=u[g];if(m&&typeof m=="object"&&m.error&&b&&!b.record_id&&(b.error=m.error),typeof m?.reference_private_key=="string")for(let y of e)this.__private_access_key[y]=m.reference_private_key;b?.unique_id&&Ja.bind(this)(p,b.unique_id,b.record_id);}return u}async function Fi(t,e,r){if(await this.__connection,!e)throw new f('"config" argument is required.',{code:"INVALID_PARAMETER"});let n=Ni.bind(this)(e),i=n.config,s=n.progress,o=n.is_reference_post,a={auth:!!this.__user,method:"post"},c=[],l=$(t);r&&Array.isArray(r)&&r.length&&(c=c.concat(r)),l.files&&Array.isArray(l.files)&&l.files.length&&(c=c.concat(l.files));let d=e?.data!==void 0?e.data:l.data,h=d!==void 0,u=await pi.bind(this)(d,Ya(e,i),h),p=null;p=Object.assign({},i),delete p.data,u.omit||(p.data=u.send);let g={};if(typeof s=="function"&&(g.progress=s),Object.keys(g).length&&Object.assign(a,{fetchOptions:g}),u.files==="decrypt"&&e?.record_id){let w=await Ti.bind(this)(e.record_id,"decrypt",s);if(w.length){let T=p.remove_bin;p.remove_bin=Array.isArray(T)?T.concat(w):w;}}if(u.spill&&e?.record_id){let w=new FormData;if(w.append(Wt,new File([u.spill],"payload.bin",{type:"application/octet-stream"})),await Zt.bind(this)(w,{record_id:e.record_id}),u.retireCt){let T=p.remove_bin,R=[u.retireCt];p.remove_bin=Array.isArray(T)?T.concat(R):R;}}let m=await P.bind(this)("post-record",p,a);if(u.encrypted&&m?.rec&&Fo.bind(this)(m.rec,u.dek),u.files==="encrypt"&&m?.rec)try{let w=await Ti.bind(this)(m.rec,"encrypt",s);w.length&&await Fi.bind(this)(void 0,{record_id:m.rec,remove_bin:w});}catch(w){console.error("Failed to encrypt existing attachments after making the record private:",w);}if(X()&&c.length){let w=new FormData;for(let x of c)w.append(x.name,x.file,x.file.name);let T={record_id:m.rec,progress:s};i.hasOwnProperty("service")&&(T.service=i.service);let{bin_endpoints:R}=await Zt.bind(this)(w,T);m.bin?m.bin.push(...R):m.bin=R;}o&&typeof m?.reference_private_key=="string"&&(this.__private_access_key[o]=m.reference_private_key);let b=!!m&&Di(m.data),y=!u.omit&&u.send!==void 0,E=await nt.bind(this)(m,"called from postRecord",y,u.encrypted);if(b&&y&&!u.encrypted&&(E.data=u.plain),u.encrypted&&(E.data=u.plain,E.encrypted={status:"encrypted",recipients:Object.keys(u.send.k||{})}),E.unique_id){let w=Yr.bind(this)(i?.service,i?.owner);Ja.bind(this)(w,E.unique_id,E.record_id),X()&&(this.__uniqueIdsPersistTimer!==null&&clearTimeout(this.__uniqueIdsPersistTimer),this.__uniqueIdsPersistTimer=setTimeout(()=>{this.__uniqueIdsPersistTimer=null;try{window.sessionStorage.setItem(`${w}:uniqueids`,JSON.stringify(this.__my_unique_ids[w]||{}));}catch{}},500));}return E}async function Za(t,e){await tr.call(this,"getTables");let r=await P.bind(this)("get-table",_.Params(t||{},{table:i=>Tt(i,"table",{allowEmpty:true}),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(r?.list))for(let i of r.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=Pe(i.table));}return r}async function ec(t,e){if(await tr.call(this,"getIndexes"),!t?.table)throw new f('"table" is required.',{code:"INVALID_PARAMETER"});let r=_.Params(t||{},{table:s=>Tt(s,"table",{allowEmpty:true}),index:s=>er(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:s=>{if(t?.order?.by==="index_name"&&typeof s=="string")return Oe(s,"order.value",{allowEmpty:true,maxLength:256,blockKeyDelimiters:true});if(typeof s!="string"&&typeof s!="number"&&typeof s!="boolean")throw new f('"order.value" should be type: <string | number | boolean>.',{code:"INVALID_PARAMETER"});return s},condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}},["table"]);if(r.hasOwnProperty("order")){if(!r.order?.by)throw new f('"order.by" is required.',{code:"INVALID_PARAMETER"});if(r.order.hasOwnProperty("condition")&&!r.order.hasOwnProperty("value"))throw new f('"value" is required for "condition".',{code:"INVALID_PARAMETER"});if(r.hasOwnProperty("index")&&r.index.substring(r.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 P.bind(this)("get-index",r,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:Pe(o[1]),index:Pe(o[2]),number_of_records:s.cnt_rec};for(let c in i)Object.prototype.hasOwnProperty.call(s,c)&&(a[i[c]]=s[c]);return a})),n}async function tc(t,e){await tr.call(this,"getTags");let r=await P.bind(this)("get-tag",_.Params(t||{},{table:n=>Tt(n,"table",{allowEmpty:true}),tag:n=>Gr(n,"tag",{allowEmpty:true}),condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}),Object.assign({auth:!!this.__user},{fetchOptions:e}));return Array.isArray(r?.list)&&(r.list=r.list.map(n=>{let i=n.tag.split("/");return {table:Pe(i[1]),tag:Pe(i[0]),number_of_records:n.cnt_rec}})),r}async function rc(t,e){await tr.call(this,"getUniqueId");let r=await P.bind(this)("get-uniqueid",_.Params(t||{},{unique_id:"string",condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}),Object.assign({auth:!!this.__user},{fetchOptions:e}));if(Array.isArray(r?.list))for(let n in r.list){let i=r.list[n];r.list[n]={unique_id:i.unq,record_id:i.rec};}return r}async function nc(t,e){await this.__connection;let r=await Qa.bind(this)(t,true),n=r.is_reference_fetch,i=await P.bind(this)("del-records",r.query,{auth:true,fetchOptions:e});return n&&typeof i?.reference_private_key=="string"&&(this.__private_access_key[n]=i.reference_private_key),Array.isArray(i?.list)&&(i.list=await Promise.all(i.list.map(async s=>{if(!s||typeof s!="object")return s;try{return await nt.bind(this)(s,"called from deleteRecords",!0,!1,!0)}catch{return s}}))),i?.message||i}async function ic(t){if(V.call(this)){let e=typeof t.user_id=="string"?[t.user_id]:t.user_id;Array.isArray(e)&&e.length&&await Ai.bind(this)(t.record_id,e);}return cc.bind(this)({record_id:t.record_id,user_id:t.user_id,execute:"add"})}async function sc(t){let e=await cc.bind(this)({record_id:t.record_id,user_id:t.user_id||null,execute:"remove"});if(V.call(this)){let r=typeof t.user_id=="string"?[t.user_id]:t.user_id;await Qo.bind(this)(t.record_id,Array.isArray(r)&&r.length?r:null);}return e}async function oc(t,e){let r={record_id:t.record_id||void 0,user_id:t.user_id||void 0,execute:"list"};if(!r.record_id&&!r.user_id)throw new f("Either record_id or user_id must be provided.",{code:"INVALID_PARAMETER"});if(r.user_id)if(typeof r.user_id=="string")_.UserId(r.user_id),r.user_id=[r.user_id];else if(Array.isArray(r.user_id))for(let s of r.user_id)_.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 P.bind(this)("grant-private-access",r,{auth:true,fetchOptions:e});return i.list=i.list.map(n),i}function ac(t){let e=t.record_id,r=t.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(r&&typeof r!="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(zr[e])return zr[e];let n=P.bind(this)("request-private-access-key",{record_id:e,reference_id:r},{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 zr[e];});return zr[e]=n,n}function cc(t){t.execute;let r=_.Params(t,{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)_.UserId(s,'User ID in "user_id"');return i},execute:["add","remove"]},["execute","record_id","user_id"]);return r.user_id||(r.user_id=null),P.bind(this)("grant-private-access",r,{auth:true})}var ap=100;async function lc(t){if(await this.__connection,!Array.isArray(t)||!t.length)throw new f('"items" should be a non-empty array.',{code:"INVALID_PARAMETER"});let e=[],r=[],n=[];for(let s=0;s<t.length;s++){let o=t[s];try{if(!o||typeof o!="object"||Array.isArray(o))throw new f(`"items[${s}]" should be an object with "config".`,{code:"INVALID_PARAMETER"});let a=o.config;if(!a||typeof a!="object"||Array.isArray(a))throw new f(`"items[${s}].config" is required.`,{code:"INVALID_PARAMETER"});Ni.bind(this)(Object.assign({},a));let c=Object.assign({},a);delete c.data;let l=a.data!==void 0?a.data:o.data;if(l!==void 0){let d=l!==null&&typeof l=="object"?$(l):{data:l,files:[]};if(d.files&&d.files.length)throw new f(`"items[${s}].data" carries files. postRecords() does not attach files; use uploadFiles() on the saved record.`,{code:"INVALID_PARAMETER"});c.data=d.data;}n.push({index:s,config:c});}catch(a){r.push({index:s,code:String(a?.code||"INVALID_PARAMETER"),message:String(a?.message||a)});}}let i=0;for(;i<n.length;){let s=n.slice(i,i+ap),o=await Oi.bind(this)(s.map(c=>Object.assign({},c.config)));if(!Array.isArray(o)||!o.length){for(let c of s)r.push({index:c.index,code:"ERROR",message:"The server answered nothing for this record."});i+=s.length;continue}let a=Math.min(o.length,s.length);for(let c=0;c<a;c++){let l=o[c];if(l&&l.record_id)e.push(l);else {let d=l?.error||{};r.push({index:s[c].index,code:String(d.code||"ERROR"),message:String(d.message||"The record was not saved.")});}}i+=a;}return r.sort((s,o)=>s.index-o.index),{list:e,failed:r}}var L={},z={},fe={},ke={},Te={},G={},Xr={};function vt(t,e){let r=(Xr[t]||Promise.resolve()).then(e,e);return Xr[t]=r.catch(()=>{}),r}var Zr={},en={};function fc(t,e,r){t[e]||(t[e]=[]),t[e].push(r);}async function hc(t,e,r){let n=[];if(t[e]){let i=t[e];delete t[e];for(let s of i)if(s){let o=r(s);o instanceof Promise&&(o=await o),n.push(o);}}return n}var Li="stun:stun.skapi.com:3468",pc=["text","detail","motion"],uc={"text-chat":{ordered:true,maxRetransmits:10,protocol:"text-chat"},"file-transfer":{ordered:false,maxPacketLifeTime:3e3,protocol:"file-transfer"},"video-chat":{ordered:true,maxRetransmits:10,protocol:"video-chat"},"voice-chat":{ordered:true,maxRetransmits:10,protocol:"voice-chat"},gaming:{ordered:false,maxPacketLifeTime:100,protocol:"gaming"},default:{ordered:true,maxRetransmits:10,protocol:"default"}};function K(t){return new f(t,{code:"INVALID_PARAMETER"})}function ee(t){return !!t&&typeof t=="object"&&!Array.isArray(t)}function Vi(){return typeof MediaStream<"u"}function Re(){return new Date().toISOString()}async function cp(){let t=jc();if(!t)try{t=await ji.bind(this)();}catch{t=null;}let e=t?t.servers:[{urls:Li}];return e.some(r=>(Array.isArray(r.urls)?r.urls:[r.urls]).some(n=>/^stuns?:/.test(n)))?e:[{urls:Li},...e]}function lp(t){if(t==null||t==="")return [{urls:Li}];let e=r=>typeof r=="string"&&/^(stun|stuns|turn|turns):/.test(r);if(typeof t=="string"){if(!e(t))throw K('"ice" should be a "stun:", "stuns:", "turn:" or "turns:" url, or a list of { urls, username, credential }.');return [{urls:t}]}if(!Array.isArray(t)||!t.length)throw K('"ice" should be a url string, or a non-empty list of { urls, username, credential }.');return t.map((r,n)=>{if(!ee(r))throw K(`"ice[${n}]" should be an object: { urls, username, credential }.`);let i=r.urls,s=Array.isArray(i)?i:[i];if(!s.length||!s.every(e))throw K(`"ice[${n}].urls" should be a "stun:", "stuns:", "turn:" or "turns:" url, or a list of them.`);let o={urls:i};for(let a of ["username","credential"])if(r[a]!==void 0){if(typeof r[a]!="string")throw K(`"ice[${n}].${a}" should be type: <string>.`);o[a]=r[a];}if(s.some(a=>/^turns?:/.test(a))&&(!o.username||!o.credential))throw K(`"ice[${n}]" is a TURN server: it needs "username" and "credential".`);return o})}async function gc(t,e){let r={iceServers:t==null||t===""?await cp.bind(this)():lp(t)};return e&&(r.iceTransportPolicy=e),r}function mc(t){if(typeof t!="string")throw K('"cid" should be type: <string>.');if(t&&t.slice(0,4)!=="cid:")throw K('"cid" should be a valid connection id.');return t}function yc(t){if(t!=null){if(t!=="all"&&t!=="relay")throw K('"icePolicy" should be "all" or "relay".');return t}}function bc(t){if(!(t==null||t===false)){if(Vi()&&t instanceof MediaStream)return t;if(!ee(t))throw K('"media" should be a MediaStream, or an object: { audio, video, screen }.');for(let e of ["audio","video"])if(t[e]!==void 0&&typeof t[e]!="boolean"&&!ee(t[e]))throw K(`"media.${e}" should be a boolean or track constraints.`);if(t.screen!==void 0&&typeof t.screen!="boolean"&&!ee(t.screen))throw K('"media.screen" should be true, or the options of getDisplayMedia().');if(ee(t.screen)&&t.screen.contentHint!==void 0&&!pc.includes(t.screen.contentHint))throw K('"media.screen.contentHint" should be "text", "detail" or "motion".');return t}}function _c(t){return ee(t)&&!!(t.audio||t.video||t.screen)}function tn(){if(window.location.hostname!=="localhost"&&window.location.protocol!=="https:")throw new f("Media stream is only supported on either localhost or https.",{code:"INVALID_REQUEST"})}function wc(t){if(t!=null){if(!ee(t))throw K('"receive" should be an object: { audio, video }.');for(let e of ["audio","video"])if(t[e]!==void 0&&typeof t[e]!="boolean")throw K(`"receive.${e}" should be type: <boolean>.`);return t}}function Ec(t){if(t==null)return null;if(!ee(t))throw K('"encoding" should be an object: { video, audio }.');for(let e of ["video","audio"]){let r=t[e];if(r!==void 0){if(!ee(r))throw K(`"encoding.${e}" should be an object.`);if(r.codecs!==void 0&&(!Array.isArray(r.codecs)||!r.codecs.every(n=>typeof n=="string"&&n)))throw K(`"encoding.${e}.codecs" should be a list of codec names.`);for(let n of ["maxBitrate","maxFramerate","scaleResolutionDownBy"])if(r[n]!==void 0&&!(typeof r[n]=="number"&&r[n]>0))throw K(`"encoding.${e}.${n}" should be a positive number.`)}}return t}function Ac(t,e){if(t==null)return e;if(!Array.isArray(t))throw K('"channels" should be an array of preset names or RTCDataChannelInit objects.');let r={ordered:"boolean",maxPacketLifeTime:"number",maxRetransmits:"number",protocol:"string",negotiated:"boolean",id:"number"};return t.map((n,i)=>{if(typeof n=="string"){if(!n)throw K(`"channels[${i}]" should be a preset name or RTCDataChannelInit.`);return n}if(!ee(n))throw K(`"channels[${i}]" should be a preset name or RTCDataChannelInit.`);for(let[s,o]of Object.entries(r))if(n[s]!==void 0&&typeof n[s]!==o)throw K(`"channels[${i}].${s}" should be type: <${o}>.`);if(n.negotiated&&typeof n.id!="number")throw K(`"channels[${i}]" is negotiated: it needs an "id" both sides open it with.`);return n})}function up(t){if(t==null)return {};if(!ee(t))throw K('"meta" should be an object.');try{return JSON.parse(JSON.stringify(t))}catch{throw K('"meta" should be a JSON object.')}}function Rc(t,e,r){return {polite:t,makingOffer:false,ignoreOffer:false,armed:false,meta:e,media:new MediaStream,user:null,sources:new Map,wires:new Map,cleanup:new Map,remoteSources:{},encoding:r,receive:null,ringTimer:null}}function Mi(t){let e=G[t];if(e){clearTimeout(e.ringTimer);for(let r of e.cleanup.values())r();for(let r of e.media.getTracks())r.stop();}L[t]&&L[t].signalingState!=="closed"&&L[t].close(),delete G[t],delete L[t],delete z[t],delete Te[t],delete Xr[t];}async function Tc(t,e){let r=G[t],{contentHint:n,source:i,...s}=ee(e)?e:{},a=(await window.navigator.mediaDevices.getDisplayMedia(Object.keys(s).length?s:{video:true})).getTracks();for(let c of a)if(r.sources.set(c,"screen"),c.kind==="video"&&n)try{c.contentHint=n;}catch{}return a}async function Sc(t,e){let r=G[t],n=await window.navigator.mediaDevices.getUserMedia(e),i=n.getTracks();for(let s of i)r.sources.set(s,s.kind==="audio"?"microphone":"camera");if(!r.user)r.user=n;else for(let s of i)r.user.addTrack(s);return i}async function vc(t,e){let r=G[t];if(!e||!r)return;if(Vi()&&e instanceof MediaStream){for(let s of e.getTracks())r.sources.set(s,"custom");Qr.call(this,t,e.getTracks(),e);return}let{screen:n,...i}=e;if(i.audio||i.video){let s=await Sc(t,i);Qr.call(this,t,s,r.user);}if(n){let s=await Tc(t,n===true?{}:n);Qr.call(this,t,s,new MediaStream(s));}}function Qr(t,e,r){let n=L[t],i=G[t];if(!(!n||!i)){for(let s of e){i.sources.has(s)||i.sources.set(s,"custom"),r.getTracks().includes(s)||r.addTrack(s),i.wires.set(s,r),i.media.getTracks().includes(s)||i.media.addTrack(s),n.getSenders().some(a=>a.track===s)||n.addTrack(s,r);let o=()=>qi.call(this,t,s,false,true);s.addEventListener("ended",o,{once:true}),i.cleanup.set(s,()=>s.removeEventListener("ended",o));}Pc.call(this,t),rr.call(this,t);}}function qi(t,e,r,n=false){let i=L[t],s=G[t];if(!s||!s.sources.has(e)){r&&e.stop();return}let o=s.sources.get(e),a=s.cleanup.get(e);if(a&&a(),s.cleanup.delete(e),i&&i.signalingState!=="closed"){let d=i.getSenders().find(h=>h.track===e);if(d)try{i.removeTrack(d);}catch(h){this.log("removeTrack",h);}}let c=s.wires.get(e);c&&c.removeTrack(e),s.wires.delete(e),s.media.removeTrack(e),s.sources.delete(e),r&&e.stop();let l=Te[t];l&&l({type:"unshare",target:i,timestamp:Re(),track:e,source:o,ended:n});}function Ic(t,e){let r=L[t];if(!(!r||!e))for(let n of ["audio","video"]){if(!e[n])continue;r.getTransceivers().some(s=>s.sender.track&&s.sender.track.kind===n||s.receiver.track&&s.receiver.track.kind===n)||r.addTransceiver(n,{direction:"recvonly"});}}function dp(t,e){let r=typeof RTCRtpReceiver<"u"?RTCRtpReceiver:null,n=r&&typeof r.getCapabilities=="function"?r.getCapabilities(t):null;if(!n||!n.codecs)return null;let i=e.map(o=>(o.includes("/")?o:`${t}/${o}`).toLowerCase()),s=[];for(let o of i)for(let a of n.codecs)a.mimeType.toLowerCase()===o&&!s.includes(a)&&s.push(a);return s.length?[...s,...n.codecs.filter(o=>!s.includes(o))]:null}function Pc(t){let e=L[t],r=G[t];if(!(!e||!r||!r.encoding))for(let n of ["audio","video"]){let i=r.encoding[n]&&r.encoding[n].codecs;if(!i||!i.length)continue;let s=dp(n,i);if(s){for(let o of e.getTransceivers())if((o.sender.track&&o.sender.track.kind||o.receiver.track&&o.receiver.track.kind)===n&&typeof o.setCodecPreferences=="function")try{o.setCodecPreferences(s);}catch(c){this.log("setCodecPreferences",c);}}}}function rr(t){let e=L[t],r=G[t];if(!(!e||!r||!r.encoding))for(let n of e.getSenders()){let i=n.track;if(!i)continue;let s=r.encoding[i.kind];if(!s)continue;let o={};for(let l of ["maxBitrate","maxFramerate","scaleResolutionDownBy"])s[l]!==void 0&&(o[l]=s[l]);if(!Object.keys(o).length)continue;let a;try{a=n.getParameters();}catch{continue}if(!a.encodings||!a.encodings.length)continue;let c=false;for(let l in o)a.encodings[0][l]!==o[l]&&(a.encodings[0][l]=o[l],c=true);c&&n.setParameters(a).catch(l=>this.log("setParameters",l));}}function Bi(t,e){let r=L[t];if(!r||r.signalingState==="closed")throw new f("The call is closed.",{code:"INVALID_REQUEST"});let n=typeof e=="string"?uc[e]||{...uc.default,protocol:e}:{...e},i=n.protocol||"default";if(z[t]||(z[t]={}),z[t][i])throw new f(`Data channel with the protocol "${i}" already exists.`,{code:"INVALID_REQUEST"});let s=r.createDataChannel(i,n);return z[t][i]=s,Bc.call(this,t,s,i),s}function kc(t){let e=L[t];e.ondatachannel=r=>{let n=r.channel;z[t]||(z[t]={});let i=n.label;z[t][i]&&z[t][i]!==n&&(i=`${n.label}#${n.id}`),this.log("ondatachannel",`received data channel "${i}".`),z[t][i]=n,Bc.call(this,t,n,i);};}async function Cc(t,e){if(!this?.session?.accessToken?.jwtToken)throw new f("Access token is required.",{code:"INVALID_PARAMETER"});let r=await this.__socket;if(!r||r.readyState!==1)throw new f("Realtime connection is not ready.",{code:"INVALID_REQUEST"});r.send(JSON.stringify({action:"rtc",uid:t,content:e,token:this.session.accessToken.jwtToken}));}function xc(t){let e=L[t],r=G[t],n={};if(!e||!r)return n;for(let i of e.getTransceivers())i.mid&&i.sender.track&&r.sources.has(i.sender.track)&&(n[i.mid]=r.sources.get(i.sender.track));return n}function Uc(t,e){let r=G[t];if(r&&ee(e))for(let n in e)typeof e[n]=="string"&&(r.remoteSources[n]=e[n]);}async function Dc(t,e={}){let r=L[t],n=G[t];if(!(!r||!n||r.signalingState==="closed"))try{n.makingOffer=!0;let i=await r.createOffer();if(r.signalingState!=="stable"){this.log("sendOffer",`offer to "${t}" dropped: an offer from the other side came first.`);return}await r.setLocalDescription(i),rr.call(this,t),this.log("rtcSdpOffer to",t),await Cc.call(this,t,{sdpoffer:r.localDescription,sources:xc(t),...e});}finally{n.makingOffer=false;}}function Nc(t){let e=L[t],r=G[t];!e||!r||r.armed||(r.armed=true,e.onnegotiationneeded=()=>{this.log("onnegotiationneeded",`sending offer to "${t}".`),Dc.call(this,t).catch(i=>this.log("onnegotiationneeded",i));let n=Te[t];n&&n({type:"negotiationneeded",target:e,timestamp:Re(),signalingState:e.signalingState,connectionState:e.iceConnectionState,gatheringState:e.iceGatheringState});});}async function dc(t,e){let r=L[e],n=G[e];if(!r||!n||r.signalingState==="closed"||!t?.sdpoffer)return;let i=n.makingOffer||r.signalingState!=="stable";if(n.ignoreOffer=!n.polite&&i,n.ignoreOffer){this.log("answerSdpOffer",`offer from "${e}" ignored: this side is offering.`);return}Uc(e,t.sources),this.log("answerSdpOffer from",e),await r.setRemoteDescription(new RTCSessionDescription(t.sdpoffer)),n.receive&&(Ic(e,n.receive),n.receive=null),Pc.call(this,e);let s=await r.createAnswer();Nc.call(this,e),await r.setLocalDescription(s),rr.call(this,e),await Cc.call(this,e,{sdpanswer:r.localDescription,sources:xc(e)}),await nn.call(this,null,e);}async function rn(t,e){if(!this?.session?.accessToken?.jwtToken)throw new f("Access token is required.",{code:"INVALID_PARAMETER"});L?.[e]&&G[e]?(await hc(en,e,r=>dc.call(this,r,e)),t&&await dc.call(this,t,e)):t&&fc(en,e,t);}async function Oc(t,e){let r=L[e],n=G[e];if(!(!r||!n||!t?.sdpanswer)){if(r.signalingState!=="have-local-offer"){this.log("sdpanswer",`answer from "${e}" ignored in signaling state "${r.signalingState}".`);return}Uc(e,t.sources),Nc.call(this,e),await r.setRemoteDescription(new RTCSessionDescription(t.sdpanswer)),rr.call(this,e),await nn.call(this,null,e);}}function Fc(t){delete en[t],delete Zr[t];}async function nn(t,e){this.log("receiveIceCandidate",t);let r=L?.[e];if(r&&r.remoteDescription&&r.remoteDescription.type){let n=async i=>{try{await r.addIceCandidate(i);}catch(s){G[e]?.ignoreOffer||this.log("addIceCandidate",s);}};await hc(Zr,e,n),t&&await n(t);}else fc(Zr,e,t);}async function Ce(t){if(typeof window>"u"||window._runningInNodeJS)throw new f("WebRTC is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});_.Params(t,{cid:mc,close_all:"boolean"});let e=this.__socket?await this.__socket:null,{cid:r,close_all:n=false}=t||{};if(!n&&!r)throw new f('"cid" is required.',{code:"INVALID_PARAMETER"});let i=s=>{if(!s)throw new f('"cid" is required.',{code:"INVALID_PARAMETER"});delete en[s],delete Zr[s];let o=G[s];if(o){clearTimeout(o.ringTimer);for(let a of o.cleanup.values())a();}if(z[s]&&Object.values(z[s]).forEach(a=>{a.readyState!=="closed"&&a.close();}),delete z[s],L?.[s]){L[s].connectionState!=="closed"&&(L[s].close(),e&&e.readyState===1&&this?.session?.accessToken?.jwtToken&&e.send(JSON.stringify({action:"rtc",uid:s,content:{hungup:this.user.user_id},token:this.session.accessToken.jwtToken})));let a={type:"connectionstatechange",target:L[s],timestamp:Re(),state:L[s].connectionState,iceState:L[s].iceConnectionState,signalingState:L[s].signalingState};Te[s]&&Te[s](a),this.log("closeRTC",a);}if(o){this.log("Cleaning up media stream...",s);for(let a of o.media.getTracks())a.stop();}delete G[s],delete Te[s],delete ke[s],delete fe[s],delete L[s],delete Xr[s];};if(n)for(let s in L)i(s);else i(r);}function Lc(t){let e=this,r=L[t],n=G[t],i=()=>{if(!G[t]||!L[t]||L[t].signalingState==="closed")throw new f("The call is closed.",{code:"INVALID_REQUEST"})},s=a=>{if(typeof MediaStreamTrack<"u"&&a instanceof MediaStreamTrack)return n.sources.has(a)?[a]:[];if(typeof a!="string")throw K('Name a source ("camera", "microphone", "screen", or a name given to share()), or pass a MediaStreamTrack.');let c=[];for(let[l,d]of n.sources)d===a&&c.push(l);return c},o=a=>{let c=()=>qi.call(e,t,a,false,true);a.addEventListener("ended",c,{once:true}),n.cleanup.set(a,()=>a.removeEventListener("ended",c));};return {cid:t,target:r,channels:z[t],media:n.media,meta:n.meta,hangup:()=>Ce.call(e,{cid:t}),tracks:a=>a===void 0?Array.from(n.sources.keys()):s(a),share:async(a,c)=>{i();let l=ee(c)?c:{};if(l.contentHint!==void 0&&!pc.includes(l.contentHint))throw K('"contentHint" should be "text", "detail" or "motion".');let d,h;if(a==="screen")tn(),d=await Tc(t,l),h=new MediaStream(d);else if(a==="camera"||a==="microphone"){tn();let{contentHint:u,source:p,...g}=l,m=Object.keys(g).length?g:true;d=await Sc(t,a==="camera"?{video:m}:{audio:m}),h=n.user;}else if(Vi()&&a instanceof MediaStream){d=a.getTracks(),h=a;for(let u of d)n.sources.set(u,typeof l.source=="string"&&l.source?l.source:"custom");}else if(typeof MediaStreamTrack<"u"&&a instanceof MediaStreamTrack)d=[a],h=new MediaStream([a]),n.sources.set(a,typeof l.source=="string"&&l.source?l.source:"custom");else throw K('share() takes "screen", "camera", "microphone", a MediaStream or a MediaStreamTrack.');if(l.contentHint){for(let u of d)if(u.kind==="video")try{u.contentHint=l.contentHint;}catch{}}return i(),Qr.call(e,t,d,h),d},unshare:a=>{for(let c of s(a))qi.call(e,t,c,true);},replace:async(a,c)=>{if(i(),typeof MediaStreamTrack>"u"||!(c instanceof MediaStreamTrack))throw K("replace() needs the MediaStreamTrack to send instead.");let l=s(a).find(g=>g.kind===c.kind);if(!l)throw new f(`No ${c.kind} track of "${typeof a=="string"?a:"that track"}" is on the call.`,{code:"INVALID_REQUEST"});let d=r.getSenders().find(g=>g.track===l);if(!d)throw new f("The track is not being sent.",{code:"INVALID_REQUEST"});await d.replaceTrack(c);let h=n.sources.get(l),u=n.wires.get(l),p=n.cleanup.get(l);p&&p(),n.cleanup.delete(l),u&&(u.removeTrack(l),u.addTrack(c),n.wires.set(c,u)),n.media.removeTrack(l),n.media.addTrack(c),n.sources.delete(l),n.wires.delete(l),l.stop(),n.sources.set(c,h),o(c),rr.call(e,t);},mute:a=>{if(!ee(a))throw K("mute() takes { audio, video, screen }.");for(let[c,l]of n.sources)l==="screen"?typeof a.screen=="boolean"&&(c.enabled=!a.screen):c.kind==="audio"?typeof a.audio=="boolean"&&(c.enabled=!a.audio):typeof a.video=="boolean"&&(c.enabled=!a.video);},addChannel:(a,c)=>{if(i(),typeof a!="string"||!a)throw K("addChannel() needs the name of the channel.");if(c!==void 0&&!ee(c))throw K("addChannel() takes RTCDataChannelInit as its second argument.");return Bi.call(e,t,c?{...c,protocol:a}:a)}}}async function Mc(t,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"});let r=$(t||{}).data||{},{media:n,...i}=r,s=_.Params(i,{cid:mc,ice:E=>E,icePolicy:E=>E,receive:E=>E,encoding:E=>E,channels:E=>E,meta:E=>E,ringTimeout:"number"},["cid"]),o=s.cid,a=bc(n),c=yc(s.icePolicy),l=wc(s.receive),d=Ec(s.encoding),h=Ac(s.channels,["default"]),u=up(s.meta);if(s.ringTimeout!==void 0&&!(s.ringTimeout>0))throw K('"ringTimeout" should be a positive number of milliseconds.');_c(a)&&tn();let p=this.__socket?await this.__socket:this.__socket;if(!p)throw new f("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});if(p.readyState!==1)throw new f("Realtime connection is not ready.",{code:"INVALID_REQUEST"});let g=await gc.call(this,s.ice,c),m=!L?.[o];m&&(L[o]=new RTCPeerConnection(g),G[o]=Rc(false,u,d));let b=L[o],y=G[o];m||(y.meta=u,y.encoding=d),Te[o]=e,z[o]||(z[o]={}),kc.call(this,o);try{await vc.call(this,o,a);}catch(E){throw m&&Mi(o),E}Ic(o,l);for(let E of h)Bi.call(this,o,E);return Vc.call(this,o),await Dc.call(this,o,{meta:u}),s.ringTimeout&&(y.ringTimer=setTimeout(()=>{if(!fe[o])return;this.log("ringTimeout",`no answer from "${o}" within ${s.ringTimeout} ms.`);let E=Te[o];E&&E({type:"ringtimeout",target:b,timestamp:Re(),cid:o}),fe[o](false);},s.ringTimeout)),{hangup:()=>fe[o]?fe[o](false):Ce.call(this,{cid:o}),connection:new Promise(E=>{fe[o]=(w=>{if(clearTimeout(y.ringTimer),delete fe[o],this.log("receiver picked up the call",o,w),!w)return Ce.call(this,{cid:o}),null;E(Lc.call(this,o));}).bind(this);})}}function qc(t){return async(e,r)=>{let n=$(e||{}).data||{},{media:i,...s}=n,o=_.Params(s,{ice:y=>y,icePolicy:y=>y,receive:y=>y,encoding:y=>y,channels:y=>y}),a=t.sender_cid,c=await this.__socket;if(!ke[a])return null;if(typeof r!="function")throw new f("Callback is required.",{code:"INVALID_PARAMETER"});let l=bc(i),d=yc(o.icePolicy),h=wc(o.receive),u=Ec(o.encoding),p=Ac(o.channels,[]);_c(l)&&tn();let g=await gc.call(this,o.ice,d),m=!L?.[a];m&&(L[a]=new RTCPeerConnection(g),G[a]=Rc(true,ee(t.meta)?t.meta:{},u));let b=G[a];Te[a]=r,z[a]||(z[a]={}),kc.call(this,a);try{await vc.call(this,a,l);}catch(y){throw m&&Mi(a),y}if(!ke[a])return Mi(a),null;delete ke[a],b.receive=h||null;for(let y of p)Bi.call(this,a,y);return Vc.call(this,a),await vt(a,()=>rn.call(this,null,a)),c.send(JSON.stringify({action:"rtc",uid:a,content:{pickup:this.user.user_id},token:this.session.accessToken.jwtToken})),Lc.call(this,a)}}async function fp(t,e){if(!this?.session?.accessToken?.jwtToken)throw new f("Access token is required.",{code:"INVALID_PARAMETER"});this.log("sendIceCandidate to",e);let r=await this.__socket;if(!t.candidate){this.log("candidate-end","all ice candidates have been sent");return}let n=t.candidate;this.log("ice gathering state set to",L[e]?.iceGatheringState),r.send(JSON.stringify({action:"rtc",uid:e,content:{candidate:n},token:this.session.accessToken.jwtToken}));}function Vc(t){let e=Te[t]||(s=>{}),r=L[t],n=s=>{let o=G[t];return o&&s!==null&&s!==void 0?o.remoteSources[s]:void 0},i={ontrack:s=>{let o=s.transceiver?s.transceiver.mid:null;e({type:"track",target:r,timeStamp:s.timeStamp,streams:s.streams,track:s.track,source:n(o),mid:o});for(let a of ["mute","unmute","ended"])s.track.addEventListener(a,()=>{let c=Te[t];c&&c({type:"track"+a,target:r,timestamp:Re(),track:s.track,streams:s.streams,source:n(o),mid:o});});},onicecandidate:s=>{fp.bind(this)(s,t),s.candidate?e({type:"icecandidate",target:r,timestamp:Re(),candidate:s.candidate.candidate,sdpMid:s.candidate.sdpMid,sdpMLineIndex:s.candidate.sdpMLineIndex,usernameFragment:s.candidate.usernameFragment,protocol:s.candidate.protocol,gatheringState:r.iceGatheringState,connectionState:r.iceConnectionState}):e({type:"icecandidateend",target:r,timestamp:Re()});},onicecandidateerror:s=>{e({type:"icecandidateerror",target:r,timestamp:Re(),errorCode:s.errorCode,errorText:s.errorText,url:s.url,hostCandidate:s.hostCandidate,gatheringState:r.iceGatheringState,connectionState:r.iceConnectionState});},oniceconnectionstatechange:()=>{e({type:"iceconnectionstatechange",target:r,timestamp:Re(),state:r.iceConnectionState,gatheringState:r.iceGatheringState,signalingState:r.signalingState});},onicegatheringstatechange:()=>{e({type:"icegatheringstatechange",target:r,timestamp:Re(),state:r.iceGatheringState,connectionState:r.iceConnectionState,signalingState:r.signalingState});},onsignalingstatechange:()=>{e({type:"signalingstatechange",target:r,timestamp:Re(),state:r.signalingState,connectionState:r.iceConnectionState,gatheringState:r.iceGatheringState});},onconnectionstatechange:()=>{e({type:"connectionstatechange",target:r,timestamp:Re(),state:r.connectionState,iceState:r.iceConnectionState,signalingState:r.signalingState});let s=r.connectionState;(s==="disconnected"||s==="failed"||s==="closed")&&Ce.bind(this)({cid:t});}};for(let[s,o]of Object.entries(i))r[s]=o;}function Bc(t,e,r){let n=Te[t]||(o=>{}),i=r||e.label,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,label:e.label};this.log(`${e.label}: message`,o.data),n(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),n(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),n(a),z[t]&&z[t][i]===e&&(delete z[t][i],Object.keys(z[t]).length===0&&Ce.bind(this)({cid:t}));},onbufferedamountlow:o=>{let a={target:e,bufferedAmount:e.bufferedAmount,bufferedAmountLowThreshold:e.bufferedAmountLowThreshold,type:o.type,timeStamp:o.timeStamp,label:e.label};this.log(`${e.label}: bufferedamountlow`,e.bufferedAmount),n(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};n(a);}};for(let[o,a]of Object.entries(s))e[o]=a;}var kt=[],It=null;function Kc(t){return t&&Array.isArray(t.servers)&&t.servers.length?{servers:t.servers,expires:typeof t.expires=="number"?t.expires:null}:null}function jc(){if(!It)return null;let t=Math.floor(Date.now()/1e3);return (It.expires??It.at+3600)-60>t?{servers:It.servers,expires:It.expires}:null}async function ji(t=2500,e){let r=e||(this.__socket?await this.__socket:null);return !r||r.readyState!==1||!this?.session?.accessToken?.jwtToken?null:new Promise(n=>{let i=false,s=setTimeout(()=>{i||(i=true,kt=kt.filter(a=>a!==o),n(null));},t),o=a=>{i||(i=true,clearTimeout(s),n(Kc(a)));};kt.push(o);try{r.send(JSON.stringify({action:"ice",token:this.session.accessToken.jwtToken}));}catch{o(null);}})}var $e;function $c(){return $e}var Ye=null,nr=true,Pt=0;async function hp(){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 t=await this.record_endpoint;return new WebSocket(t.websocket_private+"?token="+this.session.accessToken.jwtToken)}var Ki=null;async function sn(){if(typeof window>"u"||window._runningInNodeJS)throw new f("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});nr=true;let t=this.__socket?await this.__socket:this.__socket;Ce.bind(this)({close_all:true}),$e&&xt.bind(this)({group:null}),Pt=0,Ye&&(Ye.terminate(),Ye=null);try{t&&t.close();}catch{}return window.removeEventListener("visibilitychange",Ki),this.__socket=null,null}async function Ct(t,e=50,r){if(typeof window>"u"||window._runningInNodeJS)throw new f("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(typeof t!="function")throw new f("Callback must be a function.",{code:"INVALID_REQUEST"});if(r==="reconnect"){if(this.__socket instanceof Promise){let i=await this.__socket;if(i.readyState!==WebSocket.CLOSED&&i.readyState!==WebSocket.CLOSING)return this.__socket}}else if(nr&&(Ki=()=>{!document.hidden&&!nr&&Ct.bind(this)(t,0,"reconnect");},this.__socket instanceof Promise))return this.__socket;Ye&&(Ye.terminate(),Ye=null);let n={value:null};return this.__socket=new Promise(async(i,s)=>{let o=a=>{this.__socket===n.value&&(this.__socket=null),s(a);};try{await At.bind(this)();}catch(a){o(a);return}setTimeout(async()=>{try{let a=await hp.bind(this)();a.onopen=()=>{nr=!1,Pt=0,r!=="reconnect"&&window.addEventListener("visibilitychange",Ki),this.log("realtime onopen","Connected to WebSocket server."),t({type:"success",message:"Connected to WebSocket server."}),$e&&a.send(JSON.stringify({action:"joinRoom",rid:$e,token:this.session.accessToken.jwtToken})),ji.bind(this)(5e3,a).catch(()=>null);let c=`
|
|
208
208
|
let interval = 15000; // Set interval time 15 seconds
|
|
209
209
|
|
|
210
210
|
function runInterval() {
|
|
@@ -213,19 +213,19 @@ var wc=Object.create;var et=Object.defineProperty;var ji=Object.getOwnPropertyDe
|
|
|
213
213
|
}
|
|
214
214
|
|
|
215
215
|
runInterval(); // Start interval
|
|
216
|
-
`,c=new Blob([l],{type:"application/javascript"});Ge=new Worker(URL.createObjectURL(c)),Ge.onmessage=d=>{a.readyState===1&&a.send(JSON.stringify({action:"keepAlive"}));},i(a);},a.onmessage=async l=>{let c="";try{c=JSON.parse(decodeURI(l.data)),this.log("socket onmessage",c);}catch{return}let d;switch(!0){case !!c?.["#message"]:d="message";break;case !!c?.["#private"]:d="private";break;case !!c?.["#notice"]:d="notice";break;case !!c?.["#rtc"]:d="rtc";break;case !!c?.["#error"]:d="error";break;case !!c?.["#ice"]:d="ice";break}if(!d){if(c?.requestId&&c?.connectionId&&St.length){let u=St.splice(0);for(let g of u)g(null);}return}if(d==="ice"){let u=al(c["#ice"]);u&&(At={...u,at:Math.floor(Date.now()/1e3)});let g=St.splice(0);for(let p of g)p(c["#ice"]);return}let h={type:d,message:c?.["#rtc"]||c?.["#message"]||c?.["#private"]||c?.["#notice"]||c?.["#error"]||null,sender:c?.["#user_id"]||null,sender_cid:c?.["#scid"]?"cid:"+c["#scid"]:null,sender_rid:c?.["#srid"]||null,code:c?.["#code"]||null};if(d==="notice")t(h);else if(d==="rtc"){if(h.sender!==this.user.user_id){let u=h.message;if(u.hungup){Re[h.sender_cid]&&(Re[h.sender_cid](!1),delete Re[h.sender_cid]),Ue[h.sender_cid]&&delete Ue[h.sender_cid],F?.[h.sender_cid]&&Se.bind(this)({cid:h.sender_cid}),h.type="rtc:closed",t(h);return}if(u.candidate&&zr.bind(this)(u.candidate,h.sender_cid),u.sdpoffer&&(xi.bind(this)(u.sdpoffer,h.sender_cid),Ue[h.sender_cid]||(Ue[h.sender_cid]=h.sender_cid,delete h.message,h.connectRTC=nl.bind(this)(h),h.type="rtc:incoming",h.hangup=(()=>{F[h.sender_cid]?Se.bind(this)({cid:h.sender_cid}):Ue[h.sender_cid]&&(delete Ue[h.sender_cid],a.send(JSON.stringify({action:"rtc",uid:h.sender_cid,content:{hungup:this.user.user_id},token:this.session.accessToken.jwtToken})));}).bind(this),t(h))),u.pickup&&Re[h.sender_cid]&&(Re[h.sender_cid](!0),delete Re[h.sender_cid]),u.sdpanswer&&F[h.sender_cid])if(F[h.sender_cid].signalingState==="have-local-offer")await F[h.sender_cid].setRemoteDescription(new RTCSessionDescription(u.sdpanswer)),await zr.bind(this)(null,h.sender_cid);else throw new f("Invalid signaling state.",{code:"INVALID_REQUEST"})}}else t(h);},a.onclose=()=>{Yt?(this.log("realtime onclose","WebSocket connection closed."),t({type:"close",message:"WebSocket connection closed."})):(this.log("realtime onclose","WebSocket unexpected close."),t({type:"error",message:"Skapi: WebSocket unexpected close."}),Rt++,Rt<3?(this.log("realtime onclose","Reconnecting to WebSocket server..."+Rt),t({type:"reconnect",message:"Reconnecting to WebSocket server..."+Rt}),Tt.bind(this)(t,3e3,"reconnect")):(this.log("realtime onclose","Max reconnection attempts reached."),t({type:"error",message:"Skapi: Max reconnection attempts reached."})));},a.onerror=()=>{this.log("realtime onerror","WebSocket connection error."),t({type:"error",message:"Skapi: WebSocket connection error."});};}catch(a){o(a);}},e);}),n.value=this.__socket,this.__socket}async function cl(t,e,r){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 bt.bind(this)(),t=K(t).data;let i="";if(r&&(r=_.Params(r,{config:{always:"boolean"},title:"string",body:"string"},["title","body"]),i=JSON.stringify({title:r.title,body:r.body}),new Blob([i]).size>3072))throw new f("Notification size exceeds 3kb.",{code:"INVALID_PARAMETER"});if(n.readyState===1){try{_.UserId(e),n.send(JSON.stringify({action:"sendMessage",uid:e,content:t,notification:i,notificationConfig:r?.config||{},token:`IdT:${this.service}:${this.owner}:`+(this.bearerToken||this.session?.idToken?.jwtToken||"null")}));}catch(s){if(this.log("postRealtime:err",{err:s}),Ve!==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:t,notification:i,notificationConfig:r?.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 vt(t){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 bt.bind(this)(),t=K(t,{nullIfEmpty:true}).data;let{group:r=null}=t;if(!r&&!Ve)return {type:"success",message:"Left realtime message group."};if(r!==null&&typeof r!="string")throw new f('"group" must be a string | null.',{code:"INVALID_PARAMETER"});return e.readyState===1&&e.send(JSON.stringify({action:"joinRoom",rid:r,token:this.session.accessToken.jwtToken})),Ve=r,{type:"success",message:r?`Joined realtime message group: "${r}".`:"Left realtime message group."}}async function ul(t,e){t=_.Params(t,{user_id:n=>_.UserId(n,'User ID in "user_id"'),group:["string",()=>{if(!Ve)throw new f('No group has been joined. Otherwise "group" is required.',{code:"INVALID_REQUEST"});return Ve}]});let r=await k.bind(this)("get-ws-group",t,{fetchOptions:e,auth:true,method:"post"});return r.list=r.list.map(n=>({user_id:n.uid.split("#")[1],cid:"cid:"+n.cid})),r}async function dl(t,e){if(await this.__connection,t||(t={searchFor:"group",value:" ",condition:">"}),t=_.Params(t,{searchFor:["group","number_of_users",()=>"group"],value:["string","number",()=>t?.searchFor&&t?.searchFor==="number_of_users"?0:" "],condition:[">",">=","=","<","<=","!=","gt","gte","eq","lt","lte","ne"],range:["string","number"]}),t.condition||(t.value===" "||!t.value?t.condition=">":t.condition="="),t.range&&t.condition&&delete t.condition,t.searchFor==="number_of_users"&&typeof t.value!="number")throw new f('"value" must be a number.',{code:"INVALID_PARAMETER"});if(t.searchFor==="group"&&typeof t.value!="string")throw new f('"value" must be a string.',{code:"INVALID_PARAMETER"});if(t.hasOwnProperty("range")&&typeof t.range!=typeof t.value)throw new f(`"range" must be a ${typeof t.value}.`,{code:"INVALID_PARAMETER"});let r=await k.bind(this)("get-ws-group",t,{fetchOptions:e,auth:true,method:"post"});return r.list=r.list.map(n=>({group:n.rid.split("#")[1],number_of_users:n.cnt})),r}var Ph=typeof FormData<"u",hl=typeof HTMLFormElement<"u",pl=typeof SubmitEvent<"u",Ce={},Qt={},de={};function Xt(t){return Object.freeze({id:t,status:"stopped"})}function Ni(t){return !!t&&typeof t=="object"&&t.status==="stopped"}var gl=3;function ml(t,e,r){let n=false,i=Array.isArray(t?.chunks)?t.chunks.slice():[];i.sort((s,o)=>(s?.seq||0)-(o?.seq||0));for(let s of i)if(!(!s||typeof s.seq!="number"||s.seq<=e.seq)&&(e.seq=s.seq,n=true,r&&typeof s.txt=="string"&&s.txt!==""))try{r(s.txt,s.seq,"poll");}catch(o){console.error(o);}return typeof t?.last_seq=="number"&&t.last_seq>e.seq&&(e.seq=t.last_seq,n=true),n}var kh=2e3,yl=5e3,xh=2e3,Uh=5,Ch=1500,Yr=null;function bl(t,e,r){let n=new Map,i=false,s=false,o=0,a={socket:0,poll:0},l=(u,g,p)=>{if(t.seq=u,!(!e||typeof g!="string"||g===""))try{e(g,u,p);}catch(m){console.error(m);}},c=()=>{for(let u of Array.from(n.keys()))u<=t.seq&&n.delete(u);for(;;){let u=t.seq+1;if(!n.has(u))break;let g=n.get(u);n.delete(u),l(u,g.txt,g.via);}};return {cursor:t,open:()=>{i||s||(i=true,c());},fromPoll:u=>{if(s)return false;let g=t.seq,p=t.seq,m=Array.isArray(u?.chunks)?u.chunks:[];for(let y of m){if(!y||typeof y.seq!="number"||y.seq<=t.seq)continue;let A=!n.has(y.seq);A&&(a.poll++,r&&a.poll===1&&r("poll",y.seq)),n.set(y.seq,{txt:typeof y.txt=="string"?y.txt:"",via:A?"poll":n.get(y.seq).via}),y.seq>p&&(p=y.seq);}typeof u?.last_seq=="number"&&u.last_seq>p&&(p=u.last_seq);let b=Array.from(n.keys()).sort((y,A)=>y-A);for(let y of b){if(y<=t.seq){n.delete(y);continue}if(y>p)break;let A=n.get(y);n.delete(y),l(y,A.txt,A.via);}return p>t.seq&&(t.seq=p),c(),t.seq>g},fromSocket:(u,g)=>{s||typeof u!="number"||!Number.isFinite(u)||(o=Date.now(),!(u<=t.seq)&&(!n.has(u)&&n.size>=xh||(n.has(u)||(a.socket++,r&&a.socket===1&&r("socket",u)),n.set(u,{txt:typeof g=="string"?g:"",via:n.has(u)?n.get(u).via:"socket"}),i&&c())));},warm:()=>o!==0&&Date.now()-o<kh,stats:()=>({socket:a.socket,poll:a.poll}),close:()=>{s=true,n.clear();}}}function _l(t){if(!this||!this.__network_logs)return {onTransport:void 0,done:()=>{}};let e=Date.now(),r=false;return {onTransport:(n,i)=>{console.log(`%cSKAPI: stream chunk arrived over ${n==="socket"?"WEBSOCKET":"POLL"}`,`color: ${n==="socket"?"green":"orange"};`,{id:t,first_seq:i,after_ms:Date.now()-e});},done:n=>{if(r||!n)return;r=true;let i=n.stats();console.log("%cSKAPI: stream transport","color: blue;",{id:t,over_websocket:i.socket,over_poll:i.poll,took_ms:Date.now()-e});}}}function wl(t,e){let r={stop:()=>{}};if(typeof window>"u"||window._runningInNodeJS||Yr)return r;let n={stopped:false,socket:null,opened:null,joined:false,attempts:0,unavailable:false};Yr=n;let i=c=>{if(n.stopped)return;let d=c?.data;if(typeof d!="string")return;let h=null;try{h=JSON.parse(d);}catch{try{h=JSON.parse(decodeURI(d));}catch{return}}let u=h?.["#message"];if(u==null)return;if(typeof u=="string")try{u=JSON.parse(u);}catch{return}if(typeof u!="object")return;let g=h?.["#srid"];if(typeof g=="string"&&g!==t)return;let p=u.seq;typeof p=="string"&&p!==""&&(p=Number(p)),e.fromSocket(p,u.txt);},s=()=>{if(n.socket){try{n.socket.removeEventListener("message",i);}catch{}try{n.socket.removeEventListener("close",a);}catch{}n.socket=null;}},o=async()=>{let c=n.opened,d=n.joined;if(n.opened=null,n.joined=false,s(),!(!d&&!c))try{let h=this.__socket?await this.__socket:null;if(c&&h===c){await Jr.bind(this)();return}d&&h&&ll()===room&&await vt.bind(this)({group:null});}catch{}},a=()=>{n.stopped||(s(),!n.unavailable&&(n.attempts>=Uh||(n.attempts+=1,setTimeout(()=>{n.stopped||l();},Ch))));},l=async()=>{try{let c=this.__socket?await this.__socket:null;if(n.stopped){o();return}if(!c){if(!this.session){n.unavailable=!0,o();return}if(await Tt.bind(this)(()=>{},0),c=this.__socket?await this.__socket:null,n.stopped){o();return}c&&!n.opened&&(n.opened=c);}if(!c||c.readyState!==1)return;if(c.addEventListener("message",i),c.addEventListener("close",a),n.socket=c,!n.joined&&(await vt.bind(this)({group:t}),n.joined=!0,n.stopped)){o();return}}catch{}};return l(),{stop:()=>{n.stopped||(n.stopped=true,Yr===n&&(Yr=null),o());}}}function El(t){return t?.status==="running"||t?.status==="pending"}function Al(t){return !!t&&typeof t=="object"&&!Array.isArray(t)&&typeof t.status=="string"&&typeof t.id=="string"&&"in_queue"in t}function Rl(t,e,r,n){if(!t||typeof t!="string")throw new f('"requestId" should be type: <string>.',{code:"INVALID_PARAMETER"});if(t.includes("#"))return t;if(!e||typeof e!="string"||!r||typeof r!="string")throw new f('"url" and "method" are required to address a request by its short id.',{code:"INVALID_PARAMETER"});return _.Url(e),`[${r.toUpperCase()}]${e.toLowerCase()}#${n}:${t}`}function Sl({id:t,auth:e,service:r,owner:n,latency:i=1e3,queue:s,seedExecuted:o,onResponse:a,onError:l,onStream:c,realtimeGroup:d}){if(typeof i!="number")throw new f('"latency" should be a number.',{code:"INVALID_PARAMETER"});if(i<0)throw new f('"latency" should be a non-negative number.',{code:"INVALID_PARAMETER"});s&&!Ce?.[s]&&(Ce[s]=new $t({breakWhenError:false,batchSize:1}));let h={stop:null,aborted:false,queue:s};de[t]=h;let u=null,g=()=>{de[t]===h&&delete de[t];},p=()=>new Promise((b,y)=>{let A=false;if(h.aborted){g(),b(Xt(t));return}let w={seq:0},S=_l.call(this,t),R=c&&d?bl(w,c,S.onTransport):null,U=R?wl.call(this,d,R):null,O=()=>{S.done(R),U&&U.stop(),R&&R.close();};u=O;let C=0,I=false,D=0,N=typeof o=="number"&&o>0?o:void 0,M=async()=>{if(!(A||I)&&!(R&&R.warm()&&Date.now()-C<yl)){I=true;try{for(;;){let ie={id:t,service:r,owner:n};c&&(ie.since=w.seq),C=Date.now();let q=await k.bind(this)("csr-poll",ie,{auth:e});if(A)return;let X=R?R.fromPoll(q):c?ml(q,w,c):!1;R&&R.open();let tr=El(q);if(typeof q?.executed=="number"&&q.executed>0&&(N=q.executed),q?.more&&X){D=0;continue}if(tr){D=0;return}if(D=q?.more?D+1:0,q?.more&&D<gl)return;A=!0,a&&a(q,N!==void 0?{executed:N}:void 0),clearInterval(te),O(),g(),b(q);return}}catch(ie){if(A)return;A=true,l&&l(ie),clearInterval(te),O(),g(),y(ie);}finally{I=false;}}},te=setInterval(M,i);R&&M(),h.stop=()=>{A||(A=true,clearInterval(te),O(),g(),b(Xt(t)));};}),m=()=>{let b=de[t];b&&(b.stop?b.stop():(b.aborted=true,delete de[t]));};if(s){let b=new Promise((y,A)=>{let w=false,S=Ce[s].add([async()=>{try{let R=await p();return w||(w=!0,y(R)),R}catch(R){throw w||(w=true,A(R)),R}}])[0];Qt[t]=S,h.stop=()=>{if(!w){h.aborted=true,u&&u();try{Ce[s]&&Ce[s].remove(Qt[t]);}catch{}delete Qt[t],g(),w=true,y(Xt(t));}};});return Object.assign(b,{stop:m})}else return Object.assign(p(),{stop:m})}function Xr(t){let e=0,r=[];if(t?.id){if(t.url&&t.method){let n=t.service||this.service;r.push(`[${t.method.toUpperCase()}]${t.url.toLowerCase()}#${n}:${t.id}`);}r.push(t.id);}else if(t?.queue)for(let n in de)de[n]?.queue===t.queue&&r.push(n);else for(let n in de)r.push(n);for(let n of r){let i=de[n];i&&(i.stop?i.stop():(i.aborted=true,delete de[n]),e+=1);}return e}function Oi(t,e){if(!t.queue)throw new f('"queue" is required.',{code:"INVALID_PARAMETER"});let r=()=>k.bind(this)("csr-poll",{service:t.service||this.service,owner:t.owner||this.owner,queue:t.queue+":"},{auth:true});return this.__projectIdInput?this.__projectIdInput.then(r):r()}function Dh(t){if(typeof Buffer<"u"&&typeof Buffer.from=="function")return Buffer.from(t).toString("base64");if(typeof btoa=="function"){let e="";for(let n=0;n<t.length;n+=32768)e+=String.fromCharCode.apply(null,Array.from(t.subarray(n,n+32768)));return btoa(e)}throw new f("No base64 encoder available in this environment.",{code:"NOT_SUPPORTED"})}var fl=2*1024*1024-64*1024;function Qr(t){return typeof File<"u"&&t instanceof File||typeof Blob<"u"&&t instanceof Blob}function Di(t){if(Array.isArray(t)){let e=[];for(let r of t)Qr(r)||e.push(Di(r));return e}if(t&&typeof t=="object"&&!Qr(t)){let e=Object.getPrototypeOf(t);if(e!==Object.prototype&&e!==null)return t;let r={};for(let n in t)Qr(t[n])||(r[n]=Di(t[n]));return r}return t}function Nh(t){if(t==null)return null;let e=K(t)?.data;return !e||typeof e!="object"||Array.isArray(e)?null:Di(e)}function Tl(t,e,r){if(r!==void 0){if(Array.isArray(r)){for(let n of r)Tl(t,e,n);return}if(Qr(r)){t.append(e,r);return}if(r===null){t.append(e,"");return}if(typeof r=="object"){t.append(e,JSON.stringify(r));return}t.append(e,String(r));}}async function Oh(t){if(t==null)throw new f('"multipart": true needs a form body in the first argument.',{code:"INVALID_PARAMETER"});if(typeof FormData>"u"||typeof Response>"u")throw new f('"multipart": true is not available in this environment.',{code:"NOT_SUPPORTED"});let e;if(pl&&t instanceof SubmitEvent)e=new FormData(t.target);else if(hl&&t instanceof HTMLFormElement)e=new FormData(t);else if(t instanceof FormData)e=t;else if(typeof t=="object"&&!Array.isArray(t)){e=new FormData;for(let s in t)Tl(e,s,t[s]);}else throw new f('"form" should be a submit event, a form element, FormData, or an object.',{code:"INVALID_PARAMETER"});let r=new Response(e),n=r.headers.get("content-type"),i=Dh(new Uint8Array(await r.arrayBuffer()));if(i.length>fl)throw new f(`Multipart body is too large: ${i.length} bytes once base64 encoded, and the limit is ${fl}. Upload the file first and send its url instead.`,{code:"INVALID_PARAMETER"});return {body_b64:i,body_content_type:n}}function Fh(t){if(t!=null){if(typeof t=="boolean")return t;if(typeof t=="object"&&!Array.isArray(t))return {user:!!t.user,service:!!t.service};throw new f('"skapiHeaders" should be type: <boolean> or { user?: boolean; service?: boolean }.',{code:"INVALID_PARAMETER"})}}function Lh(t){if(!(!t||typeof t!="object")){for(let e in t)if(typeof e=="string"&&e.toLowerCase().indexOf("x-skapi-")===0)throw new f(`"headers" cannot set "${e}": the "x-skapi-" prefix is reserved. Use "skapiHeaders" to tell the destination who the caller is.`,{code:"INVALID_PARAMETER"})}}async function vl(t,e){let r=false,n=!!(t?.secretName||t?.clientSecretName),i=e?.signal;if(i?.aborted)throw new f('"signal" was already aborted.',{code:"INVALID_REQUEST"});if(typeof t.poll=="number"&&t.poll<0)throw new f('"poll" should be a non-negative number.',{code:"INVALID_PARAMETER"});let s=t?.onResponse,o=t?.onError,a=t?.onStream,l=typeof t.poll=="number"?t.poll:t.poll?1e3:0;delete t.poll,(l||t.stream)&&!t.queue&&(t.queue=(this.__user?.user_id||"anonymous")+"-"+Ye());let c=(u,g=new WeakSet)=>{if(!(r||!u||typeof u!="object"||g.has(u))){g.add(u);for(let p in u){let m=u[p];if(typeof m=="string"){if(m.includes("$CLIENT_SECRET")){r=true;return}}else m&&typeof m=="object"&&c(m,g);}}};if(t=_.Params(t,{url:u=>{if(!u||typeof u!="string")throw new f('"url" should be type: <string>.',{code:"INVALID_PARAMETER"});return _.Url(u),u.includes("$CLIENT_SECRET")&&(r=true),u},secretName:"string",clientSecretName:"string",method:u=>{if(u&&typeof u!="string")throw new f('"method" should be one of "GET", "POST", "PUT", "PATCH", "DELETE" or "HEAD".',{code:"INVALID_PARAMETER"});let g=u.toLowerCase();if(g!=="get"&&g!=="post"&&g!=="delete"&&g!=="put"&&g!=="patch"&&g!=="head")throw new f('"method" should be one of "GET", "POST", "PUT", "PATCH", "DELETE" or "HEAD".',{code:"INVALID_PARAMETER"});return g},stream:u=>{if(u!=null&&typeof u!="boolean")throw new f('"stream" should be type: <boolean>.',{code:"INVALID_PARAMETER"});return !!u},realtime:u=>{if(u!=null&&typeof u!="boolean")throw new f('"realtime" should be type: <boolean>.',{code:"INVALID_PARAMETER"});return !!u},headers:u=>{if(u&&typeof u!="object")throw new f('"headers" should be type: <object>.',{code:"INVALID_PARAMETER"});return Lh(u),c(u),u},skapiHeaders:u=>Fh(u),data:u=>{if(u&&typeof u!="object")throw new f('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return c(u),u},params:u=>{if(u&&typeof u!="object")throw new f('"params" should be type: <object>.',{code:"INVALID_PARAMETER"});return c(u),u},body_b64:"string",body_content_type:"string",expires:"number",queue:"string"},e?.requireSecretName?["clientSecretName","method","url"]:["method","url"]),t.realtime&&!t.stream)throw new f('"realtime" requires "stream": true.',{code:"INVALID_PARAMETER"});if(t.body_b64&&t.data)throw new f('"data" cannot be sent with "multipart": true.',{code:"INVALID_PARAMETER"});n&&!r&&(delete t.secretName,delete t.clientSecretName),await this.__connection;let d=!!this.__user,h=()=>k.bind(this)("csr",t,{auth:d,tokenHeaders:{accessToken:!!d}}).then(u=>{if(u.status==="running"||u.status==="pending"){let g=`[${t.method.toUpperCase()}]${t.url.toLowerCase()}`,p=t.service||this.service,m=t.owner||this.owner,b=`${g}#${p}:${u.id}`;if(i){let y=()=>{Xr.call(this,{id:b});};i.aborted?y():i.addEventListener("abort",y,{once:true});}Object.assign(u,{poll:y=>Sl.call(this,{id:b,auth:d,service:p,owner:m,latency:y?.latency||1e3,queue:t?.queue,onResponse:s,onError:o,onStream:y?.onStream||a,realtimeGroup:u?.realtime_group})});}return s?s(u):u}).catch(u=>{if(o)return o(u);throw u});if(t?.queue){let u="base:"+t.queue;return Ce?.[u]||(Ce[u]=new $t({breakWhenError:false,batchSize:1})),new Promise((g,p)=>{Ce[u].add([async()=>{try{let m=await h();if(l>0){let b=m.poll({latency:l});return i&&(i.aborted?b.stop():i.addEventListener("abort",()=>b.stop(),{once:!0})),g(b),b}return g(m),m}catch(m){throw p(m),m}}]);})}else return h()}async function Il(t,e){if(!e||typeof e!="object")throw new f('"options" is required in the second argument.',{code:"INVALID_PARAMETER"});if(e.apiKeyHeader!==void 0||e.apiKeyScheme!==void 0)throw new f('"apiKeyHeader" and "apiKeyScheme" are no longer supported. Store the key as a client secret, name it with "secretName", and put "$CLIENT_SECRET" where the key goes.',{code:"INVALID_PARAMETER"});if(e.multipart!==void 0&&e.multipart!==null&&typeof e.multipart!="boolean")throw new f('"multipart" should be type: <boolean>.',{code:"INVALID_PARAMETER"});let r=e.responseType;if(r!=null){if(r==="response")throw new f(`"responseType": "response" is not available here. The request is relayed from the server and what comes back is the stored answer, not a live Response; the destination's status code is the "status_code" of the row forwardRequestHistory lists.`,{code:"INVALID_PARAMETER"});if(r!=="json"&&r!=="text")throw new f('"responseType" should be either "json" or "text".',{code:"INVALID_PARAMETER"})}let n=e.method||"POST",i=typeof n=="string"?n.toLowerCase():"",s=i==="get"||i==="delete"||i==="head"?"params":"data",o={url:e.url,method:n};if(e.secretName!==void 0&&(o.secretName=e.secretName),e.headers!==void 0&&(o.headers=e.headers),e.data!==void 0&&(o.data=e.data),e.params!==void 0&&(o.params=e.params),e.skapiHeaders!==void 0&&(o.skapiHeaders=e.skapiHeaders),e.service!==void 0&&(o.service=e.service),e.owner!==void 0&&(o.owner=e.owner),e.queue!==void 0&&(o.queue=e.queue),e.expires!==void 0&&(o.expires=e.expires),e.stream!==void 0&&(o.stream=e.stream),e.realtime!==void 0&&(o.realtime=e.realtime),e.poll!==void 0&&(o.poll=e.poll),e.onStream!==void 0&&(o.onStream=e.onStream),e.onResponse!==void 0&&(o.onResponse=e.onResponse),e.onError!==void 0&&(o.onError=e.onError),e.multipart){if(e.data!==void 0&&e.data!==null)throw new f('"data" cannot be sent with "multipart": true. The form itself is the body.',{code:"INVALID_PARAMETER"});let l=await Oh(t);o.body_b64=l.body_b64,o.body_content_type=l.body_content_type;}else {let l=Nh(t);l&&Object.keys(l).length&&(o[s]=Object.assign({},l,o[s]||{}));}let a=vl.call(this,o,{signal:e.signal});return r?a.then(l=>{if(Al(l)||Ni(l))return l;if(r==="text")return typeof l=="string"?l:JSON.stringify(l);if(typeof l=="string")try{return JSON.parse(l)}catch{return l}return l}):a}async function Pl(t){return vl.call(this,t,{requireSecretName:true})}async function Fi(t,e){await this.__connection;let r=t.service||this.service,n=t.owner||this.owner;t=_.Params(t,{url:"string",method:["GET","POST","PUT","PATCH","DELETE","HEAD"],queue:"string",status:["pending","running","resolved","failed"],compact:"boolean",queue_exact:"boolean",queue_exclude:"string"},["url","method"]);let i=!!this.__user,s=`[${t.method.toUpperCase()}]${t.url.toLowerCase()}#${r}:`,o={id:s,queue:t?.queue,status:t?.status,service:r,owner:n};t?.compact&&(o.compact=true),t?.queue_exact&&(o.queue_exact=true),t?.queue_exclude&&(o.queue_exclude=t.queue_exclude),Object.keys(o).forEach(l=>{o[l]||delete o[l];}),o.queue&&(o.id_prefix=o.id,delete o.id);let a=await k.bind(this)("csr-poll",o,{auth:i,fetchOptions:e});return a.list=a.list.map(l=>{let c={id:l.id,status_code:l.rslv?.status_code||null,response_body:l.rslv?.body||l.rslv?.truncated||null,error:l?.err,created:l?.stmp,updated:l?.utmp,executed:typeof l?.att=="number"?l.att*1e3:void 0,responded:typeof l?.rtmp=="number"?l.rtmp:void 0,request_body:l?.reqbdy,expires:l?.expt,status:l.stts,queue_name:l?.qid,request_text:l?.reqtxt,response_text:l?.rslvtxt,response_complete_marker:l?.rslvmk!=null?!!l.rslvmk:void 0,compact:l?.cmpct?true:void 0};for(let d in c)c[d]===void 0&&delete c[d];return (c.status==="running"||c.status==="pending")&&(c.poll=d=>Sl.call(this,{id:s+c.id,auth:i,service:r,owner:n,latency:d?.latency||1e3,queue:l?.qid,seedExecuted:c.executed,onResponse:d?.onResponse,onError:d?.onError,onStream:d?.onStream})),c}),a}async function Li(t){await this.__connection,t=_.Params(t,{url:"string",method:["GET","POST","PUT","PATCH","DELETE","HEAD"],id:"string",queue:"string"},["url","method","id"]);let e=t?.service||this.service,r=t?.owner||this.owner,n=!!this.__user,i=`[${t.method.toUpperCase()}]${t.url.toLowerCase()}#${e}`,s=t.id,o=`${i}:${s}`,a=t?.queue;return a&&Ce?.[a]&&(Ce[a].remove(Qt[o]),delete Qt[o]),k.bind(this)("csr-cancel",{id:o,service:e,owner:r},{auth:n})}function Mi(t,e){let r=typeof e?.poll=="number"?e.poll:1e3;if(!Number.isFinite(r)||r<0)throw new f('"poll" should be a non-negative number.',{code:"INVALID_PARAMETER"});if(!t||typeof t!="string")throw new f('"requestId" should be type: <string>.',{code:"INVALID_PARAMETER"});if(e?.since!==void 0&&typeof e.since!="number")throw new f('"since" should be a number.',{code:"INVALID_PARAMETER"});if(e?.realtimeGroup!==void 0&&e.realtimeGroup!==null&&typeof e.realtimeGroup!="string")throw new f('"realtimeGroup" should be type: <string>.',{code:"INVALID_PARAMETER"});let n=typeof e?.since=="number"&&e.since>0?e.since:0,i=e?.onStream,s=e?.onResponse,o=e?.onError,a={stopped:false,fullId:t,resolve:null},l=null,c={stop:null,aborted:false},d=()=>{de[a.fullId]===c&&delete de[a.fullId];},h=()=>{a.stopped||(a.stopped=true,l&&l(),d(),a.resolve&&a.resolve(Xt(a.fullId)));};c.stop=h;let u=new Promise(async(g,p)=>{a.resolve=g;try{await this.__connection;let m=!!this.__user,b=e?.service||this.service,y=e?.owner||this.owner;if(a.fullId=Rl(t,e?.url,e?.method,b),a.stopped){g(Xt(a.fullId));return}de[a.fullId]=c;let A={seq:n},w=0,S=_l.call(this,a.fullId),R=i&&e?.realtimeGroup?bl(A,i,S.onTransport):null,U=R?wl.call(this,e.realtimeGroup,R):null,O=()=>{S.done(R),U&&U.stop(),R&&R.close();};for(l=O;;){let C=await k.bind(this)("csr-poll",{id:a.fullId,service:b,owner:y,since:A.seq},{auth:m});if(a.stopped)return;if(!Al(C)){O(),d(),s&&s(C),g(C);return}let I=R?R.fromPoll(C):ml(C,A,i);R&&R.open();let D=El(C);if(C.more&&I){w=0;continue}if(w=C.more?w+1:0,!D&&(!C.more||w>=gl)){O(),d(),s&&s(C),g(C);return}if(await new Promise(N=>setTimeout(N,R&&R.warm()?Math.max(r,yl):r)),a.stopped)return}}catch(m){if(a.stopped)return;l&&l(),d(),o&&o(m),p(m);}});return Object.assign(u,{stop:h})}async function qi(t,e,r){await this.__connection;let n=r?.service||this.service,i=r?.owner||this.owner,s=!!this.__user,o=Rl(t,r?.url,r?.method,n);return k.bind(this)("csr-finalize",{id:o,data:e,service:n,owner:i},{auth:s})}var kl=Mi,xl=qi,Ul=Fi,Cl=Li,Dl=Xr,Nl=Oi;async function Ol(t){await this.__connection;let e={name:"string",email:r=>(_.Email(r),r),subject:"string",message:"string"};return t=_.Params(t,e,["name","email","subject","message"]),await k.bind(this)("send-inquiry",t),"SUCCESS: Inquiry has been sent."}async function Fl(t,e){if(await this.__connection,Ph&&t instanceof FormData||hl&&t instanceof HTMLFormElement||pl&&t instanceof SubmitEvent){if(!e)throw new f("Url string as a second argument is required when form is passed.",{code:"INVALID_PARAMETER"});let n=K(t);t={url:e,data:n.data,sync:true};}let r={url:n=>_.Url(n),data:n=>n,sync:["boolean",()=>true]};if(Array.isArray(t))for(let n of t)n=_.Params(n,r);else t=_.Params(t,r);return k.bind(this)("post-secure",t,{auth:true})}async function Ll(t,e){await this.__connection;let{auth:r=false,method:n="POST",bypassAwaitConnection:i=false,responseType:s,contentType:o,tokenHeaders:a,progress:l}=e||{};if(e=Object.assign({auth:r,method:n,bypassAwaitConnection:i,responseType:s,contentType:o,tokenHeaders:a},{fetchOptions:{progress:l}}),typeof t!="object"&&(o==="application/json"||o===void 0))throw new f('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return k.bind(this)("mock",t,e)}async function Ml(t,e){await this.__connection,t=_.Params(t||{},{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 r=await k.bind(this)("get-feed",t,{auth:true,fetchOptions:e});return Array.isArray(r?.list)&&(r.list=await Promise.all(r.list.map(n=>Ze.bind(this)(n)))),r}function Zt(t){if(t===this.__user.user_id)throw new f(`"user_id" cannot be the user's own ID.`,{code:"INVALID_PARAMETER"});return _.UserId(t,'"user_id"')}async function ql(t,e){if(t=K(t,{ignoreEmpty:true}).data,t=_.Params(t,{subscriber:n=>_.UserId(n,'User ID in "subscriber"'),subscription:Zt.bind(this),blocked:"boolean"}),!t.subscriber&&!t.subscription)throw new f('At least either "subscriber" or "subscription" should have a value.',{code:"INVALID_PARAMETER"});let r=await k.bind(this)("get-subscription",t,Object.assign({auth:true},{fetchOptions:e}));return r.list=r.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})),r}async function Vl(t){await this.__connection,t=_.Params(t,{user_id:Zt.bind(this),get_feed:"boolean",get_notified:"boolean",get_email:i=>{if(i&&(!this.__user.email||!this.__user.email_verified))throw new f("User has no verified email address.",{code:"INVALID_REQUEST"});return !!i}},["user_id"]);let e={};for(let i of ["get_feed","get_notified","get_email"])typeof t[i]=="boolean"&&(e[i]=t[i]);let r=await k.bind(this)("subscription",{subscribe:t.user_id,option:e},{auth:true}),n={};if(r.sub){let i=r.sub.split("#");n.subscriber=i[2],n.subscription=i[0];}else n.subscriber=r.subscriber,n.subscription=r.subscription;return n.timestamp=r?.timestamp||r.stmp,n.blocked=r?.blocked||r.grp.substring(0,1)==="N",Object.assign(n,r.opt),n}async function Bl(t){await this.__connection;let{user_id:e}=_.Params(t,{user_id:Zt.bind(this)},["user_id"]);return await k.bind(this)("subscription",{unsubscribe:e},{auth:true})}async function jl(t){await this.__connection;let{user_id:e}=_.Params(t,{user_id:Zt.bind(this)},["user_id"]);return await k.bind(this)("subscription",{block:e},{auth:true})}async function Kl(t){await this.__connection;let{user_id:e}=_.Params(t,{user_id:Zt.bind(this)},["user_id"]);return await k.bind(this)("subscription",{unblock:e},{auth:true})}async function $l(t,e){await this.__connection;let r=await ee.bind(this)();if(t=_.Params(t||{},{user_id:o=>{if(o!==this.__user.user_id&&!r)throw new f("No access.",{code:"INVALID_REQUEST"});return o},group:o=>_.newsletterGroup(o,{allowNull:true}),email:o=>{if(typeof o!="string"||!o.trim())throw new f('"email" should be a non-empty string.',{code:"INVALID_PARAMETER"});if(o.trim().length>255)throw new f('"email" should be at most 255 characters.',{code:"INVALID_PARAMETER"});return o.trim().toLowerCase()}}),t.email!==void 0){if(t.user_id!==void 0&&t.user_id!==null)throw new f('"email" cannot be used with "user_id".',{code:"INVALID_PARAMETER"});if(t.group===void 0||t.group===null)throw new f('"group" is required to search by "email".',{code:"INVALID_PARAMETER"})}let n=await k.bind(this)("get-newsletter-subscription",t,{auth:true,fetchOptions:e||null}),i=n?.list||n,s=[];Array.isArray(i)||(i=[]);for(let o of i){let a=o.subt.split("#"),l=true;a[0].charAt(0)==="@"&&(l=false,a[0]=a[0].substring(1));let c=/^\d+$/.test(a[0])?parseInt(a[0]):a[0],d={timestamp:o.stmp,group:c,subscribed_email:a[1],active:l};typeof o.email_token=="string"&&o.email_token&&(d.subscriber_token=o.email_token),s.push(d);}return n?.list?(n.list=s,n):s}async function Hl(t){await this.__connection;let e=_.Params(t||{},{email:r=>Array.isArray(r)&&r.length>0?r.length===1?_.Email(r[0]):r.map(n=>_.Email(n)):_.Email(r),group:r=>_.newsletterGroup(r),redirect:r=>_.Url(r)},this.__user?["group"]:["email","group"]);return k.bind(this)(`subscribe-${this.__user?"":"public-"}newsletter`,e,{auth:!!this.__user})}async function Gl(t){await this.__connection;let e=_.Params(t||{},{group:r=>_.newsletterGroup(r,{nameOnly:true}),restriction:r=>{if(typeof r!="number"||!Number.isInteger(r)||r<0||r>99)throw new f('"restriction" should be a number between 0 and 99.',{code:"INVALID_PARAMETER"});return r},name:r=>{if(typeof r!="string"||r.length>60)throw new f('"name" should be a string of 60 characters or less.',{code:"INVALID_PARAMETER"});return r}},["group"]);return k.bind(this)("register-newsletter-group",e,{auth:true})}async function Wl(t){await this.__connection;let e=_.Params(t||{},{group:r=>_.newsletterGroup(r,{nameOnly:true})},["group"]);return k.bind(this)("delete-newsletter-group",e,{auth:true})}async function zl(){return await this.__connection,k.bind(this)("newsletter-group-endpoint",null,{auth:true})}async function Jl(t){await this.__connection,t=_.Params(t,{group:r=>_.newsletterGroup(r,{allowNull:true})},["group"]);let e=Object.assign({action:"unsubscribe"},t);return k.bind(this)("subscribe-newsletter",e,{auth:true})}async function Yl(t,e){let r=await ee.bind(this)(),n={message_id:"string",timestamp:"number",read:"number",complaint:"number",subject:"string",bounced:"number"};t||(e=Object.assign({ascending:false},e||{})),t=K(t).data,t=t||{searchFor:"timestamp",value:Date.now(),condition:"<",group:"public"},t=_.Params(t,{searchFor:["message_id","timestamp","subject","complaint","read","bounced"],value:l=>{if(typeof l!==n[t.searchFor])throw new f(`"value" type does not match the type of "${t.searchFor}" index.`,{code:"INVALID_PARAMETER"});if(typeof l=="string"&&!l)throw new f('"value" should not be empty string.',{code:"INVALID_PARAMETER"});return l},range:l=>{if(!t.hasOwnProperty("value")||typeof l!=typeof t.value)throw new f('"range" should match type of "value".',{code:"INVALID_PARAMETER"});return l},condition:[">",">=","=","<","<=","gt","gte","eq","lt","lte",()=>"="],group:l=>{let c=_.newsletterGroup(l);if(c===0)return 0;if(typeof c=="string")return c;if(!this.session)throw new f("User should be logged in.",{code:"INVALID_REQUEST"});if(l==="authorized")return 1;if(!r&&c>parseInt(this.user?.access_group||this.session?.idToken?.payload?.access_group))throw new f("User has no access.",{code:"INVALID_REQUEST"});return c}},["searchFor","value","group"]);let i=t.group===0||typeof t.group=="string"&&!this.__user?"get-public-newsletters":"get-newsletters",s=await k.bind(this)(i,t,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",group:"grp",dry:"dry",sent:"sent"},a={message_id:"",timestamp:0,complaint:0,read:0,subject:"",bounced:"",url:"",delivered:0,group:t.group,dry:false,sent:0};return s.list=s.list.map(l=>{let c={};for(let d in o)c[d]=l[o[d]]||a[d];return c.bounced=String(c.bounced),c.dry=!!c.dry,c.sent||delete c.sent,c}),s}var It="skapi:project_id";function Ql(t){let e=t.trim().toLowerCase().replace(/^<|>$/g,"").replace(/[\s_\-.]+/g,"");return e==="serviceid"||e==="projectid"}function Xl(){try{return window.sessionStorage.getItem(It)||null}catch{return null}}function Zl(t){try{window.sessionStorage.setItem(It,t);}catch{}}function Zr(t){try{window.sessionStorage.getItem(It)===t&&window.sessionStorage.removeItem(It);}catch{}}function ec(){if(J())return typeof window.prompt=="function";let t=it("tty");return !!(t&&it("readline")&&t.isatty(0)&&t.isatty(2))}function tc(){return new f("Project ID is required.",{code:"INVALID_PARAMETER"})}var er=null;function rc(t,e){if(!er){er=J()?Mh(t,e):qh(t,e);let r=()=>{er=null;};er.then(r,r);}return er}async function Mh(t,e){await new Promise(o=>setTimeout(o,0));let r=`new Skapi() was given the placeholder "${t}" instead of your Project ID.`,n=`Enter your Project ID to continue. This browser tab remembers it until the tab is closed. To stop being asked, replace "${t}" in your code with the ID.`,i=`${r}
|
|
216
|
+
`,l=new Blob([c],{type:"application/javascript"});Ye=new Worker(URL.createObjectURL(l)),Ye.onmessage=d=>{a.readyState===1&&a.send(JSON.stringify({action:"keepAlive"}));},i(a);},a.onmessage=async c=>{let l="";try{l=JSON.parse(decodeURI(c.data)),this.log("socket onmessage",l);}catch{return}let d;switch(!0){case !!l?.["#message"]:d="message";break;case !!l?.["#private"]:d="private";break;case !!l?.["#notice"]:d="notice";break;case !!l?.["#rtc"]:d="rtc";break;case !!l?.["#error"]:d="error";break;case !!l?.["#ice"]:d="ice";break}if(!d){if(l?.requestId&&l?.connectionId&&kt.length){let u=kt.splice(0);for(let p of u)p(null);}return}if(d==="ice"){let u=Kc(l["#ice"]);u&&(It={...u,at:Math.floor(Date.now()/1e3)});let p=kt.splice(0);for(let g of p)g(l["#ice"]);return}let h={type:d,message:l?.["#rtc"]||l?.["#message"]||l?.["#private"]||l?.["#notice"]||l?.["#error"]||null,sender:l?.["#user_id"]||null,sender_cid:l?.["#scid"]?"cid:"+l["#scid"]:null,sender_rid:l?.["#srid"]||null,code:l?.["#code"]||null};if(d==="notice")t(h);else if(d==="rtc"){if(h.sender!==this.user.user_id){let u=h.message;if(u.hungup){fe[h.sender_cid]&&(fe[h.sender_cid](!1),delete fe[h.sender_cid]),ke[h.sender_cid]&&delete ke[h.sender_cid],L?.[h.sender_cid]?Ce.bind(this)({cid:h.sender_cid}):Fc(h.sender_cid),h.type="rtc:closed",t(h);return}u.candidate&&vt(h.sender_cid,()=>nn.bind(this)(u.candidate,h.sender_cid)).catch(p=>this.log("rtc candidate",p)),u.sdpoffer&&(L?.[h.sender_cid]?vt(h.sender_cid,()=>rn.bind(this)(u,h.sender_cid)).catch(p=>this.log("rtc offer",p)):(vt(h.sender_cid,()=>rn.bind(this)(u,h.sender_cid)).catch(p=>this.log("rtc offer",p)),ke[h.sender_cid]||(ke[h.sender_cid]=h.sender_cid,delete h.message,h.meta=u.meta&&typeof u.meta=="object"&&!Array.isArray(u.meta)?u.meta:{},h.sources=u.sources&&typeof u.sources=="object"?Array.from(new Set(Object.values(u.sources).filter(p=>typeof p=="string"))):[],h.connectRTC=qc.bind(this)(h),h.type="rtc:incoming",h.hangup=(()=>{L[h.sender_cid]?Ce.bind(this)({cid:h.sender_cid}):ke[h.sender_cid]&&(delete ke[h.sender_cid],a.send(JSON.stringify({action:"rtc",uid:h.sender_cid,content:{hungup:this.user.user_id},token:this.session.accessToken.jwtToken})));}).bind(this),t(h)))),u.pickup&&fe[h.sender_cid]&&(fe[h.sender_cid](!0),delete fe[h.sender_cid]),u.sdpanswer&&vt(h.sender_cid,()=>Oc.bind(this)(u,h.sender_cid)).catch(p=>this.log("rtc answer",p));}}else t(h);},a.onclose=()=>{nr?(this.log("realtime onclose","WebSocket connection closed."),t({type:"close",message:"WebSocket connection closed."})):(this.log("realtime onclose","WebSocket unexpected close."),t({type:"error",message:"Skapi: WebSocket unexpected close."}),Pt++,Pt<3?(this.log("realtime onclose","Reconnecting to WebSocket server..."+Pt),t({type:"reconnect",message:"Reconnecting to WebSocket server..."+Pt}),Ct.bind(this)(t,3e3,"reconnect")):(this.log("realtime onclose","Max reconnection attempts reached."),t({type:"error",message:"Skapi: Max reconnection attempts reached."})));},a.onerror=()=>{this.log("realtime onerror","WebSocket connection error."),t({type:"error",message:"Skapi: WebSocket connection error."});};}catch(a){o(a);}},e);}),n.value=this.__socket,this.__socket}async function Hc(t,e,r){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 At.bind(this)(),t=$(t).data;let i="";if(r&&(r=_.Params(r,{config:{always:"boolean"},title:"string",body:"string"},["title","body"]),i=JSON.stringify({title:r.title,body:r.body}),new Blob([i]).size>3072))throw new f("Notification size exceeds 3kb.",{code:"INVALID_PARAMETER"});if(n.readyState===1){try{_.UserId(e),n.send(JSON.stringify({action:"sendMessage",uid:e,content:t,notification:i,notificationConfig:r?.config||{},token:`IdT:${this.service}:${this.owner}:`+(this.bearerToken||this.session?.idToken?.jwtToken||"null")}));}catch(s){if(this.log("postRealtime:err",{err:s}),$e!==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:t,notification:i,notificationConfig:r?.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 xt(t){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 At.bind(this)(),t=$(t,{nullIfEmpty:true}).data;let{group:r=null}=t;if(!r&&!$e)return {type:"success",message:"Left realtime message group."};if(r!==null&&typeof r!="string")throw new f('"group" must be a string | null.',{code:"INVALID_PARAMETER"});return e.readyState===1&&e.send(JSON.stringify({action:"joinRoom",rid:r,token:this.session.accessToken.jwtToken})),$e=r,{type:"success",message:r?`Joined realtime message group: "${r}".`:"Left realtime message group."}}async function Gc(t,e){t=_.Params(t,{user_id:n=>_.UserId(n,'User ID in "user_id"'),group:["string",()=>{if(!$e)throw new f('No group has been joined. Otherwise "group" is required.',{code:"INVALID_REQUEST"});return $e}]});let r=await P.bind(this)("get-ws-group",t,{fetchOptions:e,auth:true,method:"post"});return r.list=r.list.map(n=>({user_id:n.uid.split("#")[1],cid:"cid:"+n.cid})),r}async function Wc(t,e){if(await this.__connection,t||(t={searchFor:"group",value:" ",condition:">"}),t=_.Params(t,{searchFor:["group","number_of_users",()=>"group"],value:["string","number",()=>t?.searchFor&&t?.searchFor==="number_of_users"?0:" "],condition:[">",">=","=","<","<=","!=","gt","gte","eq","lt","lte","ne"],range:["string","number"]}),t.condition||(t.value===" "||!t.value?t.condition=">":t.condition="="),t.range&&t.condition&&delete t.condition,t.searchFor==="number_of_users"&&typeof t.value!="number")throw new f('"value" must be a number.',{code:"INVALID_PARAMETER"});if(t.searchFor==="group"&&typeof t.value!="string")throw new f('"value" must be a string.',{code:"INVALID_PARAMETER"});if(t.hasOwnProperty("range")&&typeof t.range!=typeof t.value)throw new f(`"range" must be a ${typeof t.value}.`,{code:"INVALID_PARAMETER"});let r=await P.bind(this)("get-ws-group",t,{fetchOptions:e,auth:true,method:"post"});return r.list=r.list.map(n=>({group:n.rid.split("#")[1],number_of_users:n.cnt})),r}var pp=typeof FormData<"u",Jc=typeof HTMLFormElement<"u",Yc=typeof SubmitEvent<"u",Fe={},ir={},ge={};function sr(t){return Object.freeze({id:t,status:"stopped"})}function Hi(t){return !!t&&typeof t=="object"&&t.status==="stopped"}var Qc=3;function Xc(t,e,r){let n=false,i=Array.isArray(t?.chunks)?t.chunks.slice():[];i.sort((s,o)=>(s?.seq||0)-(o?.seq||0));for(let s of i)if(!(!s||typeof s.seq!="number"||s.seq<=e.seq)&&(e.seq=s.seq,n=true,r&&typeof s.txt=="string"&&s.txt!==""))try{r(s.txt,s.seq,"poll");}catch(o){console.error(o);}return typeof t?.last_seq=="number"&&t.last_seq>e.seq&&(e.seq=t.last_seq,n=true),n}var gp=2e3,Zc=5e3,mp=2e3,yp=5,bp=1500,on=null;function el(t,e,r){let n=new Map,i=false,s=false,o=0,a={socket:0,poll:0},c=(u,p,g)=>{if(t.seq=u,!(!e||typeof p!="string"||p===""))try{e(p,u,g);}catch(m){console.error(m);}},l=()=>{for(let u of Array.from(n.keys()))u<=t.seq&&n.delete(u);for(;;){let u=t.seq+1;if(!n.has(u))break;let p=n.get(u);n.delete(u),c(u,p.txt,p.via);}};return {cursor:t,open:()=>{i||s||(i=true,l());},fromPoll:u=>{if(s)return false;let p=t.seq,g=t.seq,m=Array.isArray(u?.chunks)?u.chunks:[];for(let y of m){if(!y||typeof y.seq!="number"||y.seq<=t.seq)continue;let E=!n.has(y.seq);E&&(a.poll++,r&&a.poll===1&&r("poll",y.seq)),n.set(y.seq,{txt:typeof y.txt=="string"?y.txt:"",via:E?"poll":n.get(y.seq).via}),y.seq>g&&(g=y.seq);}typeof u?.last_seq=="number"&&u.last_seq>g&&(g=u.last_seq);let b=Array.from(n.keys()).sort((y,E)=>y-E);for(let y of b){if(y<=t.seq){n.delete(y);continue}if(y>g)break;let E=n.get(y);n.delete(y),c(y,E.txt,E.via);}return g>t.seq&&(t.seq=g),l(),t.seq>p},fromSocket:(u,p)=>{s||typeof u!="number"||!Number.isFinite(u)||(o=Date.now(),!(u<=t.seq)&&(!n.has(u)&&n.size>=mp||(n.has(u)||(a.socket++,r&&a.socket===1&&r("socket",u)),n.set(u,{txt:typeof p=="string"?p:"",via:n.has(u)?n.get(u).via:"socket"}),i&&l())));},warm:()=>o!==0&&Date.now()-o<gp,stats:()=>({socket:a.socket,poll:a.poll}),close:()=>{s=true,n.clear();}}}function tl(t){if(!this||!this.__network_logs)return {onTransport:void 0,done:()=>{}};let e=Date.now(),r=false;return {onTransport:(n,i)=>{console.log(`%cSKAPI: stream chunk arrived over ${n==="socket"?"WEBSOCKET":"POLL"}`,`color: ${n==="socket"?"green":"orange"};`,{id:t,first_seq:i,after_ms:Date.now()-e});},done:n=>{if(r||!n)return;r=true;let i=n.stats();console.log("%cSKAPI: stream transport","color: blue;",{id:t,over_websocket:i.socket,over_poll:i.poll,took_ms:Date.now()-e});}}}function rl(t,e){let r={stop:()=>{}};if(typeof window>"u"||window._runningInNodeJS||on)return r;let n={stopped:false,socket:null,opened:null,joined:false,attempts:0,unavailable:false};on=n;let i=l=>{if(n.stopped)return;let d=l?.data;if(typeof d!="string")return;let h=null;try{h=JSON.parse(d);}catch{try{h=JSON.parse(decodeURI(d));}catch{return}}let u=h?.["#message"];if(u==null)return;if(typeof u=="string")try{u=JSON.parse(u);}catch{return}if(typeof u!="object")return;let p=h?.["#srid"];if(typeof p=="string"&&p!==t)return;let g=u.seq;typeof g=="string"&&g!==""&&(g=Number(g)),e.fromSocket(g,u.txt);},s=()=>{if(n.socket){try{n.socket.removeEventListener("message",i);}catch{}try{n.socket.removeEventListener("close",a);}catch{}n.socket=null;}},o=async()=>{let l=n.opened,d=n.joined;if(n.opened=null,n.joined=false,s(),!(!d&&!l))try{let h=this.__socket?await this.__socket:null;if(l&&h===l){await sn.bind(this)();return}d&&h&&$c()===room&&await xt.bind(this)({group:null});}catch{}},a=()=>{n.stopped||(s(),!n.unavailable&&(n.attempts>=yp||(n.attempts+=1,setTimeout(()=>{n.stopped||c();},bp))));},c=async()=>{try{let l=this.__socket?await this.__socket:null;if(n.stopped){o();return}if(!l){if(!this.session){n.unavailable=!0,o();return}if(await Ct.bind(this)(()=>{},0),l=this.__socket?await this.__socket:null,n.stopped){o();return}l&&!n.opened&&(n.opened=l);}if(!l||l.readyState!==1)return;if(l.addEventListener("message",i),l.addEventListener("close",a),n.socket=l,!n.joined&&(await xt.bind(this)({group:t}),n.joined=!0,n.stopped)){o();return}}catch{}};return c(),{stop:()=>{n.stopped||(n.stopped=true,on===n&&(on=null),o());}}}function nl(t){return t?.status==="running"||t?.status==="pending"}function il(t){return !!t&&typeof t=="object"&&!Array.isArray(t)&&typeof t.status=="string"&&typeof t.id=="string"&&"in_queue"in t}function sl(t,e,r,n){if(!t||typeof t!="string")throw new f('"requestId" should be type: <string>.',{code:"INVALID_PARAMETER"});if(t.includes("#"))return t;if(!e||typeof e!="string"||!r||typeof r!="string")throw new f('"url" and "method" are required to address a request by its short id.',{code:"INVALID_PARAMETER"});return _.Url(e),`[${r.toUpperCase()}]${e.toLowerCase()}#${n}:${t}`}function ol({id:t,auth:e,service:r,owner:n,latency:i=1e3,queue:s,seedExecuted:o,onResponse:a,onError:c,onStream:l,realtimeGroup:d}){if(typeof i!="number")throw new f('"latency" should be a number.',{code:"INVALID_PARAMETER"});if(i<0)throw new f('"latency" should be a non-negative number.',{code:"INVALID_PARAMETER"});s&&!Fe?.[s]&&(Fe[s]=new Yt({breakWhenError:false,batchSize:1}));let h={stop:null,aborted:false,queue:s};ge[t]=h;let u=null,p=()=>{ge[t]===h&&delete ge[t];},g=()=>new Promise((b,y)=>{let E=false;if(h.aborted){p(),b(sr(t));return}let w={seq:0},T=tl.call(this,t),R=l&&d?el(w,l,T.onTransport):null,x=R?rl.call(this,d,R):null,O=()=>{T.done(R),x&&x.stop(),R&&R.close();};u=O;let U=0,I=false,D=0,N=typeof o=="number"&&o>0?o:void 0,M=async()=>{if(!(E||I)&&!(R&&R.warm()&&Date.now()-U<Zc)){I=true;try{for(;;){let ae={id:t,service:r,owner:n};l&&(ae.since=w.seq),U=Date.now();let q=await P.bind(this)("csr-poll",ae,{auth:e});if(E)return;let te=R?R.fromPoll(q):l?Xc(q,w,l):!1;R&&R.open();let cr=nl(q);if(typeof q?.executed=="number"&&q.executed>0&&(N=q.executed),q?.more&&te){D=0;continue}if(cr){D=0;return}if(D=q?.more?D+1:0,q?.more&&D<Qc)return;E=!0,a&&a(q,N!==void 0?{executed:N}:void 0),clearInterval(ie),O(),p(),b(q);return}}catch(ae){if(E)return;E=true,c&&c(ae),clearInterval(ie),O(),p(),y(ae);}finally{I=false;}}},ie=setInterval(M,i);R&&M(),h.stop=()=>{E||(E=true,clearInterval(ie),O(),p(),b(sr(t)));};}),m=()=>{let b=ge[t];b&&(b.stop?b.stop():(b.aborted=true,delete ge[t]));};if(s){let b=new Promise((y,E)=>{let w=false,T=Fe[s].add([async()=>{try{let R=await g();return w||(w=!0,y(R)),R}catch(R){throw w||(w=true,E(R)),R}}])[0];ir[t]=T,h.stop=()=>{if(!w){h.aborted=true,u&&u();try{Fe[s]&&Fe[s].remove(ir[t]);}catch{}delete ir[t],p(),w=true,y(sr(t));}};});return Object.assign(b,{stop:m})}else return Object.assign(g(),{stop:m})}function cn(t){let e=0,r=[];if(t?.id){if(t.url&&t.method){let n=t.service||this.service;r.push(`[${t.method.toUpperCase()}]${t.url.toLowerCase()}#${n}:${t.id}`);}r.push(t.id);}else if(t?.queue)for(let n in ge)ge[n]?.queue===t.queue&&r.push(n);else for(let n in ge)r.push(n);for(let n of r){let i=ge[n];i&&(i.stop?i.stop():(i.aborted=true,delete ge[n]),e+=1);}return e}function Gi(t,e){if(!t.queue)throw new f('"queue" is required.',{code:"INVALID_PARAMETER"});let r=()=>P.bind(this)("csr-poll",{service:t.service||this.service,owner:t.owner||this.owner,queue:t.queue+":"},{auth:true});return this.__projectIdInput?this.__projectIdInput.then(r):r()}function _p(t){if(typeof Buffer<"u"&&typeof Buffer.from=="function")return Buffer.from(t).toString("base64");if(typeof btoa=="function"){let e="";for(let n=0;n<t.length;n+=32768)e+=String.fromCharCode.apply(null,Array.from(t.subarray(n,n+32768)));return btoa(e)}throw new f("No base64 encoder available in this environment.",{code:"NOT_SUPPORTED"})}var zc=2*1024*1024-64*1024;function an(t){return typeof File<"u"&&t instanceof File||typeof Blob<"u"&&t instanceof Blob}function $i(t){if(Array.isArray(t)){let e=[];for(let r of t)an(r)||e.push($i(r));return e}if(t&&typeof t=="object"&&!an(t)){let e=Object.getPrototypeOf(t);if(e!==Object.prototype&&e!==null)return t;let r={};for(let n in t)an(t[n])||(r[n]=$i(t[n]));return r}return t}function wp(t){if(t==null)return null;let e=$(t)?.data;return !e||typeof e!="object"||Array.isArray(e)?null:$i(e)}function al(t,e,r){if(r!==void 0){if(Array.isArray(r)){for(let n of r)al(t,e,n);return}if(an(r)){t.append(e,r);return}if(r===null){t.append(e,"");return}if(typeof r=="object"){t.append(e,JSON.stringify(r));return}t.append(e,String(r));}}async function Ep(t){if(t==null)throw new f('"multipart": true needs a form body in the first argument.',{code:"INVALID_PARAMETER"});if(typeof FormData>"u"||typeof Response>"u")throw new f('"multipart": true is not available in this environment.',{code:"NOT_SUPPORTED"});let e;if(Yc&&t instanceof SubmitEvent)e=new FormData(t.target);else if(Jc&&t instanceof HTMLFormElement)e=new FormData(t);else if(t instanceof FormData)e=t;else if(typeof t=="object"&&!Array.isArray(t)){e=new FormData;for(let s in t)al(e,s,t[s]);}else throw new f('"form" should be a submit event, a form element, FormData, or an object.',{code:"INVALID_PARAMETER"});let r=new Response(e),n=r.headers.get("content-type"),i=_p(new Uint8Array(await r.arrayBuffer()));if(i.length>zc)throw new f(`Multipart body is too large: ${i.length} bytes once base64 encoded, and the limit is ${zc}. Upload the file first and send its url instead.`,{code:"INVALID_PARAMETER"});return {body_b64:i,body_content_type:n}}function Ap(t){if(t!=null){if(typeof t=="boolean")return t;if(typeof t=="object"&&!Array.isArray(t))return {user:!!t.user,service:!!t.service};throw new f('"skapiHeaders" should be type: <boolean> or { user?: boolean; service?: boolean }.',{code:"INVALID_PARAMETER"})}}function Rp(t){if(!(!t||typeof t!="object")){for(let e in t)if(typeof e=="string"&&e.toLowerCase().indexOf("x-skapi-")===0)throw new f(`"headers" cannot set "${e}": the "x-skapi-" prefix is reserved. Use "skapiHeaders" to tell the destination who the caller is.`,{code:"INVALID_PARAMETER"})}}async function cl(t,e){let r=false,n=!!(t?.secretName||t?.clientSecretName),i=e?.signal;if(i?.aborted)throw new f('"signal" was already aborted.',{code:"INVALID_REQUEST"});if(typeof t.poll=="number"&&t.poll<0)throw new f('"poll" should be a non-negative number.',{code:"INVALID_PARAMETER"});let s=t?.onResponse,o=t?.onError,a=t?.onStream,c=typeof t.poll=="number"?t.poll:t.poll?1e3:0;delete t.poll,(c||t.stream)&&!t.queue&&(t.queue=(this.__user?.user_id||"anonymous")+"-"+et());let l=(u,p=new WeakSet)=>{if(!(r||!u||typeof u!="object"||p.has(u))){p.add(u);for(let g in u){let m=u[g];if(typeof m=="string"){if(m.includes("$CLIENT_SECRET")){r=true;return}}else m&&typeof m=="object"&&l(m,p);}}};if(t=_.Params(t,{url:u=>{if(!u||typeof u!="string")throw new f('"url" should be type: <string>.',{code:"INVALID_PARAMETER"});return _.Url(u),u.includes("$CLIENT_SECRET")&&(r=true),u},secretName:"string",clientSecretName:"string",method:u=>{if(u&&typeof u!="string")throw new f('"method" should be one of "GET", "POST", "PUT", "PATCH", "DELETE" or "HEAD".',{code:"INVALID_PARAMETER"});let p=u.toLowerCase();if(p!=="get"&&p!=="post"&&p!=="delete"&&p!=="put"&&p!=="patch"&&p!=="head")throw new f('"method" should be one of "GET", "POST", "PUT", "PATCH", "DELETE" or "HEAD".',{code:"INVALID_PARAMETER"});return p},stream:u=>{if(u!=null&&typeof u!="boolean")throw new f('"stream" should be type: <boolean>.',{code:"INVALID_PARAMETER"});return !!u},realtime:u=>{if(u!=null&&typeof u!="boolean")throw new f('"realtime" should be type: <boolean>.',{code:"INVALID_PARAMETER"});return !!u},headers:u=>{if(u&&typeof u!="object")throw new f('"headers" should be type: <object>.',{code:"INVALID_PARAMETER"});return Rp(u),l(u),u},skapiHeaders:u=>Ap(u),data:u=>{if(u&&typeof u!="object")throw new f('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return l(u),u},params:u=>{if(u&&typeof u!="object")throw new f('"params" should be type: <object>.',{code:"INVALID_PARAMETER"});return l(u),u},body_b64:"string",body_content_type:"string",expires:"number",queue:"string"},e?.requireSecretName?["clientSecretName","method","url"]:["method","url"]),t.realtime&&!t.stream)throw new f('"realtime" requires "stream": true.',{code:"INVALID_PARAMETER"});if(t.body_b64&&t.data)throw new f('"data" cannot be sent with "multipart": true.',{code:"INVALID_PARAMETER"});n&&!r&&(delete t.secretName,delete t.clientSecretName),await this.__connection;let d=!!this.__user,h=()=>P.bind(this)("csr",t,{auth:d,tokenHeaders:{accessToken:!!d}}).then(u=>{if(u.status==="running"||u.status==="pending"){let p=`[${t.method.toUpperCase()}]${t.url.toLowerCase()}`,g=t.service||this.service,m=t.owner||this.owner,b=`${p}#${g}:${u.id}`;if(i){let y=()=>{cn.call(this,{id:b});};i.aborted?y():i.addEventListener("abort",y,{once:true});}Object.assign(u,{poll:y=>ol.call(this,{id:b,auth:d,service:g,owner:m,latency:y?.latency||1e3,queue:t?.queue,onResponse:s,onError:o,onStream:y?.onStream||a,realtimeGroup:u?.realtime_group})});}return s?s(u):u}).catch(u=>{if(o)return o(u);throw u});if(t?.queue){let u="base:"+t.queue;return Fe?.[u]||(Fe[u]=new Yt({breakWhenError:false,batchSize:1})),new Promise((p,g)=>{Fe[u].add([async()=>{try{let m=await h();if(c>0){let b=m.poll({latency:c});return i&&(i.aborted?b.stop():i.addEventListener("abort",()=>b.stop(),{once:!0})),p(b),b}return p(m),m}catch(m){throw g(m),m}}]);})}else return h()}async function ll(t,e){if(!e||typeof e!="object")throw new f('"options" is required in the second argument.',{code:"INVALID_PARAMETER"});if(e.apiKeyHeader!==void 0||e.apiKeyScheme!==void 0)throw new f('"apiKeyHeader" and "apiKeyScheme" are no longer supported. Store the key as a client secret, name it with "secretName", and put "$CLIENT_SECRET" where the key goes.',{code:"INVALID_PARAMETER"});if(e.multipart!==void 0&&e.multipart!==null&&typeof e.multipart!="boolean")throw new f('"multipart" should be type: <boolean>.',{code:"INVALID_PARAMETER"});let r=e.responseType;if(r!=null){if(r==="response")throw new f(`"responseType": "response" is not available here. The request is relayed from the server and what comes back is the stored answer, not a live Response; the destination's status code is the "status_code" of the row forwardRequestHistory lists.`,{code:"INVALID_PARAMETER"});if(r!=="json"&&r!=="text")throw new f('"responseType" should be either "json" or "text".',{code:"INVALID_PARAMETER"})}let n=e.method||"POST",i=typeof n=="string"?n.toLowerCase():"",s=i==="get"||i==="delete"||i==="head"?"params":"data",o={url:e.url,method:n};if(e.secretName!==void 0&&(o.secretName=e.secretName),e.headers!==void 0&&(o.headers=e.headers),e.data!==void 0&&(o.data=e.data),e.params!==void 0&&(o.params=e.params),e.skapiHeaders!==void 0&&(o.skapiHeaders=e.skapiHeaders),e.service!==void 0&&(o.service=e.service),e.owner!==void 0&&(o.owner=e.owner),e.queue!==void 0&&(o.queue=e.queue),e.expires!==void 0&&(o.expires=e.expires),e.stream!==void 0&&(o.stream=e.stream),e.realtime!==void 0&&(o.realtime=e.realtime),e.poll!==void 0&&(o.poll=e.poll),e.onStream!==void 0&&(o.onStream=e.onStream),e.onResponse!==void 0&&(o.onResponse=e.onResponse),e.onError!==void 0&&(o.onError=e.onError),e.multipart){if(e.data!==void 0&&e.data!==null)throw new f('"data" cannot be sent with "multipart": true. The form itself is the body.',{code:"INVALID_PARAMETER"});let c=await Ep(t);o.body_b64=c.body_b64,o.body_content_type=c.body_content_type;}else {let c=wp(t);c&&Object.keys(c).length&&(o[s]=Object.assign({},c,o[s]||{}));}let a=cl.call(this,o,{signal:e.signal});return r?a.then(c=>{if(il(c)||Hi(c))return c;if(r==="text")return typeof c=="string"?c:JSON.stringify(c);if(typeof c=="string")try{return JSON.parse(c)}catch{return c}return c}):a}async function ul(t){return cl.call(this,t,{requireSecretName:true})}async function Wi(t,e){await this.__connection;let r=t.service||this.service,n=t.owner||this.owner;t=_.Params(t,{url:"string",method:["GET","POST","PUT","PATCH","DELETE","HEAD"],queue:"string",status:["pending","running","resolved","failed"],compact:"boolean",queue_exact:"boolean",queue_exclude:"string"},["url","method"]);let i=!!this.__user,s=`[${t.method.toUpperCase()}]${t.url.toLowerCase()}#${r}:`,o={id:s,queue:t?.queue,status:t?.status,service:r,owner:n};t?.compact&&(o.compact=true),t?.queue_exact&&(o.queue_exact=true),t?.queue_exclude&&(o.queue_exclude=t.queue_exclude),Object.keys(o).forEach(c=>{o[c]||delete o[c];}),o.queue&&(o.id_prefix=o.id,delete o.id);let a=await P.bind(this)("csr-poll",o,{auth:i,fetchOptions:e});return a.list=a.list.map(c=>{let l={id:c.id,status_code:c.rslv?.status_code||null,response_body:c.rslv?.body||c.rslv?.truncated||null,error:c?.err,created:c?.stmp,updated:c?.utmp,executed:typeof c?.att=="number"?c.att*1e3:void 0,responded:typeof c?.rtmp=="number"?c.rtmp:void 0,request_body:c?.reqbdy,expires:c?.expt,status:c.stts,queue_name:c?.qid,request_text:c?.reqtxt,response_text:c?.rslvtxt,response_complete_marker:c?.rslvmk!=null?!!c.rslvmk:void 0,compact:c?.cmpct?true:void 0};for(let d in l)l[d]===void 0&&delete l[d];return (l.status==="running"||l.status==="pending")&&(l.poll=d=>ol.call(this,{id:s+l.id,auth:i,service:r,owner:n,latency:d?.latency||1e3,queue:c?.qid,seedExecuted:l.executed,onResponse:d?.onResponse,onError:d?.onError,onStream:d?.onStream})),l}),a}async function zi(t){await this.__connection,t=_.Params(t,{url:"string",method:["GET","POST","PUT","PATCH","DELETE","HEAD"],id:"string",queue:"string"},["url","method","id"]);let e=t?.service||this.service,r=t?.owner||this.owner,n=!!this.__user,i=`[${t.method.toUpperCase()}]${t.url.toLowerCase()}#${e}`,s=t.id,o=`${i}:${s}`,a=t?.queue;return a&&Fe?.[a]&&(Fe[a].remove(ir[o]),delete ir[o]),P.bind(this)("csr-cancel",{id:o,service:e,owner:r},{auth:n})}function Ji(t,e){let r=typeof e?.poll=="number"?e.poll:1e3;if(!Number.isFinite(r)||r<0)throw new f('"poll" should be a non-negative number.',{code:"INVALID_PARAMETER"});if(!t||typeof t!="string")throw new f('"requestId" should be type: <string>.',{code:"INVALID_PARAMETER"});if(e?.since!==void 0&&typeof e.since!="number")throw new f('"since" should be a number.',{code:"INVALID_PARAMETER"});if(e?.realtimeGroup!==void 0&&e.realtimeGroup!==null&&typeof e.realtimeGroup!="string")throw new f('"realtimeGroup" should be type: <string>.',{code:"INVALID_PARAMETER"});let n=typeof e?.since=="number"&&e.since>0?e.since:0,i=e?.onStream,s=e?.onResponse,o=e?.onError,a={stopped:false,fullId:t,resolve:null},c=null,l={stop:null,aborted:false},d=()=>{ge[a.fullId]===l&&delete ge[a.fullId];},h=()=>{a.stopped||(a.stopped=true,c&&c(),d(),a.resolve&&a.resolve(sr(a.fullId)));};l.stop=h;let u=new Promise(async(p,g)=>{a.resolve=p;try{await this.__connection;let m=!!this.__user,b=e?.service||this.service,y=e?.owner||this.owner;if(a.fullId=sl(t,e?.url,e?.method,b),a.stopped){p(sr(a.fullId));return}ge[a.fullId]=l;let E={seq:n},w=0,T=tl.call(this,a.fullId),R=i&&e?.realtimeGroup?el(E,i,T.onTransport):null,x=R?rl.call(this,e.realtimeGroup,R):null,O=()=>{T.done(R),x&&x.stop(),R&&R.close();};for(c=O;;){let U=await P.bind(this)("csr-poll",{id:a.fullId,service:b,owner:y,since:E.seq},{auth:m});if(a.stopped)return;if(!il(U)){O(),d(),s&&s(U),p(U);return}let I=R?R.fromPoll(U):Xc(U,E,i);R&&R.open();let D=nl(U);if(U.more&&I){w=0;continue}if(w=U.more?w+1:0,!D&&(!U.more||w>=Qc)){O(),d(),s&&s(U),p(U);return}if(await new Promise(N=>setTimeout(N,R&&R.warm()?Math.max(r,Zc):r)),a.stopped)return}}catch(m){if(a.stopped)return;c&&c(),d(),o&&o(m),g(m);}});return Object.assign(u,{stop:h})}async function Yi(t,e,r){await this.__connection;let n=r?.service||this.service,i=r?.owner||this.owner,s=!!this.__user,o=sl(t,r?.url,r?.method,n);return P.bind(this)("csr-finalize",{id:o,data:e,service:n,owner:i},{auth:s})}var dl=Ji,fl=Yi,hl=Wi,pl=zi,gl=cn,ml=Gi;async function yl(t){await this.__connection;let e={name:"string",email:r=>(_.Email(r),r),subject:"string",message:"string"};return t=_.Params(t,e,["name","email","subject","message"]),await P.bind(this)("send-inquiry",t),"SUCCESS: Inquiry has been sent."}async function bl(t,e){if(await this.__connection,pp&&t instanceof FormData||Jc&&t instanceof HTMLFormElement||Yc&&t instanceof SubmitEvent){if(!e)throw new f("Url string as a second argument is required when form is passed.",{code:"INVALID_PARAMETER"});let n=$(t);t={url:e,data:n.data,sync:true};}let r={url:n=>_.Url(n),data:n=>n,sync:["boolean",()=>true]};if(Array.isArray(t))for(let n of t)n=_.Params(n,r);else t=_.Params(t,r);return P.bind(this)("post-secure",t,{auth:true})}async function _l(t,e){await this.__connection;let{auth:r=false,method:n="POST",bypassAwaitConnection:i=false,responseType:s,contentType:o,tokenHeaders:a,progress:c}=e||{};if(e=Object.assign({auth:r,method:n,bypassAwaitConnection:i,responseType:s,contentType:o,tokenHeaders:a},{fetchOptions:{progress:c}}),typeof t!="object"&&(o==="application/json"||o===void 0))throw new f('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return P.bind(this)("mock",t,e)}async function wl(t,e){await this.__connection,t=_.Params(t||{},{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 r=await P.bind(this)("get-feed",t,{auth:true,fetchOptions:e});return Array.isArray(r?.list)&&(r.list=await Promise.all(r.list.map(n=>nt.bind(this)(n)))),r}function or(t){if(t===this.__user.user_id)throw new f(`"user_id" cannot be the user's own ID.`,{code:"INVALID_PARAMETER"});return _.UserId(t,'"user_id"')}async function El(t,e){if(t=$(t,{ignoreEmpty:true}).data,t=_.Params(t,{subscriber:n=>_.UserId(n,'User ID in "subscriber"'),subscription:or.bind(this),blocked:"boolean"}),!t.subscriber&&!t.subscription)throw new f('At least either "subscriber" or "subscription" should have a value.',{code:"INVALID_PARAMETER"});let r=await P.bind(this)("get-subscription",t,Object.assign({auth:true},{fetchOptions:e}));return r.list=r.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})),r}async function Al(t){await this.__connection,t=_.Params(t,{user_id:or.bind(this),get_feed:"boolean",get_notified:"boolean",get_email:i=>{if(i&&(!this.__user.email||!this.__user.email_verified))throw new f("User has no verified email address.",{code:"INVALID_REQUEST"});return !!i}},["user_id"]);let e={};for(let i of ["get_feed","get_notified","get_email"])typeof t[i]=="boolean"&&(e[i]=t[i]);let r=await P.bind(this)("subscription",{subscribe:t.user_id,option:e},{auth:true}),n={};if(r.sub){let i=r.sub.split("#");n.subscriber=i[2],n.subscription=i[0];}else n.subscriber=r.subscriber,n.subscription=r.subscription;return n.timestamp=r?.timestamp||r.stmp,n.blocked=r?.blocked||r.grp.substring(0,1)==="N",Object.assign(n,r.opt),n}async function Rl(t){await this.__connection;let{user_id:e}=_.Params(t,{user_id:or.bind(this)},["user_id"]);return await P.bind(this)("subscription",{unsubscribe:e},{auth:true})}async function Tl(t){await this.__connection;let{user_id:e}=_.Params(t,{user_id:or.bind(this)},["user_id"]);return await P.bind(this)("subscription",{block:e},{auth:true})}async function Sl(t){await this.__connection;let{user_id:e}=_.Params(t,{user_id:or.bind(this)},["user_id"]);return await P.bind(this)("subscription",{unblock:e},{auth:true})}async function vl(t,e){await this.__connection;let r=await ne.bind(this)();if(t=_.Params(t||{},{user_id:o=>{if(o!==this.__user.user_id&&!r)throw new f("No access.",{code:"INVALID_REQUEST"});return o},group:o=>_.newsletterGroup(o,{allowNull:true}),email:o=>{if(typeof o!="string"||!o.trim())throw new f('"email" should be a non-empty string.',{code:"INVALID_PARAMETER"});if(o.trim().length>255)throw new f('"email" should be at most 255 characters.',{code:"INVALID_PARAMETER"});return o.trim().toLowerCase()}}),t.email!==void 0){if(t.user_id!==void 0&&t.user_id!==null)throw new f('"email" cannot be used with "user_id".',{code:"INVALID_PARAMETER"});if(t.group===void 0||t.group===null)throw new f('"group" is required to search by "email".',{code:"INVALID_PARAMETER"})}let n=await P.bind(this)("get-newsletter-subscription",t,{auth:true,fetchOptions:e||null}),i=n?.list||n,s=[];Array.isArray(i)||(i=[]);for(let o of i){let a=o.subt.split("#"),c=true;a[0].charAt(0)==="@"&&(c=false,a[0]=a[0].substring(1));let l=/^\d+$/.test(a[0])?parseInt(a[0]):a[0],d={timestamp:o.stmp,group:l,subscribed_email:a[1],active:c};typeof o.email_token=="string"&&o.email_token&&(d.subscriber_token=o.email_token),s.push(d);}return n?.list?(n.list=s,n):s}async function Il(t){await this.__connection;let e=_.Params(t||{},{email:r=>Array.isArray(r)&&r.length>0?r.length===1?_.Email(r[0]):r.map(n=>_.Email(n)):_.Email(r),group:r=>_.newsletterGroup(r),redirect:r=>_.Url(r)},this.__user?["group"]:["email","group"]);return P.bind(this)(`subscribe-${this.__user?"":"public-"}newsletter`,e,{auth:!!this.__user})}async function Pl(t){await this.__connection;let e=_.Params(t||{},{group:r=>_.newsletterGroup(r,{nameOnly:true}),restriction:r=>{if(typeof r!="number"||!Number.isInteger(r)||r<0||r>99)throw new f('"restriction" should be a number between 0 and 99.',{code:"INVALID_PARAMETER"});return r},name:r=>{if(typeof r!="string"||r.length>60)throw new f('"name" should be a string of 60 characters or less.',{code:"INVALID_PARAMETER"});return r}},["group"]);return P.bind(this)("register-newsletter-group",e,{auth:true})}async function kl(t){await this.__connection;let e=_.Params(t||{},{group:r=>_.newsletterGroup(r,{nameOnly:true})},["group"]);return P.bind(this)("delete-newsletter-group",e,{auth:true})}async function Cl(){return await this.__connection,P.bind(this)("newsletter-group-endpoint",null,{auth:true})}async function xl(t){await this.__connection,t=_.Params(t,{group:r=>_.newsletterGroup(r,{allowNull:true})},["group"]);let e=Object.assign({action:"unsubscribe"},t);return P.bind(this)("subscribe-newsletter",e,{auth:true})}async function Ul(t,e){let r=await ne.bind(this)(),n={message_id:"string",timestamp:"number",read:"number",complaint:"number",subject:"string",bounced:"number"};t||(e=Object.assign({ascending:false},e||{})),t=$(t).data,t=t||{searchFor:"timestamp",value:Date.now(),condition:"<",group:"public"},t=_.Params(t,{searchFor:["message_id","timestamp","subject","complaint","read","bounced"],value:c=>{if(typeof c!==n[t.searchFor])throw new f(`"value" type does not match the type of "${t.searchFor}" index.`,{code:"INVALID_PARAMETER"});if(typeof c=="string"&&!c)throw new f('"value" should not be empty string.',{code:"INVALID_PARAMETER"});return c},range:c=>{if(!t.hasOwnProperty("value")||typeof c!=typeof t.value)throw new f('"range" should match type of "value".',{code:"INVALID_PARAMETER"});return c},condition:[">",">=","=","<","<=","gt","gte","eq","lt","lte",()=>"="],group:c=>{let l=_.newsletterGroup(c);if(l===0)return 0;if(typeof l=="string")return l;if(!this.session)throw new f("User should be logged in.",{code:"INVALID_REQUEST"});if(c==="authorized")return 1;if(!r&&l>parseInt(this.user?.access_group||this.session?.idToken?.payload?.access_group))throw new f("User has no access.",{code:"INVALID_REQUEST"});return l}},["searchFor","value","group"]);let i=t.group===0||typeof t.group=="string"&&!this.__user?"get-public-newsletters":"get-newsletters",s=await P.bind(this)(i,t,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",group:"grp",dry:"dry",sent:"sent"},a={message_id:"",timestamp:0,complaint:0,read:0,subject:"",bounced:"",url:"",delivered:0,group:t.group,dry:false,sent:0};return s.list=s.list.map(c=>{let l={};for(let d in o)l[d]=c[o[d]]||a[d];return l.bounced=String(l.bounced),l.dry=!!l.dry,l.sent||delete l.sent,l}),s}var Ut="skapi:project_id";function Dl(t){let e=t.trim().toLowerCase().replace(/^<|>$/g,"").replace(/[\s_\-.]+/g,"");return e==="serviceid"||e==="projectid"}function Nl(){try{return window.sessionStorage.getItem(Ut)||null}catch{return null}}function Ol(t){try{window.sessionStorage.setItem(Ut,t);}catch{}}function ln(t){try{window.sessionStorage.getItem(Ut)===t&&window.sessionStorage.removeItem(Ut);}catch{}}function Fl(){if(X())return typeof window.prompt=="function";let t=ct("tty");return !!(t&&ct("readline")&&t.isatty(0)&&t.isatty(2))}function Ll(){return new f("Project ID is required.",{code:"INVALID_PARAMETER"})}var ar=null;function Ml(t,e){if(!ar){ar=X()?Tp(t,e):Sp(t,e);let r=()=>{ar=null;};ar.then(r,r);}return ar}async function Tp(t,e){await new Promise(o=>setTimeout(o,0));let r=`new Skapi() was given the placeholder "${t}" instead of your Project ID.`,n=`Enter your Project ID to continue. This browser tab remembers it until the tab is closed. To stop being asked, replace "${t}" in your code with the ID.`,i=`${r}
|
|
217
217
|
|
|
218
|
-
${n}`,s="";for(;;){let o=window.prompt(i,s);if(o===null)throw
|
|
218
|
+
${n}`,s="";for(;;){let o=window.prompt(i,s);if(o===null)throw Ll();if(s=o.trim(),!s){i=`${r}
|
|
219
219
|
|
|
220
220
|
${n}`;continue}try{return e(s),s}catch{i=`"${s}" is not a valid Project ID.
|
|
221
221
|
|
|
222
|
-
${n}`;}}}function
|
|
223
|
-
`),s(
|
|
224
|
-
`);}
|
|
222
|
+
${n}`;}}}function Sp(t,e){let r=globalThis.process,n=ct("readline");return new Promise((i,s)=>{let o=n.createInterface({input:r.stdin,output:r.stderr,terminal:false}),a=false;o.on("close",()=>{a||(r.stderr.write(`
|
|
223
|
+
`),s(Ll()));});let c=()=>o.question("Enter your Project ID: ",l=>{let d=l.trim();if(d)try{e(d),a=!0,o.close(),i(d);return}catch{r.stderr.write(`"${d}" is not a valid Project ID.
|
|
224
|
+
`);}c();});r.stderr.write(`new Skapi() was given the placeholder "${t}" instead of your Project ID.
|
|
225
225
|
This process remembers the ID until it exits. To stop being asked, replace "${t}" in your code with the ID.
|
|
226
|
-
`),l();})}async function nc(t){let e=_.Params(t,{user_id:n=>_.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 ee.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 k.bind(this)("block-account",e,{auth:true})}async function ic(t){let e=_.Params(t,{user_id:n=>_.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 ee.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 k.bind(this)("block-account",e,{auth:true})}async function sc(t){let e=_.Params(t,{user_id:n=>_.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 ee.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 k.bind(this)("remove-account",e,{auth:true})}async function oc(t,e){let r={email:s=>_.Email(s),password:s=>_.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=>_.Birthdate(s),phone_number:s=>_.PhoneNumber(s),picture:s=>{if(s)return _.Url(s)},profile:s=>{if(s)return _.Url(s)},website:s=>{if(s)return _.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=_.Params(t,r,["email"]);if(e=_.Params(e,{confirmation_url:s=>{let o=s;if(typeof s=="string")o=_.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:_.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 ee.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 k.bind(this)("admin-signup",n,{auth:true})}async function ac(t){let e={email:s=>_.Email(s),password:s=>_.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=>_.Birthdate(s),phone_number:s=>_.PhoneNumber(s),picture:s=>s?_.Url(s):"",profile:s=>s?_.Url(s):"",website:s=>s?_.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}},r=["email","password"],n=_.Params(t,e,r);if(!await ee.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 k.bind(this)("admin-signup",n,{auth:true})}async function lc(t){if(t=_.Params(t,{user_id:r=>_.UserId(r,'"user_id"'),access_group:r=>{try{typeof r=="string"&&(r=parseInt(r));}catch{throw new f('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof r=="number"&&r>0&&r<100)return r;throw new f('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"})}},["user_id","access_group"]),!await ee.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 k.bind(this)("grant-access",t,{auth:true})}async function cc(t,e){if(t=_.Params(t,{email:"string"}),!await ee.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 k.bind(this)("invitation-list",Object.assign({mode:"search"},t),{fetchOptions:e,auth:true});return n.list=n.list.map(i=>Ut(i.user)),n}async function uc(t){if(t=_.Params(t,{email:r=>_.Email(r)},["email"]),!await ee.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 k.bind(this)("invitation-list",Object.assign({mode:"cancel"},t),{auth:true})}async function dc(t){if(t=_.Params(t,{email:r=>_.Email(r)},["email"]),!await ee.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 k.bind(this)("invitation-list",Object.assign({mode:"resend"},t),{auth:true})}async function fc(t){let e=_.Params(t,{user_id:o=>_.UserId(o,'"user_id"'),email:o=>_.Email(o),address:o=>{if(!o)return "";if(typeof o=="string")return o;if(typeof o=="object")return JSON.stringify(o)},name:"string",gender:"string",birthdate:o=>o?_.Birthdate(o):"",phone_number:o=>o?_.PhoneNumber(o):"",misc:"string",picture:o=>o?_.Url(o):"",profile:o=>o?_.Url(o):"",nickname:"string",website:o=>o?_.Url(o):""},["user_id"]),r=e.service,n=e.owner;if(delete e.service,delete e.owner,await this.__connection,this.__user?.user_id&&e.user_id===this.__user.user_id)throw new f("Cannot modify attributes of the current user.",{code:"INVALID_REQUEST"});if(Object.keys(e).filter(o=>o!=="user_id"&&e[o]!==void 0).length===0)throw new f("At least one attribute to update is required.",{code:"INVALID_PARAMETER"});if(!await ee.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 s={attributes:e};return r&&n&&(s.service=r,s.owner=n),await k.bind(this)("admin-edit-profile",s,{auth:true})}async function hc(t){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,!t.endpoint)throw new f("Missing parameter: endpoint",{code:"INVALID_PARAMETER"});if(!t.keys||!t.keys.p256dh||!t.keys.auth)throw new f("Missing parameter: keys.p256dh or keys.auth",{code:"INVALID_PARAMETER"});return await k.bind(this)("store-subscription",{endpoint:t.endpoint,keys:t.keys},{auth:true}),"SUCCESS: Subscribed to receive notifications."}async function pc(t){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,!t.endpoint)throw new f("Missing parameter: endpoint",{code:"INVALID_PARAMETER"});if(!t.keys||!t.keys.p256dh||!t.keys.auth)throw new f("Missing parameter: keys.p256dh or keys.auth",{code:"INVALID_PARAMETER"});return await k.bind(this)("delete-subscription",{endpoint:t.endpoint,keys:t.keys},{auth:true}),"SUCCESS: Unsubscribed from notifications."}async function gc(){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 k.bind(this)("get-vapid-public-key",null,{auth:true})}}async function mc(t,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:r,body:n}=K(t||{},{nullIfEmpty:true}).data;if(!r)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:r,body:n};return e?(typeof e=="string"&&(e=[e]),i.user_ids=e):i.user_ids="all_users",await k.bind(this)("push-notification",i,{auth:true}),"SUCCESS: Notification sent."}async function yc(t){await this.__connection,t=_.Params(t,{spell:"string",name:"string",magic:r=>r},["spell","name"]);await k.bind(this)("castspell",t);return `The spell "${t.spell}" has been cast.`}async function bc(t){return await this.__connection,t=_.Params(t||{},{search:["spell","name",()=>"spell"],value:"string"}),await k.bind(this)("getspell",t)}async function _c(t){await this.__connection,t=_.Params(t,{message:"string",name:"string"},["message","name"]);let e=await k.bind(this)("dopamine",t,{auth:true}),r=e?.previous_message?.message,n=e?.previous_message?.name;if(J())r&&n&&window.alert(`${n} said: ${r}`),window.location.href=e.video;else return r&&n?`${n} said: ${r}
|
|
226
|
+
`),c();})}async function ql(t){let e=_.Params(t,{user_id:n=>_.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 ne.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 P.bind(this)("block-account",e,{auth:true})}async function Vl(t){let e=_.Params(t,{user_id:n=>_.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 ne.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 P.bind(this)("block-account",e,{auth:true})}async function Bl(t){let e=_.Params(t,{user_id:n=>_.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 ne.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 P.bind(this)("remove-account",e,{auth:true})}async function jl(t,e){let r={email:s=>_.Email(s),password:s=>_.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=>_.Birthdate(s),phone_number:s=>_.PhoneNumber(s),picture:s=>{if(s)return _.Url(s)},profile:s=>{if(s)return _.Url(s)},website:s=>{if(s)return _.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=_.Params(t,r,["email"]);if(e=_.Params(e,{confirmation_url:s=>{let o=s;if(typeof s=="string")o=_.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:_.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 ne.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 P.bind(this)("admin-signup",n,{auth:true})}async function Kl(t){let e={email:s=>_.Email(s),password:s=>_.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=>_.Birthdate(s),phone_number:s=>_.PhoneNumber(s),picture:s=>s?_.Url(s):"",profile:s=>s?_.Url(s):"",website:s=>s?_.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}},r=["email","password"],n=_.Params(t,e,r);if(!await ne.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 P.bind(this)("admin-signup",n,{auth:true})}async function $l(t){if(t=_.Params(t,{user_id:r=>_.UserId(r,'"user_id"'),access_group:r=>{try{typeof r=="string"&&(r=parseInt(r));}catch{throw new f('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof r=="number"&&r>0&&r<100)return r;throw new f('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"})}},["user_id","access_group"]),!await ne.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 P.bind(this)("grant-access",t,{auth:true})}async function Hl(t,e){if(t=_.Params(t,{email:"string"}),!await ne.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 P.bind(this)("invitation-list",Object.assign({mode:"search"},t),{fetchOptions:e,auth:true});return n.list=n.list.map(i=>Ft(i.user)),n}async function Gl(t){if(t=_.Params(t,{email:r=>_.Email(r)},["email"]),!await ne.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 P.bind(this)("invitation-list",Object.assign({mode:"cancel"},t),{auth:true})}async function Wl(t){if(t=_.Params(t,{email:r=>_.Email(r)},["email"]),!await ne.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 P.bind(this)("invitation-list",Object.assign({mode:"resend"},t),{auth:true})}async function zl(t){let e=_.Params(t,{user_id:o=>_.UserId(o,'"user_id"'),email:o=>_.Email(o),address:o=>{if(!o)return "";if(typeof o=="string")return o;if(typeof o=="object")return JSON.stringify(o)},name:"string",gender:"string",birthdate:o=>o?_.Birthdate(o):"",phone_number:o=>o?_.PhoneNumber(o):"",misc:"string",picture:o=>o?_.Url(o):"",profile:o=>o?_.Url(o):"",nickname:"string",website:o=>o?_.Url(o):""},["user_id"]),r=e.service,n=e.owner;if(delete e.service,delete e.owner,await this.__connection,this.__user?.user_id&&e.user_id===this.__user.user_id)throw new f("Cannot modify attributes of the current user.",{code:"INVALID_REQUEST"});if(Object.keys(e).filter(o=>o!=="user_id"&&e[o]!==void 0).length===0)throw new f("At least one attribute to update is required.",{code:"INVALID_PARAMETER"});if(!await ne.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 s={attributes:e};return r&&n&&(s.service=r,s.owner=n),await P.bind(this)("admin-edit-profile",s,{auth:true})}async function Jl(t){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,!t.endpoint)throw new f("Missing parameter: endpoint",{code:"INVALID_PARAMETER"});if(!t.keys||!t.keys.p256dh||!t.keys.auth)throw new f("Missing parameter: keys.p256dh or keys.auth",{code:"INVALID_PARAMETER"});return await P.bind(this)("store-subscription",{endpoint:t.endpoint,keys:t.keys},{auth:true}),"SUCCESS: Subscribed to receive notifications."}async function Yl(t){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,!t.endpoint)throw new f("Missing parameter: endpoint",{code:"INVALID_PARAMETER"});if(!t.keys||!t.keys.p256dh||!t.keys.auth)throw new f("Missing parameter: keys.p256dh or keys.auth",{code:"INVALID_PARAMETER"});return await P.bind(this)("delete-subscription",{endpoint:t.endpoint,keys:t.keys},{auth:true}),"SUCCESS: Unsubscribed from notifications."}async function Ql(){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 P.bind(this)("get-vapid-public-key",null,{auth:true})}}async function Xl(t,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:r,body:n}=$(t||{},{nullIfEmpty:true}).data;if(!r)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:r,body:n};return e?(typeof e=="string"&&(e=[e]),i.user_ids=e):i.user_ids="all_users",await P.bind(this)("push-notification",i,{auth:true}),"SUCCESS: Notification sent."}async function Zl(t){await this.__connection,t=_.Params(t,{spell:"string",name:"string",magic:r=>r},["spell","name"]);await P.bind(this)("castspell",t);return `The spell "${t.spell}" has been cast.`}async function eu(t){return await this.__connection,t=_.Params(t||{},{search:["spell","name",()=>"spell"],value:"string"}),await P.bind(this)("getspell",t)}async function tu(t){await this.__connection,t=_.Params(t,{message:"string",name:"string"},["message","name"]);let e=await P.bind(this)("dopamine",t,{auth:true}),r=e?.previous_message?.message,n=e?.previous_message?.name;if(X())r&&n&&window.alert(`${n} said: ${r}`),window.location.href=e.video;else return r&&n?`${n} said: ${r}
|
|
227
227
|
Watch the video here: ${e.video}`:`Your message has been uploaded for future generations to receive.
|
|
228
|
-
Watch the video here: ${e.video}`}var
|
|
228
|
+
Watch the video here: ${e.video}`}var S=class{constructor(e,r,n,i){this.__version="2.2.13";this.project_id="";this.session=null;this.connection=null;this.__my_unique_ids={};this.__uniqueIdsPersistTimer=null;this.userPool=null;this.__socket=null;this.host="skapi";this.hostDomain="skapi.com";this.target_cdn="d3e9syvbtso631";this.customApiDomain="skapi.dev";this.requestBatchSize=50;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 _.UserId(e),!0}catch{return false}},url(e){try{return _.Url(e),!0}catch{return false}},phoneNumber(e){try{return _.PhoneNumber(e),!0}catch{return false}},birthdate(e){try{return _.Birthdate(e),!0}catch{return false}},email(e){try{return _.Email(e),!0}catch{return false}},params(e,r,n){return _.Params(e,r,n)}};this.util={MD5:he,generateRandom:et,toBase62:so,fromBase62:Se,decodeProjectId:Qn,formatServiceId:Xn,extractFormData:$,terminatePendingRequests:La,request:(e,r,n)=>P.bind(this)(e,r,n,{ignoreService:true})};this.__projectIdInput=null;this.__network_logs=false;this.__endpoint_version="v2";this.__public_identifier="";this.bearerToken="";this.registerTicket=fa.bind(this);this.unregisterTicket=ha.bind(this);this.updateTicket=pa.bind(this);if(!e||typeof e!="string")throw this._alert("Service ID is required."),new f("Service ID is required.",{code:"INVALID_PARAMETER"});if(Dl(e)){let o=Nl(),a=null;if(o)try{a=this._resolveProject(o,r,n,i);}catch{ln(o);}if(a)X()&&console.info(`Skapi: "${e}" was replaced with the Project ID entered earlier in this tab (${o}). It is kept in sessionStorage under "${Ut}"; delete that entry to enter a different one.`),this._start(a),this.__connection.catch(()=>ln(o));else if(Fl())this._startAfterProjectIdInput(e,r,n,i);else throw this._alert(`Replace "${e}" with your actual Project ID.`),new f("Project ID is required.",{code:"INVALID_PARAMETER"});return}let s;try{s=this._resolveProject(e,r,n,i);}catch(o){throw this._alert(o.message),o}this._start(s);}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 r of this._userProfileListeners)typeof r=="function"&&r(e);}_runOnLoginListeners(e){for(let r of this._onLoginListeners)typeof r=="function"&&r(e);}get onBatchProcess(){return this._onBatchProcessListeners}set onBatchProcess(e){typeof e=="function"&&this._onBatchProcessListeners.push(e);}_alert(e){X()&&typeof window.alert=="function"&&window.alert(e);}_resolveProject(e,r,n,i){let s=e.split("-").length;if(s===2||s===7)try{let c=Qn(e);n&&typeof n=="object"&&(i=n),r&&typeof r=="object"&&(n=r),r=c.owner,e=c.service;}catch{throw new f("Service ID is invalid.",{code:"INVALID_PARAMETER"})}if(!r||typeof r!="string")throw new f("Owner ID is invalid.",{code:"INVALID_PARAMETER"});if(r!==this.host)try{_.UserId(r,'"owner"');}catch{throw new f("Owner ID is invalid.",{code:"INVALID_PARAMETER"})}return {service:e,owner:r,options:n,__etc:i}}_startAfterProjectIdInput(e,r,n,i){let s=Ml(e,o=>{this._resolveProject(o,r,n,i);}).then(o=>{Ol(o),this._start(this._resolveProject(o,r,n,i)),this.__connection.catch(()=>ln(o));});this.__projectIdInput=s,this.admin_endpoint=s.then(()=>this.admin_endpoint),this.record_endpoint=s.then(()=>this.record_endpoint),this.__authConnection=s.then(()=>this.__authConnection),this.__connection=s.then(()=>this.__connection);for(let o of [s,this.admin_endpoint,this.record_endpoint,this.__authConnection,this.__connection])o.catch(()=>{});}_start({service:e,owner:r,options:n,__etc:i}){this.service=e,this.owner=r;try{this.project_id=Xn(e,r);}catch{this.project_id="";}let s=true,o=false,a=null;if(n&&(typeof n.refetchServiceInfo=="boolean"&&(o=n.refetchServiceInfo),typeof n.autoLogin=="boolean"&&(s=n.autoLogin),n.encryption&&(a=ko(n.encryption)),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`,l=e.substring(0,4);this.admin_endpoint=fetch(`${c}/${l}/admin-${this.__endpoint_version}.json`).then(g=>g.blob()).then(g=>new Promise((m,b)=>{let y=new FileReader;y.onloadend=()=>m(y.result),y.onerror=b,y.readAsDataURL(g);})).then(g=>{try{return typeof g=="string"?JSON.parse(atob(g.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}/${l}/record-${this.__endpoint_version}.json`).then(g=>g.blob()).then(g=>new Promise((m,b)=>{let y=new FileReader;y.onloadend=()=>m(y.result),y.onerror=b,y.readAsDataURL(g);})).then(g=>{try{return typeof g=="string"?JSON.parse(atob(g.split(",")[1])):null}catch{throw new f("Service does not exist. Create your service from skapi.com",{code:"NOT_EXISTS"})}});let d=X();if(d&&!window.sessionStorage)throw this._alert("This browser is not supported."),new Error("This browser is not supported.");let h=d?JSON.parse(window.sessionStorage.getItem(`${e}#${r}`)||"null"):null;if(this.log("constructor:restore",h),h?.connection){for(let g in h)this[g]=h[g];h.__public_identifier||(this.__public_identifier=`${this.service}:${this.owner}:${et(16)}`);}Co.bind(this)(a),this.__authConnection=(async()=>{let g=await this.admin_endpoint,m={UserPoolId:g.userpool_id,ClientId:g.userpool_client};Yn()&&(m.Storage=window.localStorage),this.userPool=new Gn(m);try{this.user||await re.bind(this)().getSession({skipUserUpdateEventTrigger:!0}),this.user&&(!h?.connection&&!s?je.bind(this)():(a&&Jo.bind(this)(),this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user)));}catch{}})();let u=`${this.service}/${this.owner}`,p=d?window.sessionStorage.getItem(`${u}:uniqueids`):null;if(p)try{let g=JSON.parse(p);this.__my_unique_ids=g&&typeof g=="object"&&!Array.isArray(g)?{[u]:g}:{};}catch{this.__my_unique_ids={};}this.__connection=(async()=>{let g=null;await this.record_endpoint,h?.connection||(g=this._updateConnection({refresh:o}));let m=()=>{if(this.__class_properties_has_been_cached)return;let b=()=>{let y={},E=["__startKeyHistory","__disabledAccount","__cached_requests","__request_signup_confirmation","__public_identifier","connection"];if(this.connection){for(let w of E)y[w]=this[w];if(a&&(y.__cached_requests={},y.__startKeyHistory={}),d){let w=`${e}#${r}`;try{window.sessionStorage.setItem(w,JSON.stringify(y));}catch{try{let R=Object.assign({},y,{__cached_requests:{},__startKeyHistory:{}});window.sessionStorage.setItem(w,JSON.stringify(R));}catch{try{window.sessionStorage.removeItem(w);}catch{}}}}this.__class_properties_has_been_cached=true;}};return g instanceof Promise?g.then(()=>b()):b()};return d&&(window.addEventListener("beforeunload",()=>{this.closeRealtime(),m();}),window.addEventListener("visibilitychange",()=>{m();})),await g,await this.__authConnection,this.connection})(),this.__connection.then(g=>{((g?.group||0)<3||this.__network_logs)&&this.version();}).catch(()=>{});}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||(X()&&typeof window.navigator?.userAgent=="string"?window.navigator.userAgent:`skapi-node/${globalThis?.process?.versions?.node||"unknown"}`);return {project_id:this.project_id,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||"",conf:n?.opt}}async _updateConnection(e){let r=e?.refresh||false;try{this.connection=await P.bind(this)("service",{service:this.service,owner:this.owner,refresh:r},{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,X()){let r=`Built with:
|
|
229
229
|
%c\r
|
|
230
230
|
##\\ ##\\ \r
|
|
231
231
|
## | \\__|\r
|
|
@@ -238,7 +238,7 @@ Watch the video here: ${e.video}`}var T=class{constructor(e,r,n,i){this.__versio
|
|
|
238
238
|
## | \r
|
|
239
239
|
## | \r
|
|
240
240
|
\\__| \r
|
|
241
|
-
Version: ${this.__version}`;console.log(r,"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,r){if(this.__network_logs){if(r!==null&&typeof r=="object")try{
|
|
241
|
+
Version: ${this.__version}`;console.log(r,"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,r){if(this.__network_logs){if(r!==null&&typeof r=="object")try{X()?r=JSON.parse(JSON.stringify(r)):r=JSON.stringify(r,null,2);}catch{r=String(r);}else typeof r=="string"&&r.length>100&&(r=r.substring(0,100)+"...");console.log(`%c${e}:`,"color: blue;",r);}}getFeed(e,r){return wl.bind(this)(e,r)}closeRTC(e){return Ce.bind(this)(e)}connectRTC(e,r){return Mc.bind(this)(e,r)}connectRealtime(e){return Ct.bind(this)(e)}spellcast(e){return Zl.bind(this)(e)}getspell(e){return eu.bind(this)(e)}dopamine(e){return tu.bind(this)(e)}getUniqueId(e,r){return rc.bind(this)(e,r)}resendInvitation(e){return Wl.bind(this)(e)}cancelInvitation(e){return Gl.bind(this)(e)}getInvitations(e,r){return Hl.bind(this)(e,r)}openIdLogin(e){return ma.bind(this)(e)}loginWithToken(e){return ya.bind(this)(e)}registerNewsletterGroup(e){return Pl.bind(this)(e)}deleteNewsletterGroup(e){return kl.bind(this)(e)}clientSecretRequest(e){return ul.bind(this)(e)}clientSecretRequestHistory(e,r){return Wi.bind(this)(e,r)}clientSecretRequestStream(e,r){return Ji.bind(this)(e,r)}clientSecretRequestFinalize(e,r,n){return Yi.bind(this)(e,r,n)}cancelClientSecretRequest(e){return zi.bind(this)(e)}stopClientSecretPolling(e){return cn.bind(this)(e||{})}isPollStopped(e){return Hi(e)}clientSecretRequestQueueCount(e){return Gi.bind(this)(e)}forwardRequestHistory(e,r){return hl.bind(this)(e,r)}forwardRequestStream(e,r){return dl.bind(this)(e,r)}forwardRequestFinalize(e,r,n){return fl.bind(this)(e,r,n)}cancelForwardRequest(e){return pl.bind(this)(e)}stopForwardRequestPolling(e){return gl.bind(this)(e||{})}forwardRequestQueueCount(e){return ml.bind(this)(e)}consumeTicket(e){return ca.bind(this)(e)}getConsumedTickets(e,r){return da.bind(this)(e,r)}getTickets(e,r){return la.bind(this)(e,r)}clearTicketLog(e){return ua.bind(this)(e)}closeRealtime(){return sn.bind(this)()}getRealtimeUsers(e,r){return Gc.bind(this)(e,r)}sendInquiry(e){return yl.bind(this)(e)}blockAccount(e){return ql.bind(this)(e)}unblockAccount(e){return Vl.bind(this)(e)}deleteAccount(e){return Bl.bind(this)(e)}inviteUser(e,r){return jl.bind(this)(e,r)}createAccount(e){return Kl.bind(this)(e)}grantAccess(e){return $l.bind(this)(e)}updateUserAttributes(e){return zl.bind(this)(e)}getRealtimeGroups(e,r){return Wc.bind(this)(e,r)}newsletterGroupEndpoint(){return Cl.bind(this)()}postRealtime(e,r,n){return Hc.bind(this)(e,r,n)}joinRealtime(e){return xt.bind(this)(e)}getProfile(e){return ga.bind(this)(e)}getFile(e,r){return Ke.bind(this)(e,r)}secureRequest(e,r){return bl.bind(this)(e,r)}forwardRequest(e,r){return ll.bind(this)(e,r)}getFormResponse(){return qa.bind(this)()}getRecords(e,r){return Xa.bind(this)(e,r)}getTables(e,r){return Za.bind(this)(e,r)}getIndexes(e,r){return ec.bind(this)(e,r)}getTags(e,r){return tc.bind(this)(e,r)}deleteRecords(e,r){return nc.bind(this)(e,r)}resendSignupConfirmation(){return ba.bind(this)()}recoverAccount(e=false){return _a.bind(this)(e)}getUsers(e,r){return ka.bind(this)(e,r)}disableAccount(){return Ea.bind(this)()}lastVerifiedEmail(e){return Ca.bind(this)(e)}unsubscribeNewsletter(e){return xl.bind(this)(e)}subscribeNotification(e,r){return Jl.bind(this)({endpoint:e,keys:r})}unsubscribeNotification(e,r){return Yl.bind(this)({endpoint:e,keys:r})}vapidPublicKey(){return Ql.bind(this)()}pushNotification(e,r){return Xl.bind(this)(e,r)}getNewsletters(e,r){return Ul.bind(this)(e,r)}getNewsletterSubscription(e,r){return vl.bind(this)(e,r)}getEncryptionStatus(){return xo.bind(this)()}isWithheld(e){return fi.call(this,e)}unlockEncryption(e){return $o.bind(this)(e)}lockEncryption(e){return Ho.bind(this)(e)}takeRecoveryCode(){return ea.bind(this)()}unlockWithRecoveryCode(e){return ta.bind(this)(e)}regenerateRecoveryCode(){return ra.bind(this)()}pinPeerKey(e){return Xo.bind(this)(e)}grantPrivateRecordAccess(e){return ic.bind(this)(e)}removePrivateRecordAccess(e){return sc.bind(this)(e)}listPrivateRecordAccess(e,r){return oc.bind(this)(e,r)}requestPrivateRecordAccessKey(e){return ac.bind(this)(e)}deleteFiles(e){return za.bind(this)(e)}uploadFiles(e,r){return Zt.bind(this)(e,r)}mock(e,r){return _l.bind(this)(e,r)}login(e){return Si.bind(this)(e)}logout(e){return Jt.bind(this)(e)}signup(e,r){return wa.bind(this)(e,r)}resetPassword(e){return Aa.bind(this)(e)}verifyEmail(e,r){return Sa.bind(this)(e,r)}verifyPhoneNumber(e,r){return Ta.bind(this)(e,r)}forgotPassword(e,r){return va.bind(this)(e,r)}changePassword(e){return Ia.bind(this)(e)}updateProfile(e){return Pa.bind(this)(e)}postRecord(e,r,n){return Fi.bind(this)(e,r,n)}postRecords(e){return lc.bind(this)(e)}getSubscriptions(e,r){return El.bind(this)(e,r)}subscribe(e){return Al.bind(this)(e)}unsubscribe(e){return Rl.bind(this)(e)}blockSubscriber(e){return Tl.bind(this)(e)}unblockSubscriber(e){return Sl.bind(this)(e)}subscribeNewsletter(e){return Il.bind(this)(e)}bulkPostRecords(e){return Oi.bind(this)(e)}};k([C()],S.prototype,"getFeed"),k([C()],S.prototype,"closeRTC"),k([C()],S.prototype,"connectRTC"),k([C()],S.prototype,"spellcast"),k([C()],S.prototype,"getspell"),k([C()],S.prototype,"dopamine"),k([C()],S.prototype,"getUniqueId"),k([C()],S.prototype,"resendInvitation"),k([C()],S.prototype,"cancelInvitation"),k([C()],S.prototype,"getInvitations"),k([C()],S.prototype,"openIdLogin"),k([C()],S.prototype,"loginWithToken"),k([C()],S.prototype,"registerNewsletterGroup"),k([C()],S.prototype,"deleteNewsletterGroup"),k([C()],S.prototype,"clientSecretRequest"),k([C()],S.prototype,"clientSecretRequestHistory"),k([C()],S.prototype,"cancelClientSecretRequest"),k([C()],S.prototype,"forwardRequestHistory"),k([C()],S.prototype,"cancelForwardRequest"),k([C()],S.prototype,"consumeTicket"),k([C()],S.prototype,"getConsumedTickets"),k([C()],S.prototype,"getTickets"),k([C()],S.prototype,"clearTicketLog"),k([C()],S.prototype,"getRealtimeUsers"),k([C()],S.prototype,"sendInquiry"),k([C()],S.prototype,"blockAccount"),k([C()],S.prototype,"unblockAccount"),k([C()],S.prototype,"deleteAccount"),k([C()],S.prototype,"inviteUser"),k([C()],S.prototype,"createAccount"),k([C()],S.prototype,"grantAccess"),k([C()],S.prototype,"updateUserAttributes"),k([C()],S.prototype,"getRealtimeGroups"),k([C()],S.prototype,"newsletterGroupEndpoint"),k([C()],S.prototype,"postRealtime"),k([C()],S.prototype,"joinRealtime"),k([C()],S.prototype,"getProfile"),k([C()],S.prototype,"getFile"),k([C()],S.prototype,"secureRequest"),k([C()],S.prototype,"forwardRequest"),k([C()],S.prototype,"getFormResponse"),k([C()],S.prototype,"getRecords"),k([C()],S.prototype,"getTables"),k([C()],S.prototype,"getIndexes"),k([C()],S.prototype,"getTags"),k([C()],S.prototype,"deleteRecords"),k([C()],S.prototype,"resendSignupConfirmation"),k([C()],S.prototype,"recoverAccount"),k([C()],S.prototype,"getUsers"),k([C()],S.prototype,"disableAccount"),k([C()],S.prototype,"lastVerifiedEmail"),k([C()],S.prototype,"unsubscribeNewsletter"),k([C()],S.prototype,"subscribeNotification"),k([C()],S.prototype,"unsubscribeNotification"),k([C()],S.prototype,"vapidPublicKey"),k([C()],S.prototype,"pushNotification"),k([C()],S.prototype,"getNewsletters"),k([C()],S.prototype,"getNewsletterSubscription"),k([C()],S.prototype,"unlockEncryption"),k([C()],S.prototype,"unlockWithRecoveryCode"),k([C()],S.prototype,"grantPrivateRecordAccess"),k([C()],S.prototype,"removePrivateRecordAccess"),k([C()],S.prototype,"listPrivateRecordAccess"),k([C()],S.prototype,"requestPrivateRecordAccessKey"),k([C()],S.prototype,"deleteFiles"),k([C()],S.prototype,"uploadFiles"),k([C()],S.prototype,"mock"),k([C({preventMultipleCalls:true})],S.prototype,"login"),k([C()],S.prototype,"logout"),k([C({preventMultipleCalls:true})],S.prototype,"signup"),k([C({preventMultipleCalls:true})],S.prototype,"resetPassword"),k([C({preventMultipleCalls:true})],S.prototype,"verifyEmail"),k([C({preventMultipleCalls:true})],S.prototype,"verifyPhoneNumber"),k([C({preventMultipleCalls:true})],S.prototype,"forgotPassword"),k([C({preventMultipleCalls:true})],S.prototype,"changePassword"),k([C({preventMultipleCalls:true})],S.prototype,"updateProfile"),k([C()],S.prototype,"postRecord"),k([C()],S.prototype,"getSubscriptions"),k([C()],S.prototype,"subscribe"),k([C()],S.prototype,"unsubscribe"),k([C()],S.prototype,"blockSubscriber"),k([C()],S.prototype,"unblockSubscriber"),k([C()],S.prototype,"subscribeNewsletter");var Qi={};var un=typeof globalThis<"u"?globalThis:void 0;un&&(un.Skapi=S,un.SkapiError=f,un.SkapiTypes=Qi);/*! Bundled license information:
|
|
242
242
|
|
|
243
243
|
ieee754/index.js:
|
|
244
244
|
(*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> *)
|
|
@@ -288,5 +288,5 @@ amazon-cognito-identity-js/es/index.js:
|
|
|
288
288
|
|
|
289
289
|
js-cookie/dist/js.cookie.mjs:
|
|
290
290
|
(*! js-cookie v3.0.8 | MIT *)
|
|
291
|
-
*/export{
|
|
291
|
+
*/export{S as Skapi,f as SkapiError,Qi as Types};//# sourceMappingURL=skapi.browser.mjs.map
|
|
292
292
|
//# sourceMappingURL=skapi.browser.mjs.map
|