skapi-js 1.5.0 → 1.5.2-beta.0

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.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import {CognitoUserPool,AuthenticationDetails,CognitoUserSession,CognitoRefreshToken,CognitoAccessToken,CognitoIdToken,CognitoUser,CognitoUserAttribute}from'amazon-cognito-identity-js';import Zn from'cocochex';import fr from'qpass';/**
1
+ import {CognitoUserPool,AuthenticationDetails,CognitoUserSession,CognitoRefreshToken,CognitoAccessToken,CognitoIdToken,CognitoUser,CognitoUserAttribute}from'amazon-cognito-identity-js';import er from'cocochex';import pr from'qpass';/**
2
2
  * @license
3
3
  Apache License
4
4
  Version 2.0, January 2004
@@ -203,7 +203,7 @@ import {CognitoUserPool,AuthenticationDetails,CognitoUserSession,CognitoRefreshT
203
203
  limitations under the License.
204
204
 
205
205
  */
206
- var Nn=Object.defineProperty;var Cn=Object.getOwnPropertyDescriptor;var ee=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var w=(n,e,t,i)=>{for(var r=Cn(e,t),s=n.length-1,o;s>=0;s--)(o=n[s])&&(r=(o(e,t,r))||r);return r&&Nn(e,t,r),r};var J=typeof globalThis<"u"?globalThis:void 0,he=J?.window;function Ln(n){if(Buffer)return Buffer.from(n).toString("base64");let e="",t=new Uint8Array(n),i=32768;for(let r=0;r<t.length;r+=i){let s=t.subarray(r,r+i);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(he)he.global=he,he.global._runningInNodeJS=false;else if(J&&(J.global=J,typeof J.window>"u")){class n{constructor(){this.result=null;this.error=null;this.onload=null;this.onloadend=null;this.onerror=null;}readAsDataURL(i){i.arrayBuffer().then(r=>{let s=Ln(r),o=i.type||"application/octet-stream";this.result=`data:${o};base64,${s}`,this.onload&&this.onload({target:this}),this.onloadend&&this.onloadend({target:this});}).catch(r=>{this.error=r,this.onerror&&this.onerror({target:this});});}readAsArrayBuffer(i){i.arrayBuffer().then(r=>{this.result=r,this.onload&&this.onload({target:this}),this.onloadend&&this.onloadend({target:this});}).catch(r=>{this.error=r,this.onerror&&this.onerror({target:this});});}readAsText(i,r="utf-8"){i.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});});}}J.FileReader=n;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(i,r){this._method=i,this._url=r,this.readyState=1;}setRequestHeader(i,r){this._headers[i]=r;}getResponseHeader(i){return null}abort(){this._aborted=true,this.onabort&&this.onabort({});}send(i){if(this._aborted)return;let r={method:this._method,headers:this._headers};i&&this._method!=="GET"&&this._method!=="HEAD"&&(r.body=i),fetch(this._url,r).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);});}}J.XMLHttpRequest=e,J.window={_runningInNodeJS:true,alert:t=>console.error("[Alert]",t),sessionStorage:{getItem:t=>null,setItem:(t,i)=>{},removeItem:t=>{}},localStorage:{getItem:t=>{let i=ee("fs"),r=ee("path");try{let s=r.resolve(process.cwd(),"states","localStorage",`${t}.skapi`);return i.existsSync(s)?i.readFileSync(s,"utf8"):null}catch{return null}},setItem:(t,i)=>{let r=ee("fs"),s=ee("path");try{let o=s.resolve(process.cwd(),"states","localStorage");r.existsSync(o)||r.mkdirSync(o,{recursive:!0});let c=s.resolve(o,`${t}.skapi`);r.writeFileSync(c,i,"utf8");}catch{}},removeItem:t=>{let i=ee("fs"),r=ee("path");try{let s=r.resolve(process.cwd(),"states","localStorage",`${t}.skapi`);i.existsSync(s)&&i.unlinkSync(s);}catch{}}},location:{href:"",origin:"",hostname:"",protocol:"",replace:t=>{}},navigator:{userAgent:`nodejs/${J?.process?.versions?.node||"unknown"}`,mediaDevices:{getUserMedia:async t=>{throw new Error("getUserMedia is not supported in Node.js environment.")}}},addEventListener:()=>{},removeEventListener:()=>{}};}var a=class extends Error{constructor(e,t){if(Array.isArray(e)&&e.length<=2){let i=e[1];if(e.length>2)for(let r=2;r<e.length&&typeof e[r]=="string";r++)i+=e[r];super((i||"Something went wrong.").trim()),this.name=t?.name||"SKAPI",this.code=t?.code||e[0]||"ERROR",t?.cause&&(this.cause=t.cause);}else super((e?.message||(typeof e=="string"?e:"Something went wrong.")).trim()),typeof e=="string"?(this.name=t?.name||"SKAPI",this.code=t?.code||"ERROR",t?.cause&&(this.cause=t.cause)):e instanceof Error?(this.cause=e,this.name=e.name,e.hasOwnProperty("code")&&(this.code=e.code)):typeof e=="object"&&e?.code&&e?.message&&(this.name=t?.name||"SKAPI",this.code=t?.code||"ERROR",this.cause=e?.cause);}};var z="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",xe=BigInt(z.length),On=2*1024*1024,Fn=["aud","cognito:username","event_id","exp","iat","iss","jti","origin_jti","secret_key","token_use"],Ke={auth_time:"log",sub:"user_id"},Mn=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f","g","h","i","j","k","l"],ze=["us31","us72","ap51","ap22","ap41","eu71","ap21","us32","us71","af51","ap31","ap43","ap23","ap42","ca01","eu01","eu72","eu51","eu73","eu11","me51","sa31"],Qe=typeof TextEncoder<"u"?new TextEncoder:null;function Vn(){if(typeof globalThis<"u")return globalThis.Buffer}function $n(n){if(Qe)return Qe.encode(n);let e=unescape(encodeURIComponent(n)),t=new Uint8Array(e.length);for(let i=0;i<e.length;i++)t[i]=e.charCodeAt(i);return t}function qn(n){if(n instanceof Uint8Array)return n;if(typeof n=="string")return $n(n);if(typeof ArrayBuffer<"u"&&n instanceof ArrayBuffer)return new Uint8Array(n);if(typeof ArrayBuffer<"u"&&ArrayBuffer.isView(n))return new Uint8Array(n.buffer,n.byteOffset,n.byteLength);if(Array.isArray(n))return Uint8Array.from(n);let e=Vn();if(e)return new Uint8Array(e.from(n));throw new Error("No byte conversion available in this environment.")}var m=class m{static hash(e){typeof e!="string"&&(console.warn("coercing non-string value to empty string"),e="");let t=m.sb(e),i=1732584193,r=-271733879,s=-1732584194,o=271733878,c,l,d,h;for(let u=0;u<t.length;u+=16)c=i,l=r,d=s,h=o,i=m.ff(i,r,s,o,t[u],7,-680876936),o=m.ff(o,i,r,s,t[u+1],12,-389564586),s=m.ff(s,o,i,r,t[u+2],17,606105819),r=m.ff(r,s,o,i,t[u+3],22,-1044525330),i=m.ff(i,r,s,o,t[u+4],7,-176418897),o=m.ff(o,i,r,s,t[u+5],12,1200080426),s=m.ff(s,o,i,r,t[u+6],17,-1473231341),r=m.ff(r,s,o,i,t[u+7],22,-45705983),i=m.ff(i,r,s,o,t[u+8],7,1770035416),o=m.ff(o,i,r,s,t[u+9],12,-1958414417),s=m.ff(s,o,i,r,t[u+10],17,-42063),r=m.ff(r,s,o,i,t[u+11],22,-1990404162),i=m.ff(i,r,s,o,t[u+12],7,1804603682),o=m.ff(o,i,r,s,t[u+13],12,-40341101),s=m.ff(s,o,i,r,t[u+14],17,-1502002290),r=m.ff(r,s,o,i,t[u+15],22,1236535329),i=m.gg(i,r,s,o,t[u+1],5,-165796510),o=m.gg(o,i,r,s,t[u+6],9,-1069501632),s=m.gg(s,o,i,r,t[u+11],14,643717713),r=m.gg(r,s,o,i,t[u],20,-373897302),i=m.gg(i,r,s,o,t[u+5],5,-701558691),o=m.gg(o,i,r,s,t[u+10],9,38016083),s=m.gg(s,o,i,r,t[u+15],14,-660478335),r=m.gg(r,s,o,i,t[u+4],20,-405537848),i=m.gg(i,r,s,o,t[u+9],5,568446438),o=m.gg(o,i,r,s,t[u+14],9,-1019803690),s=m.gg(s,o,i,r,t[u+3],14,-187363961),r=m.gg(r,s,o,i,t[u+8],20,1163531501),i=m.gg(i,r,s,o,t[u+13],5,-1444681467),o=m.gg(o,i,r,s,t[u+2],9,-51403784),s=m.gg(s,o,i,r,t[u+7],14,1735328473),r=m.gg(r,s,o,i,t[u+12],20,-1926607734),i=m.hh(i,r,s,o,t[u+5],4,-378558),o=m.hh(o,i,r,s,t[u+8],11,-2022574463),s=m.hh(s,o,i,r,t[u+11],16,1839030562),r=m.hh(r,s,o,i,t[u+14],23,-35309556),i=m.hh(i,r,s,o,t[u+1],4,-1530992060),o=m.hh(o,i,r,s,t[u+4],11,1272893353),s=m.hh(s,o,i,r,t[u+7],16,-155497632),r=m.hh(r,s,o,i,t[u+10],23,-1094730640),i=m.hh(i,r,s,o,t[u+13],4,681279174),o=m.hh(o,i,r,s,t[u],11,-358537222),s=m.hh(s,o,i,r,t[u+3],16,-722521979),r=m.hh(r,s,o,i,t[u+6],23,76029189),i=m.hh(i,r,s,o,t[u+9],4,-640364487),o=m.hh(o,i,r,s,t[u+12],11,-421815835),s=m.hh(s,o,i,r,t[u+15],16,530742520),r=m.hh(r,s,o,i,t[u+2],23,-995338651),i=m.ii(i,r,s,o,t[u],6,-198630844),o=m.ii(o,i,r,s,t[u+7],10,1126891415),s=m.ii(s,o,i,r,t[u+14],15,-1416354905),r=m.ii(r,s,o,i,t[u+5],21,-57434055),i=m.ii(i,r,s,o,t[u+12],6,1700485571),o=m.ii(o,i,r,s,t[u+3],10,-1894986606),s=m.ii(s,o,i,r,t[u+10],15,-1051523),r=m.ii(r,s,o,i,t[u+1],21,-2054922799),i=m.ii(i,r,s,o,t[u+8],6,1873313359),o=m.ii(o,i,r,s,t[u+15],10,-30611744),s=m.ii(s,o,i,r,t[u+6],15,-1560198380),r=m.ii(r,s,o,i,t[u+13],21,1309151649),i=m.ii(i,r,s,o,t[u+4],6,-145523070),o=m.ii(o,i,r,s,t[u+11],10,-1120210379),s=m.ii(s,o,i,r,t[u+2],15,718787259),r=m.ii(r,s,o,i,t[u+9],21,-343485551),i=m.ad(i,c),r=m.ad(r,l),s=m.ad(s,d),o=m.ad(o,h);return m.rh(i)+m.rh(r)+m.rh(s)+m.rh(o)}static rh(e){let t="";for(let i=0;i<=3;i++)t+=m.alphabet.charAt(e>>i*8+4&15)+m.alphabet.charAt(e>>i*8&15);return t}static ad(e,t){let i=(e&65535)+(t&65535);return (e>>16)+(t>>16)+(i>>16)<<16|i&65535}static rl(e,t){return e<<t|e>>>32-t}static cm(e,t,i,r,s,o){return m.ad(m.rl(m.ad(m.ad(t,e),m.ad(r,o)),s),i)}static ff(e,t,i,r,s,o,c){return m.cm(t&i|~t&r,e,t,s,o,c)}static gg(e,t,i,r,s,o,c){return m.cm(t&r|i&~r,e,t,s,o,c)}static hh(e,t,i,r,s,o,c){return m.cm(t^i^r,e,t,s,o,c)}static ii(e,t,i,r,s,o,c){return m.cm(i^(t|~r),e,t,s,o,c)}static sb(e){let t,i=(e.length+8>>6)+1,r=new Array(i*16);for(t=0;t<i*16;t++)r[t]=0;for(t=0;t<e.length;t++)r[t>>2]|=e.charCodeAt(t)<<t%4*8;return r[t>>2]|=128<<t%4*8,r[i*16-2]=e.length*8,r}};m.alphabet="0123456789abcdef";var V=m;function Ge(n){if(n===0)return z[0];let e="";for(;n>0;)e=z[n%62]+e,n=Math.floor(n/62);return e}function B(n){return n.split("").reverse().reduce((e,t,i)=>e+z.indexOf(t)*62**i,0)}function oe(n=6){let e="",t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",i=t.length,r=0;for(;r<n;)e+=t.charAt(Math.floor(Math.random()*i)),r+=1;return e}function ve(){return typeof window>"u"||!!window?._runningInNodeJS}function $(){return !ve()&&typeof document<"u"&&typeof document.createElement=="function"}function pe(n){let e;try{e=JSON.stringify(n);}catch{throw new a("Invalid data type.",{code:"INVALID_REQUEST"})}if(new Blob([e]).size>On)throw new a("Data should not exceed 2MB",{code:"INVALID_REQUEST"})}function We(n){return n===""||n==="on"||n==="true"}function He(n){return n==="false"}function Je(n,e,t){e.name&&t(n,e.name,e.value);}var me=$(),jn=typeof SubmitEvent<"u",Bn=typeof HTMLFormElement<"u";function D(n,e,t){let i={},r=[];function s(l,d,h){if(e?.ignoreEmpty&&h==="")return;if(e?.nullIfEmpty&&h===""&&(h=null),typeof t=="function"){let A=t(d,h);A!==void 0&&(h=A);}let u=d.split("[").map(A=>{let f=A.replace("]",""),y=Number(f);return !isNaN(y)&&!f.includes(".")?f=y:(f[0]==='"'&&f[f.length-1]==='"'||f[0]==="'"&&f[f.length-1]==="'")&&(f=f.replace(/"/g,"").replace(/'/g,"")),f}),p=l;if(typeof u[0]=="number")throw new a("Form key cannot start with an array index.",{code:"INVALID_REQUEST"});for(let A=0;A<u.length;A++){let f=u[A];A<u.length-1?(p[f]===void 0&&(typeof u[A+1]=="number"?p[f]=[]:p[f]={}),p=p[f]):p[f]===void 0?p[f]=h:Array.isArray(p[f])?p[f].push(h):p[f]=[p[f],h];}}function o(l,d,h){if(h instanceof File)l.push({name:d,file:h});else if(h instanceof FileList&&h&&h.length>0)for(let u=0;u<=h.length-1;u++){let p=h.item(u);p&&l.push({name:d,file:p});}}let c=l=>{l.name&&(l.type==="number"?l.value&&s(i,l.name,Number(l.value)):l.type==="checkbox"||l.type==="radio"?l.checked?l.type==="checkbox"&&l.value===""||We(l.value)?s(i,l.name,true):He(l.value)?s(i,l.name,false):l.value&&s(i,l.name,l.value):l.type==="checkbox"&&(We(l.value)?s(i,l.name,false):He(l.value)&&s(i,l.name,true)):l.type==="file"?l.files&&l.files.length>0&&o(r,l.name,l.files):s(i,l.name,l.value));};if(me&&(n instanceof HTMLInputElement||n instanceof HTMLSelectElement||n instanceof HTMLTextAreaElement))return c(n),pe(i),{data:i,files:r};if(me&&n instanceof FormData){for(let l of n.entries()){let d=l[0],h=l[1];if(h instanceof File||h instanceof FileList)o(r,d,h);else if(h instanceof Blob){let u=h;if(u.type==="application/json")try{let p=JSON.parse(u.text());s(i,d,p);}catch{s(i,d,u);}}else s(i,d,h);}return pe(i),{data:i,files:r}}if(me&&jn&&n instanceof SubmitEvent&&(n=n.target),me&&Bn&&n instanceof HTMLFormElement){let l=n.querySelectorAll("input"),d=n.querySelectorAll("select"),h=n.querySelectorAll("textarea");for(let u=0;u<d.length;u++)Je(i,d[u],s);for(let u=0;u<h.length;u++)Je(i,h[u],s);for(let u=0;u<l.length;u++)c(l[u]);return pe(i),{data:i,files:r}}return pe(n),{data:n,files:r}}function ae(n){let e={};for(let t in n){let i=n[t];if(!Fn.includes(t))if(Ke[t])e[Ke[t]]=i;else if(t.includes("custom:"))e[t.replace("custom:","")]=i;else if(t==="address"){let r=i;if(r&&typeof r=="object"&&Object.keys(r).length){if(r?.formatted)try{e[t]=JSON.parse(r.formatted);}catch{e[t]=r.formatted;}}else e[t]=r;}else e[t]=i;}for(let t of ["address_public","birthdate_public","email_public","gender_public","phone_number_public","access_group"])t.includes("_public")?e.hasOwnProperty(t.split("_")[0])?e[t]=e.hasOwnProperty(t)?!!Number(e[t]):false:delete e[t]:e[t]=e.hasOwnProperty(t)?Number(e[t]):0;for(let t of ["email","phone_number"])e.hasOwnProperty(t)?e[t+"_verified"]=e[t+"_verified"]===true:delete e[t+"_verified"];return e}function De(n){if(n=Xn(n),n.split("-").length===7){let e=n.split("-"),t,i;try{t=ze[B(e[1][0])],i=e.slice(2).join("-");}catch{throw new Error("INVALID_PARAMETER: Service ID is invalid.")}if(!t)throw new Error("INVALID_PARAMETER: Service ID is invalid.");return {service:t+e[0]+e[1].slice(1),owner:i}}return {service:n,owner:""}}function Xe(n,e){let t=ze.indexOf(n.slice(0,4)),i=Mn[t],s=`${n.slice(4,-4)}-${i}${n.slice(-4)}-${e}`;return Gn(s)}function Kn(n){let e=0n;for(let t of n){let i=z.indexOf(t);if(i<0)throw new Error(`INVALID_PARAMETER: Invalid base62 character: ${t}`);e=e*xe+BigInt(i);}return e}function Qn(n,e=1){if(n<0n)throw new Error("INVALID_PARAMETER: Negative values are not supported.");if(n===0n)return "0".repeat(Math.max(1,e));let t="",i=n;for(;i>0n;){let r=Number(i%xe);t=z[r]+t,i/=xe;}return t.length<e&&(t="0".repeat(e-t.length)+t),t}function Wn(n){if(n===0n)return Uint8Array.from([0]);let e=[],t=n;for(;t>0n;)e.push(Number(t&0xffn)),t>>=8n;return e.reverse(),Uint8Array.from(e)}function Hn(n){let e=0n;for(let t of n)e=(e<<8n)+BigInt(t);return e}function Jn(n){let e=String(n).replace(/-/g,"");if(!/^[0-9a-fA-F]{32}$/.test(e))throw new Error("INVALID_PARAMETER: Invalid UUID format.");let t=new Uint8Array(16);for(let i=0;i<16;i++)t[i]=parseInt(e.slice(i*2,i*2+2),16);return t}function zn(n){let e=Array.from(qn(n),t=>t.toString(16).padStart(2,"0")).join("");return [e.slice(0,8),e.slice(8,12),e.slice(12,16),e.slice(16,20),e.slice(20)].join("-")}function Gn(n){let e=String(n);if(e.split("-").length===2)return e;let t=e.match(/^([0-9A-Za-z]+)-([0-9A-Za-z]+)-([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/);if(!t)throw new Error("INVALID_PARAMETER: Input must match <base62>-<base62>-<uuid>.");let[,i,r,s]=t;if(i.length<2)throw new Error("INVALID_PARAMETER: The first part must contain at least 2 characters.");if(r.length>=z.length)throw new Error("INVALID_PARAMETER: The middle section is too long to encode.");let o=i.slice(0,2),c=i.slice(2),l=r+o,d=z[r.length]+c+l,h=Jn(s),u=Qn(Hn(h));return `${d}-${u}`}function Xn(n){let e=String(n);if(e.split("-").length!==2)return e;let t=e.split("-");if(t.length!==2||!t[0]||!t[1])throw new Error("INVALID_PARAMETER: Corrupt compressed token.");let[i,r]=t,s=z.indexOf(i[0]);if(s<0)throw new Error("INVALID_PARAMETER: Corrupt compressed token.");let o=i.slice(1),c=s+2;if(o.length<c)throw new Error("INVALID_PARAMETER: Corrupt compressed token.");let l=o.slice(0,o.length-c),d=o.slice(o.length-c),h=d.slice(s),u=d.slice(0,s),p=h+l;if(!/^[0-9A-Za-z]+$/.test(p)||!/^[0-9A-Za-z]+$/.test(u))throw new Error("INVALID_PARAMETER: Corrupt compressed token.");let A=Kn(r),f=Wn(A);if(f.length>16)throw new Error("INVALID_PARAMETER: Corrupt compressed token.");let y=new Uint8Array(16);y.set(f,16-f.length);let P=zn(y);return `${p}-${u}-${P}`}function Yn(n,e="User ID"){let t=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;if(n){if(typeof n!="string")throw new a(`${e} should be type: string.`,{code:"INVALID_PARAMETER"});if(!n.match(t))throw new a(`${e} is invalid.`,{code:"INVALID_PARAMETER"})}else throw new a(`${e} is empty.`,{code:"INVALID_PARAMETER"});return n}function er(n){if(n&&(typeof n!="string"||n.charAt(0)!=="+"||isNaN(Number(n.substring(1)))))throw new a('"phone_number" is invalid. The format should be "+00123456789". Type: string.',{code:"INVALID_PARAMETER"});return n||""}function tr(n){if(n){if(typeof n!="string")throw new a('"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(n.length!==10||n.split("-").length!==3||!e.test(n))throw new a('"birthdate" is invalid. The format should be "yyyy-mm-dd". Type: string.',{code:"INVALID_PARAMETER"})}}return n||""}function nr(n){if(n){if(typeof n!="string")throw new a('"password" should be type: string.',{code:"INVALID_PARAMETER"});if(n.length<6)throw new a('"password" should be at least 6 characters.',{code:"INVALID_PARAMETER"});if(n.length>60)throw new a('"password" can be up to 60 characters max.',{code:"INVALID_PARAMETER"})}else throw new a('"password" is required.',{code:"INVALID_PARAMETER"});return n}function rr(n,e="email"){if(n){if(typeof n!="string")throw new a(`"${e}"should be type: string.`,{code:"INVALID_PARAMETER"});if(n.length<5)throw new a(`"${e}" should be at least 5 characters.`,{code:"INVALID_PARAMETER"});if(/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/.test(n)&&(n=n.trim(),n.split("@")[1].split(".").length>=2))return n.toLowerCase()}else throw new a(`"${e}" is required.`,{code:"INVALID_PARAMETER"});throw new a(`"${n}" is an invalid email.`,{code:"INVALID_PARAMETER"})}function ir(n){let e=typeof window<"u",t=(()=>{let r=e&&window.location.origin||null;return r&&r.slice(-1)==="/"&&(r=r.slice(0,-1)),r})(),i=r=>{if(typeof r=="string"){if(r==="*")return "*";{let s=r.trim();if(s[0]==="/"&&t){if(t.slice(0,5)==="file:")throw new a(`"${r}" is an invalid url. Relative URL does not work on local file system. Use full URL string.`,{code:"INVALID_PARAMETER"});s=t+s;}else if(s[0]==="."&&t){if(t.slice(0,5)==="file:")throw new a(`"${r}" is an invalid url. Relative URL does not work on local file system. Use full URL string.`,{code:"INVALID_PARAMETER"});let c=e?window.location.href.split("?")[0]:"";c.slice(-1)!=="/"&&(c+="/"),s=c+s.slice(1);}let o;try{o=new URL(s);}catch{throw new a(`"${r}" is an invalid url.`,{code:"INVALID_PARAMETER"})}if(o.protocol)return o.href}}throw new a(`"${r}" is an invalid url.`,{code:"INVALID_PARAMETER"})};return Array.isArray(n)?n.map(r=>i(r)):i(n)}function sr(n,e,t=[],i){let r=D(n,i),s=r.data;e.service="string",e.owner="string";let o={};for(let c in e)if(s&&typeof s=="object"&&!Array.isArray(s)&&s.hasOwnProperty(c))if(typeof s[c]=="function")o[c]=s[c];else try{o[c]=JSON.parse(JSON.stringify(s[c]));}catch{o[c]=s[c];}i?.precall&&i.precall({data:o,files:r?.files||[]});try{return Zn(o,e,t)}catch(c){throw new a(c.message,{code:"INVALID_PARAMETER"})}}var g={UserId:Yn,PhoneNumber:er,Birthdate:tr,Password:nr,Email:rr,Url:ir,Params:sr};var U=null;function Ue(n){let e={tkid:"ticket_id",cond:"condition",stmp:"timestamp",actn:"action",cnt:"count",ttl:"time_to_live",plch:"placeholder",hash:"hash",desc:"description",pmc:"limit_per_user"},t={};for(let i in n)if(i==="tkid"){let r=n[i].split("#");if(r.length===1){t.ticket_id=r[0];continue}t.ticket_id=r[1],t.consume_id=r[2],t.user_id=r[3];let s=r[2].slice(-4);if(t.is_test=s===":CHK",!n.stmp){let o=r[2].slice(0,-4);/^[0-9]+$/.test(o)?t.timestamp=parseInt(o,10):t.timestamp=B(r[2].slice(0,-4));}}else e[i]?t[e[i]]=n[i]:t[i]=n[i];return t}async function Ye(n){if(!n.ticket_id)throw new a("Ticket ID is required.",{code:"INVALID_PARAMETER"});if(!n.method)throw new a('Method is required. Should be either "GET" or "POST"',{code:"INVALID_PARAMETER"});let e=n.ticket_id;await this.__connection;let t=await R.bind(this)(`https://${this.service.slice(0,4)}.${this.customApiDomain}/auth/consume/${this.service}/${this.owner}/${e}`,n?.data||{},{method:n.method,auth:!!n?.auth});return Ue(t)}async function et(n,e){await this.__connection;let t=await R.bind(this)("ticket",Object.assign({exec:"list"},n||{}),{auth:true,fetchOptions:e});return t.list=t.list.map(Ue),t}async function tt(n,e){await this.__connection;let t=await R.bind(this)("ticket",Object.assign({exec:"consumed"},n||{}),{auth:true,fetchOptions:e});return t.list=t.list.map(Ue),t}async function nt(n){return R.bind(this)("register-ticket",Object.assign({exec:"reg"},n),{auth:true})}async function rt(n){return R.bind(this)("register-ticket",Object.assign({exec:"unreg"},n),{auth:true})}async function ne(){if(await this.__connection,this.session){let n=Math.floor(Date.now()/1e3),t=this.session.getIdToken().getExpiration();if(t<n){this.log("request:requesting new token",null);try{await F.bind(this)().getSession({refreshToken:!0}),this.log("request:received new tokens",{exp:this.session?.idToken?.payload?.exp,currentTime:n,expiresIn:t-n,token:this.session?.accessToken?.jwtToken,refreshToken:this.session?.refreshToken?.token});}catch(i){throw this.log("request:new token error",i),new a("User login is required.",{code:"INVALID_REQUEST"})}}else this.log("request:tokens",{exp:this.session.idToken.payload.exp,currentTime:n,expiresIn:t-n,token:this.session.accessToken.jwtToken,refreshToken:this.session.refreshToken.token});return this.session?.idToken?.jwtToken}else throw this.log("request:no session",null),G.bind(this)(),new a("User login is required.",{code:"INVALID_REQUEST"})}function Ze(n,e){return new Promise((t,i)=>{e.refreshSession(n.getRefreshToken(),(r,s)=>{this.log("getSession:refreshSessionCallback",{refreshErr:r,refreshedSession:s}),r?(G.bind(this)(),i(r)):s.isValid()?t(s):(G.bind(this)(),i(new a("Invalid session.",{code:"INVALID_REQUEST"})));});})}function F(){if(!this.userPool)throw new a("User pool is missing",{code:"INVALID_REQUEST"});let n=()=>{let s=U.getSignInUserSession().getIdToken().payload||null,o=ae(s);return this.log("normalized user attribute",o),this.__user=o,o},e=async s=>new Promise((o,c)=>{this.log("getSession:option",s);let{refreshToken:l=false,skipUserUpdateEventTrigger:d=false}=s||{};if(l&&d&&(d=false),U=this.userPool.getCurrentUser(),!U){this.log("getSession:cognitoUser",U),G.bind(this)(),c(null);return}let h=u=>{let p=u.getIdToken().payload;if(this.log("getSession:respond:sessionAttribute",p),p["custom:service"]!==this.service)throw this.log("getSession:respond","invalid service, signing out"),G.bind(this)(),new a("Invalid session.",{code:"INVALID_REQUEST"});return this.session=u,n(),d||this._runOnUserUpdateListeners(this.user),this.session};U.getSession((u,p)=>{if(this.log("getSession:getSessionCallback",{err:u,session:p}),!p){G.bind(this)(),c(new a("Current session does not exist.",{code:"INVALID_REQUEST"}));return}if(u){Ze.bind(this)(p,U).then(_=>o(h(_))).catch(c);return}let A=Math.floor(Date.now()/1e3),f=p.getIdToken(),y=f.getExpiration(),P=y<A;if(this.log("getSession:currentTime",A),this.log("getSession:idTokenExp",y),this.log("getSession:isExpired",P),this.log("getSession:existingBearerToken",this.bearerToken),this.bearerToken=f.getJwtToken(),P||l||!p.isValid())Ze.bind(this)(p,U).then(_=>o(h(_))).catch(c);else try{o(h(p));}catch(_){c(_);}});}),t=(s,o)=>{let c=o||s.includes(this.service+"-")?s:this.service+"-"+V.hash(s);return {cognitoUser:new CognitoUser({Username:c,Pool:this.userPool}),cognitoUsername:c}};return {getSession:e,authenticateUser:(s,o,c=false,l=false)=>new Promise((d,h)=>{this.__request_signup_confirmation=null,this.__disabledAccount=null;let u=t(s,c),p=u.cognitoUsername,A=new AuthenticationDetails({Username:p,Password:o});u.cognitoUser.authenticateUser(A,{newPasswordRequired:(f,y)=>{this.__disabledAccount=null,this.__request_signup_confirmation=p,f["custom:signup_ticket"]==="PASS"||f["custom:signup_ticket"]==="MEMBER"||f["custom:signup_ticket"]==="OIDPASS"?u.cognitoUser.completeNewPasswordChallenge(o,{},{onSuccess:P=>{U=u.cognitoUser,e().then(_=>d(this.user));},onFailure:P=>{h(new a(P.message||"Failed to authenticate user.",{code:P.code}));}}):h(new a("User's signup confirmation is required.",{code:"SIGNUP_CONFIRMATION_NEEDED"}));},onSuccess:f=>e({skipUserUpdateEventTrigger:true}).then(y=>{this.__disabledAccount=null,this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user),d(this.user);}),onFailure:f=>{let y=[],{parsed:P,code:_}=be(f),k=typeof f?.message=="string"?f.message:"";if(_==="NotAuthorizedException"?k.includes("User is disabled.")?(this.__disabledAccount=p,y=["This account is disabled.","USER_IS_DISABLED"]):l?y=["The account already exists.","ACCOUNT_EXISTS"]:y=["Incorrect username or password.","INCORRECT_USERNAME_OR_PASSWORD"]:_==="UserNotFoundException"?y=["Incorrect username or password.","INCORRECT_USERNAME_OR_PASSWORD"]:_==="UserNotConfirmedException"?(this.__request_signup_confirmation=p,y=["User's signup confirmation is required.","SIGNUP_CONFIRMATION_NEEDED"]):(_==="TooManyRequestsException"||_==="LimitExceededException")&&(y=["Too many attempts. Please try again later.","REQUEST_EXCEED"]),P.code==="SIGNUP_CONFIRMATION_NEEDED"&&(this.__request_signup_confirmation=p),y.length){let S=y[1],T=y[0];h(new a(T,{code:S,cause:f}));}else h(P);}});}),createCognitoUser:t,signup:(s,o,c)=>new Promise((l,d)=>{this.userPool.signUp(s,o,c,null,(h,u)=>{if(h){let{parsed:p,code:A}=be(h),f=[];A==="UsernameExistsException"?f=["The account already exists.","EXISTS"]:A==="InvalidPasswordException"?f=["Invalid password. Password must be at least 6 characters.","INVALID_PARAMETER"]:A==="InvalidParameterException"?f=[p.message||"Invalid parameter.","INVALID_PARAMETER"]:A==="TooManyRequestsException"||A==="LimitExceededException"?f=["Too many attempts. Please try again later.","REQUEST_EXCEED"]:A==="CodeDeliveryFailureException"?f=["Failed to deliver verification code.","CODE_DELIVERY_FAILURE"]:A==="UserLambdaValidationException"&&(f=[p.message||"Signup validation failed.","INVALID_REQUEST"]),f.length?d(new a(f[0],{code:f[1],cause:h})):d(p);return}l(u);});})}}function be(n){let e=typeof n?.code=="string"&&n.code.trim()?n.code.trim():"ERROR",i=((typeof n?.message=="string"?n.message:typeof n=="string"?n:"An error occurred.")||"An error occurred.").trim();i||(i="An error occurred.");let r=i.match(/#([A-Za-z0-9_]+)\s*:\s*([\s\S]+)/),s=r?.[1]?.trim()||e,o=r?.[2]?.trim()||i;return {parsed:new a(o,{code:s,cause:n}),code:e}}async function it(n){await this.__authConnection;let e=n?.refreshToken||false;if(!e)return this.user;try{return await F.bind(this)().getSession(Object.assign({skipUserUpdateEventTrigger:!e,refreshToken:e},n)),this.user}catch{return null}}async function st(n){await this.__connection,n=g.Params(n,{token:"string",id:"string",merge:s=>{if(s===void 0)return false;if(typeof s=="string")return [s];if(Array.isArray(s)){for(let o of s)if(typeof o!="string")throw new a('"merge" array items should be type: <string>.',{code:"INVALID_PARAMETER"})}if(typeof s!="boolean"&&!Array.isArray(s))throw new a('"merge" should be type: <boolean | string[]>.',{code:"INVALID_PARAMETER"});return s}});let e=await R.bind(this)("openid-logger",n),t=e.logger.split("#"),i=this.service+"-"+t[0],r=t[1];return {userProfile:await F.bind(this)().authenticateUser(i,r,true,true),openid:e.openid}}function dr(n){let e=typeof globalThis<"u"?globalThis:void 0;if(e?.Buffer)return e.Buffer.from(n,"base64").toString("utf8");if(typeof atob=="function"){let t=atob(n),i=new Uint8Array(t.length);for(let r=0;r<t.length;r++)i[r]=t.charCodeAt(r);return typeof TextDecoder<"u"?new TextDecoder().decode(i):t}throw new Error("No base64 decoder available in this environment")}function gr(n){let e=n.split(".");if(e.length!==3)throw new Error("Invalid JWT format");let i=e[1].replace(/-/g,"+").replace(/_/g,"/"),r=dr(i);return JSON.parse(r)}async function ot(n){await this.__authConnection,this.log("loginWithToken:params",n),n=g.Params(n,{idToken:"string",accessToken:"string",refreshToken:"string"},["idToken"]);let e=gr(n.idToken);if(this.log("loginWithToken:idTokenPayload",e),e["custom:service"]!==this.service)throw new a("Token does not belong to this service.",{code:"INVALID_REQUEST"});let t=Math.floor(Date.now()/1e3);if(e.exp&&e.exp<t)throw new a("Token has expired.",{code:"INVALID_REQUEST"});if(this.__user=ae(e),this.session=null,n.accessToken&&n.refreshToken)try{if(this.session=new CognitoUserSession({IdToken:new CognitoIdToken({IdToken:n.idToken}),AccessToken:new CognitoAccessToken({AccessToken:n.accessToken}),RefreshToken:new CognitoRefreshToken({RefreshToken:n.refreshToken})}),this.log("loginWithToken:session",this.session),this.log("loginWithToken:CognitoUser",CognitoUser),this.log("loginWithToken:userPool",this.userPool),CognitoUser&&this.userPool){this.log("loginWithToken:cognito:username",e["cognito:username"]);let i={Username:e["cognito:username"],Pool:this.userPool};this.log("loginWithToken:cognitoUserParams",i),U=new CognitoUser(i),U.setSignInUserSession(this.session),this.log("loginWithToken:cognitoUserRestored",{cognitoUserType:typeof U,cognitoUserKeys:Object.keys(U||{}),cognitoUser:U});}}catch(i){this.log("loginWithToken:err",i);try{this.log("loginWithToken:err:stringified",JSON.stringify(i));}catch{this.log("loginWithToken:err:stringifyFail",String(i));}try{let r=Object.keys(i||{}),s=Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(i||{}):[],o=Object.getOwnPropertyDescriptors?Object.getOwnPropertyDescriptors(i||{}):{};this.log("loginWithToken:createSessionError:allKeys",{keys:r,symbols:s,descriptors:o});}catch(r){this.log("loginWithToken:createSessionError:allKeysFail",String(r));}}return this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user),this.user}async function M(){return await this.__connection,this.__user?.service===this.service?this.__user?.owner===this.host:(await ce.bind(this)(),false)}async function G(n=false){let e=null;U&&(n?e=new Promise((i,r)=>{U.globalSignOut({onSuccess:s=>{this.log("globalSignOut:success",s),i(s);},onFailure:s=>{this.log("globalSignOut:error",s),r(s);}});}):U.signOut());let t={session:null,__startKeyHistory:{},__cached_requests:{},__user:null};e&&(e=await e);for(let i in t)this[i]=t[i];return this._runOnUserUpdateListeners(null),this._runOnLoginListeners(null),e}async function ce(n){await this.__connection;let{data:e}=D(n);return await G.bind(this)(e?.global),"SUCCESS: The user has been logged out."}async function at(){if(!this.__request_signup_confirmation)throw new a("Least one login attempt is required.",{code:"INVALID_REQUEST"});return await R.bind(this)("confirm-signup",{username:this.__request_signup_confirmation})}async function ct(n=false){if(typeof n=="string")n=g.Url(n);else if(typeof n!="boolean")throw new a("Argument should be type: <boolean | string>.",{code:"INVALID_REQUEST"});if(!this.__disabledAccount)throw new a("Least one signin attempt of disabled account is required.",{code:"INVALID_REQUEST"});return await R.bind(this)("recover-account",{username:this.__disabledAccount,redirect:n}),"SUCCESS: Recovery e-mail has been sent."}async function Ne(n){let e=g.Params(n,{username:"string",email:"string",password:"string"},["password"]);if(await this.__authConnection,e.email)try{g.Email(e.email);}catch{e.username=e.email,delete e.email;}if(!e.username&&!e.email)throw new a('Least one of "username" or "email" is required.',{code:"INVALID_PARAMETER"});return await F.bind(this)().authenticateUser(e.username||e.email,e.password)}async function lt(n,e){await this.__authConnection;let t={username:"string",password:d=>g.Password(d),email:d=>g.Email(d),name:"string",address:d=>{if(!d)return "";if(typeof d=="string")return d;if(typeof d=="object")return JSON.stringify(d)},gender:"string",birthdate:d=>d?g.Birthdate(d):"",phone_number:d=>d?g.PhoneNumber(d):"",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:d=>d?g.Url(d):"",profile:d=>d?g.Url(d):"",family_name:"string",given_name:"string",middle_name:"string",nickname:"string",website:d=>d?g.Url(d):""},i=g.Params(n||{},t,["email","password"]);await ce.bind(this)(),e=g.Params(e||{},{email_subscription:d=>{if(typeof d!="boolean")throw new a('"option.email_subscription" should be type: <boolean>.',{code:"INVALID_PARAMETER"});if(!e?.signup_confirmation)throw new a('"option.signup_confirmation" is required for email subscription.',{code:"INVALID_PARAMETER"});return d},signup_confirmation:d=>{let h=d;if(typeof d=="string")h=g.Url(d);else if(typeof d=="boolean")h=d;else throw new a('"option.signup_confirmation" should be type: <string | boolean>.',{code:"INVALID_PARAMETER"});if(h&&!i.email)throw new a('"email" is required for signup confirmation.',{code:"INVALID_PARAMETER"});return h},login:d=>{if(typeof d=="boolean"){if(e.signup_confirmation&&d)throw new a('"login" is not allowed when "option.signup_confirmation" is true.',{code:"INVALID_PARAMETER"});return d}throw new a('"option.login" should be type: boolean.',{code:"INVALID_PARAMETER"})}});let r=e?.login||false;if(i.signup_confirmation=e?.signup_confirmation||false,i.email_subscription=e?.email_subscription||false,i.email_public&&!i.signup_confirmation)throw new a('"option.signup_confirmation" should be true if "email_public" is set to true.',{code:"INVALID_PARAMETER"});i.service=this.service,i.owner=this.owner;let s=F.bind(this)().createCognitoUser(i.username||i.email);for(let d of ["email_public","address_public","gender_public","birthdate_public","phone_number_public"])i[d]=i[d]?"1":"0";i.access_group&&(i.access_group=i.access_group.toString());let o=(await R.bind(this)("signupkey",{username:s.cognitoUsername,signup_confirmation:typeof i.signup_confirmation=="boolean"?JSON.stringify(i.signup_confirmation):i.signup_confirmation,email_subscription:i.email_subscription})).split(":"),c=o.slice(1).join(":"),l=[new CognitoUserAttribute({Name:"custom:signup",Value:o[0]}),new CognitoUserAttribute({Name:"locale",Value:c.split("#")[1]}),new CognitoUserAttribute({Name:"custom:signup_ticket",Value:c})];for(let d in t){let h=["email_public","address_public","gender_public","birthdate_public","phone_number_public","misc","service","owner"];i[d]!==""&&(d==="username"||d==="password"||d==="access_group"||(h.includes(d)?l.push(new CognitoUserAttribute({Name:"custom:"+d,Value:i[d]})):l.push(new CognitoUserAttribute({Name:d,Value:i[d]}))));}return await F.bind(this)().signup(s.cognitoUsername,i.password,l),i.signup_confirmation?(U=s.cognitoUser,this.__request_signup_confirmation=s.cognitoUsername,"SUCCESS: The account has been created. User's signup confirmation is required."):r?Ne.bind(this)({email:i.username||i.email,password:i.password}):"SUCCESS: The account has been created."}async function ut(){await this.__connection;let n=await R.bind(this)("remove-account",{disable:this.__user.user_id},{auth:true});return await ce.bind(this)(),n}async function dt(n){await this.__connection;let e=g.Params(n,{email:r=>g.Email(r),code:["number","string"],new_password:r=>g.Password(r)},["email","code","new_password"]),t=e.code,i=e.new_password;return typeof t=="number"&&(t=t.toString()),new Promise(async(r,s)=>{F.bind(this)().createCognitoUser(e.email).cognitoUser.confirmPassword(t,i,{onSuccess:c=>{r("SUCCESS: New password has been set.");},onFailure:c=>{s(new a(c?.message||"Failed to reset password.",{code:c?.code||"ERROR",cause:c}));}});})}async function gt(n,e){await this.__connection;let t;if(!U)throw new a("The user has to be logged in.",{code:"INVALID_REQUEST"});if(n==="email"||n==="phone_number"){if(!this.__user.hasOwnProperty(n))throw new a(`No ${n==="email"?"e-mail":"phone number"} to verify`,{code:"INVALID_REQUEST"});if(this.__user?.[`${n}_verified`])return `SUCCESS: "${n}" is verified.`;t=(e?g.Params(e,{code:"string"}):{}).code||"";}else return;return new Promise((i,r)=>{let s={onSuccess:o=>{t?F.bind(this)().getSession({refreshToken:true}).then(()=>{this.__user&&(this.__user[n+"_verified"]=true),i(`SUCCESS: "${n}" is verified.`);}).catch(c=>{r(c);}):i("SUCCESS: Verification code has been sent.");},onFailure:o=>{r(new a(o.message||"Failed to request verification code.",{code:o?.code}));}};t?U?.verifyAttribute(n,t,s):(s.inputVerificationCode=null,U?.getAttributeVerificationCode(n,s));})}function ft(n){return gt.bind(this)("phone_number",n)}function ht(n){return gt.bind(this)("email",n)}async function pt(n){await this.__connection;let e=g.Params(n,{email:t=>g.Email(t)},["email"]);return new Promise(async(t,i)=>{F.bind(this)().createCognitoUser(e.email).cognitoUser.forgotPassword({onSuccess:s=>{t("SUCCESS: Verification code has been sent.");},onFailure:s=>{let{parsed:o,code:c}=be(s),l={UserNotFoundException:"NOT_EXISTS",InvalidParameterException:"INVALID_PARAMETER",NotAuthorizedException:"INVALID_REQUEST",LimitExceededException:"REQUEST_EXCEED",TooManyRequestsException:"REQUEST_EXCEED",CodeDeliveryFailureException:"CODE_DELIVERY_FAILURE"}[c]||o.code||c||"ERROR";i(new a(o.message,{code:l,cause:s}));}});})}async function mt(n){if(await this.__connection,!this.session)throw new a("User login is required.",{code:"INVALID_REQUEST"});let e=g.Params(n,{current_password:"string",new_password:"string"});if(!e?.current_password)throw new a('"current_password" is required to change password.',{code:"INVALID_PARAMETER"});if(!e?.new_password)throw new a('"new_password" is required to change password.',{code:"INVALID_PARAMETER"});return g.Password(e.current_password),g.Password(e.new_password),new Promise((t,i)=>{U.changePassword(e.current_password,e.new_password,(r,s)=>{if(r){if(r?.code==="InvalidParameterException")i(new a("Invalid password parameter.",{code:"INVALID_PARAMETER"}));else if(r?.code==="NotAuthorizedException")i(new a("Incorrect password.",{code:"INVALID_REQUEST"}));else if(r?.code==="TooManyRequestsException"||r?.code==="LimitExceededException")i(new a("Too many attempts. Please try again later.",{code:"REQUEST_EXCEED"}));else {let{parsed:o}=be(r);i(o);}return}t("SUCCESS: Password has been changed.");});})}async function _t(n){if(await this.__connection,!this.session)throw new a("User login is required.",{code:"INVALID_REQUEST"});let e=g.Params(n||{},{user_id:r=>g.UserId(r),email:r=>g.Email(r),address:r=>{if(!r)return "";if(typeof r=="string")return r;if(typeof r=="object")return JSON.stringify(r)},name:"string",gender:"string",birthdate:r=>r?g.Birthdate(r):"",phone_number:r=>r?g.PhoneNumber(r):"",email_public:"boolean",phone_number_public:"boolean",address_public:"boolean",gender_public:"boolean",birthdate_public:"boolean",misc:"string",picture:r=>r?g.Url(r):"",profile:r=>r?g.Url(r):"",family_name:"string",given_name:"string",middle_name:"string",nickname:"string",website:r=>r?g.Url(r):""});if(e&&typeof e=="object"&&!Object.keys(e).length)return this.user;e.email&&(e.preferred_username=this.service+"-"+V.hash(e.email));let t=[["email_public","email_verified","User's e-mail should be verified to set"],["phone_number_public","phone_number_verified","User's phone number should be verified to set"]];if(this.__user){for(let r of t)if(e[r[0]]&&!this.__user[r[1]])throw new a(`${r[2]} "${r[0]}" to true.`,{code:"INVALID_REQUEST"})}let i=[];for(let r in e){if(e[r]===this.user[r]){i.push(r);continue}if(["email_public","phone_number_public","address_public","gender_public","birthdate_public","misc"].includes(r)){let o=e[r];typeof o=="boolean"&&(o=o?"1":"0"),e["custom:"+r]=o,i.push(r);}}for(let r of i)delete e[r];if(e.user_id)if(e.user_id===this.user.user_id)delete e.user_id;else return R.bind(this)("admin-edit-profile",{attributes:e},{auth:true});if(e&&typeof e=="object"&&Object.keys(e).length){let r=[];for(let s in e)r.push(new CognitoUserAttribute({Name:s,Value:e[s]}));return await new Promise((s,o)=>{U?.updateAttributes(r,(c,l)=>{c&&o([c?.code||c?.name,c?.message||"Failed to update user settings."]),s(l);});}),await F.bind(this)().getSession({refreshToken:true}),this.user}return this.user}async function bt(n,e){n=D(n).data,n||(n={searchFor:"timestamp",condition:">",value:0},e||(e={}),e.ascending=false),await this.__connection;let t={user_id:r=>Array.isArray(r)?r.map(s=>g.UserId(s)):g.UserId(r),email:"string",phone_number:"string",locale:r=>{if(typeof r!="string"||typeof r=="string"&&r.length>5)throw new a('Value of "locale" should be a country code.',{code:"INVALID_PARAMETER"});return r},name:"string",address:"string",gender:"string",birthdate:r=>g.Birthdate(r),subscribers:"number",timestamp:"number",access_group:"number",approved:"string"},i=["searchFor","value"];if(n=g.Params(n,{searchFor:["user_id","name","email","phone_number","address","gender","birthdate","locale","subscribers","timestamp","access_group","approved"],condition:[">",">=","=","<","<=","gt","gte","eq","lt","lte",()=>"="],value:r=>{let s=t[n.searchFor];if(typeof s=="function")return s(r);if(typeof r!==s)throw new a(`Value does not match the type of "${n.searchFor}" index.`,{code:"INVALID_PARAMETER"});return r},range:r=>{let s=t[n.searchFor];if(typeof s=="function")return s(r);if(typeof r!==s)throw new a(`Range does not match the type of "${n.searchFor}" index.`,{code:"INVALID_PARAMETER"});return r}},i),n?.condition&&n?.condition!=="="&&n.hasOwnProperty("range"))throw new a("Conditions does not apply on range search.",{code:"INVALID_PARAMETER"});if(n.searchFor==="user_id"&&(n.condition!=="="||n.range))throw new a(`Conditions are not allowed on "${n.searchFor}"`,{code:"INVALID_PARAMETER"});if(typeof n?.value=="string"&&!n?.value)throw new a("Value should not be an empty string.",{code:"INVALID_PARAMETER"});if(typeof n?.searchFor=="string"&&!n?.searchFor)throw new a('"searchFor" should not be an empty string.',{code:"INVALID_PARAMETER"});return R.bind(this)("get-users",n,{auth:true,fetchOptions:e})}async function yt(n){await this.__connection;let e=await R.bind(this)("last-verified-email",n,{auth:true});return e.includes("SUCCESS")?(await F.bind(this)().getSession({refreshToken:true}),this.user):e}async function wt(n){return await this.__connection,n=g.Params(n,{username:g.Email,redirect:g.Url},["username"]),await R.bind(this)("request-username-change",n,{auth:true})}var re=null,Rt=typeof SubmitEvent<"u",hr=typeof HTMLFormElement<"u",ue=$(),Ce=0;function At(n){if(!n)return null;let e=Number(n);if(Number.isFinite(e))return Math.max(0,e*1e3);let t=Date.parse(n);return Number.isNaN(t)?null:Math.max(0,t-Date.now())}function Le(n,e){return e>0?n/e*100:0}var Et=n=>{let{auth:e,type:t,endpoints:i}=n,r=i[0],s=i[1];if(Ce++,t==="admin"){let o=Object.entries(r).filter(([c,l])=>c.includes(e?"_private":"_public")&&c!=="get_users_private"&&c!=="service_public"&&typeof l=="string").map(([,c])=>c);if(!o.length)throw new a("No available admin gateways.",{code:"INVALID_REQUEST"});return o[Ce%o.length]}if(t==="record"){let o=Object.entries(s).filter(([c,l])=>c.includes(e?"record_private":"record_public")&&typeof l=="string").map(([,c])=>c);if(!o.length)throw new a("No available record gateways.",{code:"INVALID_REQUEST"});return o[Ce%o.length]}throw new a("Invalid gateway type.",{code:"INVALID_REQUEST"})};async function pr(n,e){let t=await Promise.all([this.admin_endpoint,this.record_endpoint]),i=t[0],r=t[1],s=n.split("?"),o=s.length>1?"?"+s[1]:"";switch(n=s[0],n){case "get-users":return i.get_users_private+n+o;case "service":return i.service_public+n+o;case "get-newsletters":case "get-public-newsletters":case "subscribe-newsletter":case "subscribe-public-newsletter":case "signupkey":case "admin-newsletter-request":case "admin-signup":case "confirm-signup":case "openid-logger":case "block-account":case "admin-edit-profile":case "remove-account":case "post-secure":case "recover-account":case "mock":case "grant-access":case "last-verified-email":case "ticket":case "register-ticket":case "get-newsletter-subscription":case "request-username-change":case "send-inquiry":case "register-newsletter-group":case "newsletter-group-endpoint":case "invitation-list":case "csr":return Et.bind(this)({auth:e,type:"admin",endpoints:t})+n+o;case "post-record":return (e?r.post_private:r.post_public)+n+o;case "get-records":return (e?r.get_private:r.get_public)+n+o;case "del-files":case "del-records":return r.del_private+n+o;case "store-subscription":case "get-vapid-public-key":case "push-notification":case "delete-subscription":case "subscription":case "get-subscription":case "get-table":case "get-tag":case "get-uniqueid":case "get-index":case "get-signed-url":case "grant-private-access":case "request-private-access-key":case "get-ws-group":case "check-schema":case "get-feed":case "castspell":case "dopamine":case "getspell":return Et.bind(this)({auth:e,type:"record",endpoints:t})+n+o;default:return g.Url(n)+o}}var le={};function It(){re&&(re.terminate(),re=null);}async function R(n,e=null,t,i){this.log("request",{url:n,data:e,options:t,_etc:i||{}}),t=t||{};let{auth:r=false,method:s="post",bypassAwaitConnection:o=false}=t;s=s.toUpperCase();let c=null,l=e?.service||this.service,d=e?.owner||this.owner,h=null,u=await pr.bind(this)(n,!!r);if(!o&&(c=await this.__connection,!c))throw new a("Invalid connection. The service could have been disabled, or has a restricted CORS.",{code:"INVALID_REQUEST"});r&&(h=await ne.bind(this)());let p={},{fetchMore:A=false,progress:f}=t?.fetchOptions||{};if(t?.fetchOptions&&Object.keys(t.fetchOptions).length){for(let x of ["limit","startKey","ascending"])t.fetchOptions.hasOwnProperty(x)&&(p[x]=t.fetchOptions[x]);p=g.Params(p,{limit:x=>{if(typeof x!="number")throw new a("Fetch limit should be a number.",{code:"INVALID_REQUEST"});if(x>1e3)throw new a("Fetch limit should be below 1000.",{code:"INVALID_REQUEST"});return x},startKey:x=>x,ascending:"boolean"});}let y=i?.ignoreService?{}:{service:l,owner:d};Object.assign(y,p),e=D(e).data,e?e&&typeof e=="object"&&(e=Object.assign(y,e)):e=y;let P=`${s}:${r?"auth":"public"}:${n}`,_=(()=>{if(e&&typeof e=="object"&&Object.keys(e).length&&!(ue&&e instanceof FormData)){let x=function(v){return typeof v=="object"&&v!==null?Object.keys(v).sort().reduce((N,O)=>(typeof v[O]=="object"&&v[O]!==null?N[O]=x(v[O]):N[O]=v[O],N),{}):v};return V.hash(P+"/"+JSON.stringify(x(e)))}return V.hash(P+"/"+l)})(),{requestKey:k,requestKeyWithStartKey:S}=mr.bind(this)({params:e,url:n,fetchMore:A,hashedParams:_});if(!k||k&&typeof k=="object")return k;if(this.log("requestKey",S),typeof S=="string"&&le[S]instanceof Promise)return this.log("request:returning pending",S),le[S];let T={Accept:"*/*"};if(Object.prototype.hasOwnProperty.call(t,"contentType")&&t.contentType!==void 0){let x=t.contentType===null?"application/x-www-form-urlencoded":t.contentType;x&&(T["Content-Type"]=x);}else T["Content-Type"]="application/json";h&&(T.Authorization=h);let q={public_identifier:this.__public_identifier,service:l,owner:d};T["Content-Meta"]=JSON.stringify(q);let j={headers:T};if(t?.responseType&&(j.responseType=t.responseType),s==="GET"){if(e){let x=[];if(ue&&e instanceof FormData?x=Array.from(e.entries()).map(([v,N])=>{let O=typeof N=="string"?N:N.name;return encodeURIComponent(v)+"="+encodeURIComponent(O)}):x=Object.keys(e).map(v=>{let N=e[v];return typeof N!="string"&&(N=JSON.stringify(N)),encodeURIComponent(v)+"="+encodeURIComponent(N)}),x.length){let v=u.includes("?")?u.endsWith("?")||u.endsWith("&")?"":"&":"?";u+=v+x.join("&");}}j.body=null;}else if(ue&&e instanceof FormData)j.body=e;else if(T["Content-Type"]==="application/x-www-form-urlencoded"&&e&&typeof e=="object"){let x=new URLSearchParams;for(let v of Object.keys(e)){let N=e[v];x.append(v,typeof N=="string"?N:JSON.stringify(N));}j.body=x.toString();}else typeof e=="string"?j.body=e:j.body=e?JSON.stringify(e):null;if(j.method=s,re===null){let x={batchSize:this.requestBatchSize,breakWhenError:false,onProgress:v=>{this.onBatchProcess.forEach(N=>N(v));}};re=new fr(x);}return this.log("request-opt",j),new Promise((x,v)=>{re.add([async()=>{let N=Tt.bind(this)(u,j,f);le[S]=N;try{let O=_r.bind(this)({hashedParam:k,requestKeyWithStartKey:S,url:n,fetched:await N});return delete le[S],this.log("request:end",O),x(O),O}catch(O){throw delete le[S],this.log("request:err",O),v(O),O}}]);})}function mr(n){let{params:e={},url:t,fetchMore:i=false,hashedParams:r}=n||{};if(e.startKey){if(!(typeof e.startKey=="object"&&Object.keys(e.startKey).length)&&e.startKey!=="start"&&e.startKey!=="end")throw new a(`"${e.startKey}" is invalid startKey key.`,{code:"INVALID_PARAMETER"});e.startKey==="start"&&(i=false,delete e.startKey);}if(!i){if(this.__cached_requests?.[t]?.[r]&&delete this.__cached_requests[t][r],this.__startKeyHistory?.[t]?.[r]){if(Array.isArray(this.__startKeyHistory[t][r])&&this.__startKeyHistory[t][r].length)for(let l of this.__startKeyHistory[t][r]){let d=r+V.hash(l);this.__cached_requests?.[t]&&this.__cached_requests?.[t]?.[d]&&delete this.__cached_requests[t][d];}delete this.__startKeyHistory[t][r];}return {requestKeyWithStartKey:r,requestKey:r}}if(!Array.isArray(this.__startKeyHistory?.[t]?.[r]))return {requestKeyWithStartKey:r,requestKey:r};let s=this.__startKeyHistory[t][r],o=s[s.length-1],c=r;if(o){if(o==="end")return {requestKey:{list:[],startKey:"end",endOfList:true,startKeyHistory:s},requestKeyWithStartKey:c};c+=V.hash(o),e.startKey=JSON.parse(o);}return this.__cached_requests?.[t]?.[c]?{requestKey:this.__cached_requests[t][c],requestKeyWithStartKey:c}:{requestKeyWithStartKey:c,requestKey:r}}function Tt(n,e,t){return new Promise((i,r)=>{let s=new XMLHttpRequest;s.open(e.method||"GET",n);for(var o in e.headers||{})s.setRequestHeader(o,e.headers[o]);e.responseType&&(s.responseType=e.responseType),s.onload=()=>{if(s.status<400)if(e.responseType=="json"||e.responseType=="blob")i(s.response);else {let c=s.responseText;try{c=JSON.parse(c);}catch{}i(c);}else if(s.status===429){let c=s.getResponseHeader("Retry-After"),l=At(c);l!==null?setTimeout(()=>{Tt(n,e,t).then(i,r);},l):r("Too many requests");}else {let c=s.status,l=["INVALID_CORS","INVALID_REQUEST","SERVICE_DISABLED","INVALID_PARAMETER","ERROR","EXISTS","NOT_EXISTS"],d=e.responseType=="blob"?s.response:s.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();r(new a(p||d,{code:l.includes(u)?u:"ERROR"}));}else if(typeof d=="object"&&d?.message){let h=d?.code||(c?c.toString():null)||"ERROR",u=d.message,p=d?.cause;typeof u=="string"&&(u=u.trim()),r(new a(u,{cause:p,code:h}));}else r(d);}},s.onerror=()=>r("Network error"),s.onabort=()=>r("Aborted"),s.ontimeout=()=>r("Timeout"),typeof t=="function"&&(s.onprogress=c=>{t({status:"download",progress:Le(c.loaded,c.total),loaded:c.loaded,total:c.total,abort:()=>s.abort()});},s.upload&&(s.upload.onprogress=c=>{t({status:"upload",progress:Le(c.loaded,c.total),loaded:c.loaded,total:c.total,abort:()=>s.abort()});})),s.send(e.body);})}function _r(n){let{hashedParam:e,requestKeyWithStartKey:t,url:i,fetched:r}=n;if(!r?.startKey)return r;this.__startKeyHistory.hasOwnProperty(i)||(this.__startKeyHistory[i]={}),this.__startKeyHistory[i].hasOwnProperty(e)||(this.__startKeyHistory[i][e]=[]);let s=r.startKey==="end"?"end":JSON.stringify(r.startKey);return this.__startKeyHistory[i][e].includes(s)||this.__startKeyHistory[i][e].push(s),this.__cached_requests?.[i]||(this.__cached_requests[i]={}),this.__cached_requests[i][t]=r,Object.assign({startKeyHistory:this.__startKeyHistory[i][e]},r)}async function we(n,e){await this.__connection;let{record_id:t,service:i=this.service,progress:r}=e;if(!t)throw new a('"record_id" is required.',{code:"INVALID_PARAMETER"});if(Rt&&n instanceof SubmitEvent&&(n=n.target),hr&&n instanceof HTMLFormElement&&(n=new FormData(n)),!ue||!(n instanceof FormData))throw new a('"fileList" should be a FormData or HTMLFormElement.',{code:"INVALID_PARAMETER"});let o={reserved_key:oe(),service:i,request:"post"};e?.record_id&&(o.id=e.record_id);let c,l=(A,f,y)=>new Promise((P,_)=>{c=new XMLHttpRequest,c.open("POST",A),c.onload=()=>{let k=c.responseText;try{k=JSON.parse(k);}catch{}if(c.status>=200&&c.status<300)P(k);else if(c.status===429){let S=c.getResponseHeader("Retry-After"),T=At(S);T!==null?setTimeout(()=>{l(A,f,y).then(P,_);},T):_("Too many requests");}else _(k);},c.onerror=()=>_("Network error"),c.onabort=()=>_("Aborted"),c.ontimeout=()=>_("Timeout"),c.upload&&typeof y=="function"&&(c.upload.onprogress=y),c.send(f);});function d(A){let f="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";if(A===0)return f[0];let y="";for(;A>0;)y=f[A%62]+y,A=Math.floor(A/62);return y}let h=[],u=[],p=[];for(let[A,f]of n.entries()){if(!(f instanceof File))continue;let y=Object.assign({key:A+"/"+f.name,sizeKey:d(f.size),contentType:f.type||null},o),{fields:P=null,url:_,cdn:k}=await R.bind(this)("get-signed-url",y,{auth:!!this.__user});p.push(k);let S=new FormData;for(let T in P)S.append(T,P[T]);S.append("file",f);try{await l(_,S,typeof r=="function"?T=>r({status:"upload",progress:Le(T.loaded,T.total),currentFile:f,completed:h,failed:u,loaded:T.loaded,total:T.total,abort:()=>c.abort()}):null),h.push(f);}catch{u.push(f);}}return {completed:h,failed:u,bin_endpoints:p}}var ye={};function E(n){let{preventMultipleCalls:e=false}=n||{};return function(t,i,r){let s=r.value;r.value=function(...o){let c=o[0],l=true,d=null,h="",u={},p=false;if(Rt&&c instanceof SubmitEvent){c.preventDefault();let _=window.location.href;d=c.target;let k=new URL(d.action);h=k.href;let S=h?h.match(/(?<=\{).*?(?=\})/g):"";if(S)for(let T of S){if(!T)continue;let L=d.querySelector(`[name="${T}"]`);if(L)if(L.type==="file")for(let q=0;q<=L.files.length-1;q++)L.files[q]&&(u[T]||(u[T]=[]),u[T].push(new Promise((j,x)=>{let v=new FileReader;v.onload=function(){j(v.result);},v.readAsDataURL(L.files[q]),v.onerror=x;})));else h=h.replace(`{${T}}`,L.value);}d.getAttribute("action")===null?l=false:p=k.href===_;}let A=async _=>{if(h)for(let k in u)u[k].length&&(h=h.replace(`{${k}}`,(await Promise.all(u[k])).join(",")));return d&&l&&(window.sessionStorage.setItem(`${this.service}:${V.hash(h)}`,JSON.stringify(_)),p?window.location.replace(h):window.location.href=h),_},f,y=_=>{throw _ instanceof a?_.name=i+"()":_=_ instanceof Error?_:new a(_,{name:i+"()"}),_},P=async()=>{try{if(f=s.bind(this)(...o),f instanceof Promise){let _=await f;return A(_)}return A(f)}catch(_){throw y(_)}};if(e){let _=`${i}:${this?.__public_identifier||""}:${this?.service||""}:${this?.owner||""}`;return ye?.[_]||(ye[_]=P().finally(()=>{delete ye[_];})),ye[_]}return P()};}}async function Pt(){await this.__connection;let n=`${this.service}:${V.hash(window.location.href.split("?")[0])}`,e=window.sessionStorage.getItem(n);if(window.sessionStorage.removeItem(n),e!==null){try{e=JSON.parse(e);}catch{}return e}return null}var br=128,yr=64,wr=128,Er=256,Rr="\u{10FFFF}",Ar=/[\u0000-\u001F\u007F]|\u{10FFFF}/u,Ir=/[\/!*#]/;function X(n,e,t={}){let{allowEmpty:i=false,maxLength:r,blockKeyDelimiters:s=false,disallowLeadingDollar:o=false,onlyAlphanumeric:c=false}=t;if(typeof n!="string")throw new a(`"${e}" should be type: <string>.`,{code:"INVALID_PARAMETER"});if(c&&/[^a-zA-Z0-9]/.test(n))throw new a(`"${e}" should only contain alphanumeric characters.`,{code:"INVALID_PARAMETER"});if(!i&&n.length===0)throw new a(`"${e}" is required.`,{code:"INVALID_PARAMETER"});if(r&&n.length>r)throw new a(`"${e}" should be <= ${r} characters.`,{code:"INVALID_PARAMETER"});if(Ar.test(n)||n.includes(Rr))throw new a(`"${e}" cannot include control characters or unsupported sentinel characters.`,{code:"INVALID_PARAMETER"});if(s&&Ir.test(n))throw new a(`"${e}" cannot include reserved delimiters: / ! * #`,{code:"INVALID_PARAMETER"});if(o&&n.startsWith("$"))throw new a(`"${e}" cannot start with "$".`,{code:"INVALID_PARAMETER"});return n}function Oe(n,e="table.name"){return X(n,e,{allowEmpty:false,maxLength:br,blockKeyDelimiters:true})}function Fe(n,e="tag"){return X(n,e,{allowEmpty:false,maxLength:yr,blockKeyDelimiters:true})}function de(n,e="index.name"){return X(n,e,{allowEmpty:false,maxLength:wr,blockKeyDelimiters:true,disallowLeadingDollar:true})}function St(n,e="index.value"){return X(n,e,{allowEmpty:true,maxLength:Er})}function kt(n){if(!n.record_id&&!n.unique_id)return null;let e={};return n?.service&&(e.service=n.service),n?.owner&&(e.owner=n.owner),n?.record_id?e.record_id=X(n.record_id,"record_id",{allowEmpty:false,onlyAlphanumeric:true}):n?.unique_id&&(e.unique_id=n.unique_id),e}function Me(n){if(n===void 0)return 0;if(typeof n=="number"){if(n>99||n<0)throw new a('"table.access_group" value should be within a range of 0 ~ 99.',{code:"INVALID_REQUEST"})}else if(typeof n=="string"){if(n={private:"private",public:0,authorized:1,admin:99}[n],n===void 0)throw new a('"table.access_group" is invalid.',{code:"INVALID_PARAMETER"})}else throw new a('"table.access_group" should be type: <number | string>.',{code:"INVALID_PARAMETER"});if(!this.__user&&n)throw new a("Unsigned users have no access to records with access group.",{code:"INVALID_REQUEST"});return n}var Ee=4503599627370496;function Re(n){if(typeof n=="number"){if(n>Ee||n<-Ee)throw new a(`Number value should be within range -${Ee} ~ +${Ee}`,{code:"INVALID_PARAMETER"});return n}if(typeof n=="boolean")return n;if(typeof n=="string")return St(n,"index.value");throw new a('"index.value" should be type: <number | boolean | string>.',{code:"INVALID_PARAMETER"})}function xt(n,e){if(!e.index||!("value"in e.index))throw new a('"index.value" is required.',{code:"INVALID_PARAMETER"});if(e.index.name==="$record_id")throw new a(`Cannot do "index.range" on ${e.index.name}`,{code:"INVALID_PARAMETER"});if(typeof e.index.value!=typeof n)throw new a('"index.range" type should match the type of "index.value".',{code:"INVALID_PARAMETER"});return typeof n=="string"?St(n,"index.range"):n}var Ae={};async function ie(n,e){let t={user_id:"",record_id:"",updated:0,uploaded:0,readonly:false,table:{name:"",access_group:0,subscription:{is_subscription_record:false,upload_to_feed:false,notify_subscribers:false,feed_referencing_records:false,notify_referencing_records:false}},referenced_count:0,source:{referencing_limit:null,prevent_multiple_referencing:false,can_remove_referencing_records:false,only_granted_can_reference:false},ip:"",bin:{}},i=false;function r(o){let c=o=="**"?"private":parseInt(o);return c=c==0?"public":c==1?"authorized":c==99?"admin":c,c}let s={ip:o=>{let c=o.split("#"),l=c[0];c.length>1&&(t.unique_id=c[1]),l.slice(-1)==="R"?(t.readonly=true,l=l.slice(0,-1)):t.readonly=false,/^\d{1,3}-\d{1,3}-\d{1,3}-\d{1,3}$/.test(l)&&(l=l.split("-").join("."),i=true),t.ip=l;},rec:o=>{if(!o)return;t.record_id=o;let c=o.substring(0,o.length-9),l=B(c);t.uploaded=l;},usr:o=>{t.user_id=o;},tbl:o=>{if(o&&!t.table.name){let c=o.split("/");t.table.name=c[0],t.table.access_group=r(c[2]),c?.[3]&&(t.table.subscription.is_subscription_record=true);}},usr_tbl:o=>{let c=o.split("/");t.user_id||(t.user_id=c[0]),t.table.name||(t.table.name=c[1],t.table.access_group=r(c[3]),c?.[4]&&(t.table.subscription.is_subscription_record=true));},idx:o=>{if(!o)return;let c=o.split("!"),l=c.splice(0,1)[0],d=Tr("!"+c.join("!"));t.index={name:l,value:d};},ref:o=>{o&&(t.reference=o.split("/")[0]);},tags:o=>{t.tags=o;},upd:o=>{t.updated=o;},acpt_mrf:o=>{t.source.prevent_multiple_referencing=!o;},ref_limt:o=>{t.source.referencing_limit=o;},rfd:o=>{t.referenced_count=o;},bin:async o=>{let c={},l=t?.reference||null;if(Array.isArray(o)){let d=await Promise.all(o.map(async h=>{try{let u=h.split("/").slice(3).join("/"),p=u.split("/");if(p.length<12)return null;let A=decodeURIComponent(p[p.length-1]),f=decodeURIComponent(p[10]),y=p[9],P=p[8],_=r(p[6]),k=h;if(_!=="public")try{k=await Ie.bind(this)(h,{dataType:"endpoint",_ref:l});}catch(T){console.error("Error getting signed url for private file:",T),k=h;}let S={access_group:_,filename:A,url:k,path:u,size:B(y),uploaded:B(P),getFile:(T,L)=>{let q={dataType:T||"download",progress:L,_ref:l,_update:S};return Ie.bind(this)(k,q)}};return {pathKey:f,obj:S}}catch{return null}}));for(let h of d)if(h){if(c[h.pathKey]){c[h.pathKey].push(h.obj);continue}c[h.pathKey]=[h.obj];}}t.bin=c;},prv_acs:o=>{for(let c in o)["notify_subscribers","upload_to_feed","feed_referencing_records","notify_referencing_records"].includes(c)?t.table.subscription[c]=o[c]:t.source[c]=o[c];},data:o=>{let c=o;o==="!D%{}"?c={}:o==="!L%[]"&&(c=[]),t.data=c;}};if(n.record_id)return n;for(let o in s)if(n.hasOwnProperty(o)){let c=s[o](n[o]);c instanceof Promise&&await c;}return i&&(t.user_id="anonymous:"+t.user_id),t}function Tr(n){let e=n.substring(3);switch(n.substring(0,3)){case "!S%":return e;case "!N%":let i=e.split("."),r=Number(i[0])-4503599627370496;return i.length===1?r:parseFloat(r.toString()+"."+i[1]);case "!B%":return e==="1";case "!L%":case "!D%":try{return JSON.parse(e)}catch{throw new a("Value parse error.",{code:"PARSE_ERROR"})}default:return n}}async function vt(n){let{endpoints:e}=n;if(typeof e=="string"&&(e=[e]),!Array.isArray(e))throw new a('"endpoints" should be type: array | string.',{code:"INVALID_PARAMETER"});let t=await R.bind(this)("del-files",{endpoints:e,storage:"records"},{auth:true,method:"post"}),i=[];for(let r in t)i.push(ie.bind(this)(t[r]));return Promise.all(i)}async function Ie(n,e){if(typeof n!="string")throw new a('"url" should be type: string.',{code:"INVALID_PARAMETER"});let t=n.split("?"),i=t.shift()||"",r=t.length?"?"+t.join("?"):"",s=g.Url(i);n=s+r;let o=false,c=s.split("/"),d=c[2].split("."),h=null;d.length===3&&d[1]==="skapi"&&(h=d[0],o=true);let u=c.slice(3),p=false;if(!o&&(u[0]==="auth"||u[0]==="publ"))try{g.UserId(u[2]),g.UserId(u[3]),p=u[0]=="auth",o=!0;}catch{throw new a("Invalid file url.",{code:"INVALID_PARAMETER"})}let A=h?null:u[1];if(e=g.Params(e,{expires:["number",()=>0],dataType:["base64","blob","endpoint","text","info",()=>"download"],progress:"function",_ref:[null,"string"],_update:_=>_}),e?.dataType==="info")return {url:n,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:B(u[9]),uploaded:B(u[8])};let f=n.split("/").slice(-1)[0],y=e.expires;if(y){if(!o)throw new a("Expires option can only be used on skapi cdn endpoints.",{code:"INVALID_PARAMETER"});if(y<0)throw new a('"config.expires" should be > 0. (seconds)',{code:"INVALID_PARAMETER"});let _={request:h?"get-host":"get",id:h||u[5],key:n,expires:y};A&&(_.service=A),n=(await R.bind(this)("get-signed-url",_,{auth:true})).url;}else if(p){let _=Math.floor(Date.now()/1e3);if(!this.bearerToken&&(!this.session?.idToken?.payload?.exp||this.session.idToken.payload.exp<_)){this.log("getFile:requesting new token",null);try{await F.bind(this)().getSession({refreshToken:!0}),this.log("getFile:received new tokens",{exp:this.session?.idToken?.payload?.exp,currTime:_,expiresIn:this.session?.idToken?.payload?.exp-_,token:this.session?.accessToken?.jwtToken,refreshToken:this.session?.refreshToken?.token});}catch(L){throw this.log("getFile:new token error",L),new a("User login is required.",{code:"INVALID_REQUEST"})}}let k=this.bearerToken||this.session?.idToken?.jwtToken;if(!k||!this.user?.user_id)throw new a("User login is required.",{code:"INVALID_REQUEST"});n+=`${n.includes("?")?"&":"?"}t=${encodeURIComponent(k)}`;let S=u[6]==="**"?"**":parseInt(u[6]),T=this.user?.access_group??-1;if(this.user.user_id!==u[3]&&(S==="**"||T<S)){let L=u[5];if(this.__private_access_key[L]&&typeof this.__private_access_key[L]=="string")n+=`&p=${encodeURIComponent(this.__private_access_key[L])}`;else if(this.owner!==this.host)try{let q=await this.requestPrivateRecordAccessKey({record_id:L,reference_id:e?._ref});n+=`&p=${encodeURIComponent(q)}`;}catch{}}}if(e?.dataType==="endpoint")return e._update&&(e._update.url=n),n;if(e?.dataType==="download"){let _=document.createElement("a");return _.href=n,document.body.appendChild(_),_.setAttribute("download",f),_.target="_blank",_.click(),document.body.removeChild(_),null}return new Promise(async(_,k)=>{try{let S=await R.bind(this)(n,null,{method:"get",contentType:null,responseType:e?.dataType==="text"?"text":"blob",fetchOptions:{progress:e?.progress}},{ignoreService:!0});if(e?.dataType==="base64"){let T=new FileReader;T.onloadend=()=>_(T.result),T.readAsDataURL(S);}else _(S);}catch(S){k(S);}})}async function Dt(n,e=false){n=D(n,{ignoreEmpty:true}).data||{};let t="",i=kt(n);if(i)n=i,t=n.record_id||n.unique_id,typeof t=="string"&&(typeof this.__private_access_key?.[t]=="string"&&(n.private_key=this.__private_access_key?.[t]||void 0),this.__my_unique_ids[t]&&(e?delete this.__my_unique_ids[t]:n.record_id=this.__my_unique_ids[t]));else {let r=await M.bind(this)(),s=n?.reference,o=false;typeof s=="object"&&Object.keys(s).length&&(s?.record_id||s?.unique_id?(t=s.record_id||s.unique_id,t&&typeof this.__private_access_key?.[t]=="string"&&(n.private_key=this.__private_access_key?.[t]||void 0),n.reference=t):s?.user_id&&(o=s.user_id===this.user?.user_id,n.reference=s.user_id)),typeof n?.table=="string"&&(n.table={name:n.table,access_group:0}),n.index&&n.index.hasOwnProperty("range")&&n.index.hasOwnProperty("condition")&&delete n.index.range;let c=l=>({table:{name:d=>Oe(d,"table.name"),access_group:Me.bind(this),subscription:d=>g.UserId(d,'User ID in "subscription"')},reference:"string",index:{name:["$updated","$uploaded","$referenced_count","$user_id",d=>de(d,"index.name")],value:d=>{let h={$updated:"number",$uploaded:"number",$referenced_count:"number",$user_id:g.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 a(`"index.value" should be type: ${u}.`,{code:"INVALID_PARAMETER"});return d}return typeof d=="string"&&!d?"":Re(d)},condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq"],range:d=>xt(d,l)},tag:d=>{if(d==null)return d;if(typeof d=="string")return Fe(d,"tag");throw new a('"tag" should be type: string.',{code:"INVALID_PARAMETER"})},private_key:"string"});n=g.Params(n||{},c(n),o||r?[]:["table"],{ignoreEmpty:true});}return {query:n,is_reference_fetch:t}}async function Ut(n,e){await this.__connection;let t=await Dt.bind(this)(n),i=t.is_reference_fetch,r=await R.bind(this)("get-records",t.query,{fetchOptions:e,auth:!!this.__user,method:this.__user?"post":"get"});i&&r?.reference_private_key&&typeof r.reference_private_key=="string"&&(this.__private_access_key[i]=r.reference_private_key);let s=[];for(let o in r.list)s.push(ie.bind(this)(r.list[o]));return r.list=await Promise.all(s),r}function Nt(n){let e="",t=[],i=g.Params(n||{},{record_id:s=>X(s,"record_id",{allowEmpty:false,onlyAlphanumeric:true}),unique_id:["string",null],readonly:"boolean",table:{name:s=>Oe(s,"table.name"),subscription:[null,{is_subscription_record:"boolean",upload_to_feed:"boolean",notify_subscribers:"boolean",feed_referencing_records:"boolean",notify_referencing_records:"boolean"}],access_group:Me.bind(this)},source:{referencing_limit:s=>{if(s===null)return null;if(typeof s=="number"){if(0>s)throw new a('"reference_limit" should be >= 0',{code:"INVALID_PARAMETER"});if(s>4503599627370546)throw new a('"reference_limit" should be <= 4503599627370546',{code:"INVALID_PARAMETER"});return s}throw new a('"reference_limit" should be type: <number | null>',{code:"INVALID_PARAMETER"})},prevent_multiple_referencing:"boolean",can_remove_referencing_records:"boolean",only_granted_can_reference:"boolean",allow_granted_to_grant_others:"boolean",referencing_index_restrictions:s=>{if(s===void 0)return;if(!s||Array.isArray(s)&&!s.length)return null;let o={name:l=>de(l,'"name" in "index_restrictions"'),value:l=>Re(l),condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne",()=>null],range:l=>{if(l!==null&&typeof s.value!=typeof l)throw new a('Index restriction "range" type should match the type of "value".',{code:"INVALID_PARAMETER"});if(!s.hasOwnProperty("value"))throw new a('Index restriction "value" is required.',{code:"INVALID_PARAMETER"});return l}};Array.isArray(s)||(s=[s]);let c=s.map(l=>g.Params(l,o,["name"]));if(c.length)for(let l of c)l.condition&&l.hasOwnProperty("range")&&delete l.range;return c}},reference:s=>{if(s===null)return {record_id:null};if(s){if(typeof s=="string")return e=s,this.__my_unique_ids[s]?this.__my_unique_ids[s]:s;if(typeof s!="object")throw new a('"reference" should be type: <string | object>.',{code:"INVALID_PARAMETER"});return g.Params(s,{unique_id:"string",record_id:o=>o==null?o:(e=o,typeof this.__private_access_key?.[o]=="string"&&(n.reference_private_key=this.__private_access_key[o]||void 0),X(o,"reference.record_id",{allowEmpty:false,onlyAlphanumeric:true}))})}},index:[null,{name:s=>de(s,"index.name"),value:s=>Re(s)}],tags:s=>{if(s==null)return s;if(typeof s=="string"&&(s=s.split(",").map(o=>o.trim())),!Array.isArray(s))throw new a('"tag" should be type: <string | string[]>.',{code:"INVALID_PARAMETER"});return s.map(o=>Fe(o,"tag"))},remove_bin:s=>{if(!s)return null;let o=[];if(Array.isArray(s))for(let c of s)if(typeof c=="string")o.push(decodeURIComponent(c.split("?")[0]));else if(c.url&&c.size&&c.filename){let d=c.url.split("/").slice(0,3).join("/")+"/"+c.path;o.push(d);}else throw new a('"remove_bin" should be type: <string[] | BinaryFile[] | null>',{code:"INVALID_PARAMETER"});else throw new a('"remove_bin" should be type: <string[] | BinaryFile[] | null>',{code:"INVALID_PARAMETER"});return o},progress:"function",data:s=>s},[],{precall:s=>{let o=s?.data||{};if(!o?.record_id&&!o.table)throw new a('"table.name" is required.',{code:"INVALID_PARAMETER"});typeof o.table=="string"&&(o.table={name:o.table,access_group:0}),s.files&&(t=s.files);}}),r=n.progress||null;if(delete i.progress,!this.__user){let s=!!(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 a("Public users cannot update existing records.",{code:"INVALID_REQUEST"});if(i.table.access_group!=="public"&&i.table.access_group!==0)throw new a("Public users can only post records to public tables.",{code:"INVALID_REQUEST"});if(s)throw new a("Public users cannot post subscription records.",{code:"INVALID_REQUEST"});if(i.remove_bin)throw new a("Public users cannot remove files from records.",{code:"INVALID_REQUEST"});if(i.unique_id)throw new a("Public users cannot set unique_id for records.",{code:"INVALID_REQUEST"})}return {config:i,progress:r,is_reference_post:e,files:t}}async function Ct(n){if(await this.__connection,!Array.isArray(n)||!n.length)throw new a('"params" should be a non-empty array.',{code:"INVALID_PARAMETER"});!this.__user;let t=[],i,r,s=null,c={_is_bulk_:n.map((p,A)=>{if(!p||typeof p!="object"||Array.isArray(p))throw new a(`"params[${A}]" should be type: <object>.`,{code:"INVALID_PARAMETER"});let f=Nt.bind(this)(p),y=f.config;if(f.is_reference_post&&t.push(f.is_reference_post),typeof y.progress=="function"&&s===null&&(s=y.progress),y.service!==void 0){if(i===void 0)i=y.service;else if(i!==y.service)throw new a('All bulk params should share the same "service" value.',{code:"INVALID_PARAMETER"})}if(y.owner!==void 0){if(r===void 0)r=y.owner;else if(r!==y.owner)throw new a('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:""};i!==void 0&&(c.service=i),r!==void 0&&(c.owner=r);let l={auth:!!this.__user,method:"post"},d={};Object.keys(d).length&&Object.assign(l,{fetchOptions:d});let h=await R.bind(this)("post-record",c,l),u=await Promise.all(h.map(p=>ie.bind(this)(p,"called from postRecord")));for(let p=0;p<h.length;p++){let A=h[p],f=u[p];if(typeof A?.reference_private_key=="string")for(let y of t)this.__private_access_key[y]=A.reference_private_key;f?.unique_id&&(this.__my_unique_ids[f.unique_id]=f.record_id);}return u}async function Lt(n,e,t){if(await this.__connection,!e)throw new a('"config" argument is required.',{code:"INVALID_PARAMETER"});let i=Nt.bind(this)(e),r=i.config,s=i.progress,o=i.is_reference_post,c={auth:!!this.__user,method:"post"},l=[],d=D(n);t&&Array.isArray(t)&&t.length&&(l=l.concat(t)),d.files&&Array.isArray(d.files)&&d.files.length&&(l=l.concat(d.files));let h=null;h=Object.assign({data:d.data},r);let u={};typeof s=="function"&&(u.progress=s),Object.keys(u).length&&Object.assign(c,{fetchOptions:u});let p=await R.bind(this)("post-record",h,c);if($()&&l.length){let f=new FormData;for(let _ of l)f.append(_.name,_.file,_.file.name);let y={record_id:p.rec,progress:s};r.hasOwnProperty("service")&&(y.service=r.service);let{bin_endpoints:P}=await we.bind(this)(f,y);p.bin?p.bin.push(...P):p.bin=P;}o&&typeof p?.reference_private_key=="string"&&(this.__private_access_key[o]=p.reference_private_key);let A=await ie.bind(this)(p,"called from postRecord");return A.unique_id&&(this.__my_unique_ids[A.unique_id]=A.record_id,$()&&window.sessionStorage.setItem(`${this.service}:uniqueids`,JSON.stringify(this.__my_unique_ids))),A}async function Ot(n,e){let t=await R.bind(this)("get-table",g.Params(n||{},{table:"string",condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}),Object.assign({auth:!!this.__user},{fetchOptions:e})),i={cnt_rec:"number_of_records",tbl:"table",srvc:"service"};if(Array.isArray(t?.list))for(let r of t.list)for(let s in i)r.hasOwnProperty(s)&&(r[i[s]]=r[s],delete r[s]);return t}async function Ft(n,e){if(!n?.table)throw new a('"table" is required.',{code:"INVALID_PARAMETER"});let t=g.Params(n||{},{table:"string",index:s=>de(s,"index.name"),order:{by:["average_number","total_number","number_count","average_bool","total_bool","bool_count","string_count","index_name","number_of_records"],value:["string","number","boolean"],condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}},["table"]);if(t.hasOwnProperty("order")){if(!t.order?.by)throw new a('"order.by" is required.',{code:"INVALID_PARAMETER"});if(t.order.hasOwnProperty("condition")&&!t.order.hasOwnProperty("value"))throw new a('"value" is required for "condition".',{code:"INVALID_PARAMETER"});if(t.hasOwnProperty("index")&&t.index.substring(t.index.length-1)!==".")throw new a('"index" should be a parent index name of the compound index when using "order.by"',{code:"INVALID_PARAMETER"})}let i=await R.bind(this)("get-index",t,Object.assign({auth:!!this.__user},{fetchOptions:e})),r={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(i?.list)&&(i.list=i.list.map(s=>{let o=s.idx.split("/"),c={table:o[1],index:o[2],number_of_records:s.cnt_rec};for(let l in r)Object.prototype.hasOwnProperty.call(s,l)&&(c[r[l]]=s[l]);return c})),i}async function Mt(n,e){let t=await R.bind(this)("get-tag",g.Params(n||{},{table:"string",tag:"string",condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}),Object.assign({auth:!!this.__user},{fetchOptions:e}));return Array.isArray(t?.list)&&(t.list=t.list.map(i=>{let r=i.tag.split("/");return {table:r[1],tag:r[0],number_of_records:i.cnt_rec}})),t}async function Vt(n,e){let t=await R.bind(this)("get-uniqueid",g.Params(n||{},{unique_id:"string",condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}),Object.assign({auth:!!this.__user},{fetchOptions:e}));if(Array.isArray(t?.list))for(let i in t.list){let r=t.list[i];t.list[i]={unique_id:r.unq,record_id:r.rec};}return t}async function $t(n,e){await this.__connection;let t=await Dt.bind(this)(n,true),i=t.is_reference_fetch,r=await R.bind(this)("del-records",t.query,{auth:true,fetchOptions:e});return i&&typeof r?.reference_private_key=="string"&&(this.__private_access_key[i]=r.reference_private_key),r?.message||r}function qt(n){return Qt.bind(this)({record_id:n.record_id,user_id:n.user_id,execute:"add"})}function jt(n){return Qt.bind(this)({record_id:n.record_id,user_id:n.user_id||null,execute:"remove"})}async function Bt(n,e){let t={record_id:n.record_id||void 0,user_id:n.user_id||void 0,execute:"list"};if(!t.record_id&&!t.user_id)throw new a("Either record_id or user_id must be provided.",{code:"INVALID_PARAMETER"});if(t.user_id)if(typeof t.user_id=="string")g.UserId(t.user_id),t.user_id=[t.user_id];else if(Array.isArray(t.user_id))for(let s of t.user_id)g.UserId(s);else throw new a("user_id should be type: <string | string[]>",{code:"INVALID_PARAMETER"});let i=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),r=await R.bind(this)("grant-private-access",t,{auth:true,fetchOptions:e});return r.list=r.list.map(i),r}function Kt(n){let e=n.record_id,t=n.reference_id||void 0;if(!e)throw new a("Record ID is required.",{code:"INVALID_PARAMETER"});if(typeof e!="string")throw new a("Record ID should be type: <string | string[]>",{code:"INVALID_PARAMETER"});if(t&&typeof t!="string")throw new a("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(Ae[e])return Ae[e];let i=R.bind(this)("request-private-access-key",{record_id:e,reference_id:t},{auth:true}).then(r=>{let s=typeof r=="string"?r:r?.private_key;if(typeof s!="string")throw new a("Invalid private access key response.",{code:"ERROR"});return this.__private_access_key[e]=s,s}).finally(()=>{delete Ae[e];});return Ae[e]=i,i}function Qt(n){n.execute;let t=g.Params(n,{record_id:"string",user_id:i=>{if(!i)throw new a("User ID is required.",{code:"INVALID_PARAMETER"});let r=i;if(typeof r=="string"&&(r=[r]),r.length>100)throw new a("Cannot process more than 100 users at once.",{code:"INVALID_REQUEST"});for(let s of r)g.UserId(s,'User ID in "user_id"');return r},execute:["add","remove"]},["execute","record_id","user_id"]);return t.user_id||(t.user_id=null),R.bind(this)("grant-private-access",t,{auth:true})}var I={},C={},K={},H={},W={},Te={},Pe={};function Wt(n,e,t){n[e]||(n[e]=[]),n[e].push(t);}async function Se(n,e,t){let i=[];if(n[e]){for(let r of n[e])if(r){let s=t(r);s instanceof Promise&&(s=await s),i.push(s);}delete n[e];}return i}async function $e(n,e){if(!this?.session?.accessToken?.jwtToken)throw new a("Access token is required.",{code:"INVALID_PARAMETER"});let t=await this.__socket;async function i(r,s,o){this.log("answerSdpOffer from",s),await I[s].setRemoteDescription(new RTCSessionDescription(r));let c=await I[s].createAnswer();await I[s].setLocalDescription(c),o.send(JSON.stringify({action:"rtc",uid:s,content:{sdpanswer:c},token:this.session.accessToken.jwtToken}));}I?.[e]?n?(await Se(Pe,e,r=>i.bind(this)(r,e,t)),await i.bind(this)(n,e,t)):await Se(Pe,e,r=>i.bind(this)(r,e,t)):n&&Wt(Pe,e,n);}async function qe(n,e){if(this.log("receiveIceCandidate",n),I?.[e]&&I[e]?.remoteDescription&&I[e]?.remoteDescription?.type){if(!n)return Se(Te,e,t=>I[e].addIceCandidate(t));await Se(Te,e,t=>I[e].addIceCandidate(t)),await I[e].addIceCandidate(n);}else Wt(Te,e,n);}async function Q(n){if(typeof window>"u"||window._runningInNodeJS)throw new a("WebRTC is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});g.Params(n,{cid:s=>{if(typeof s!="string")throw new a('"cid" should be type: <string>.',{code:"INVALID_PARAMETER"});if(s&&s.slice(0,4)!=="cid:")throw new a('"cid" should be a valid connection id.',{code:"INVALID_PARAMETER"});return s},close:"boolean"});let e=await this.__socket,{cid:t,close_all:i=false}=n||{};if(!i&&!t)throw new a('"cid" is required.',{code:"INVALID_PARAMETER"});let r=s=>{if(!s)throw new a('"cid" is required.',{code:"INVALID_PARAMETER"});if(delete Pe[s],delete Te[s],C[s]&&Object.values(C[s]).forEach(o=>{o.readyState!=="closed"&&o.close();}),delete C[s],I?.[s]){I[s].connectionState!=="closed"&&(I[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:I[s],timestamp:new Date().toISOString(),state:I[s].connectionState,iceState:I[s].iceConnectionState,signalingState:I[s].signalingState};W[s]&&W[s](o),this.log("closeRTC",o);}delete W[s],delete H[s],delete K[s],delete I[s];};if(i)for(let s in I)r(s);else r(t);this.log("Cleaning up media stream..."),this.__mediaStream&&(this.__mediaStream.getTracks().forEach(s=>{s.stop();}),this.__mediaStream=null);}async function Ht(n){if(n instanceof MediaStream)return n;if(!n.video&&!n.audio){let e=new MediaStream,t=document.createElement("canvas");t.width=1,t.height=1;let r=t.captureStream().getVideoTracks()[0];return e.addTrack(r),e}return window.navigator.mediaDevices.getUserMedia(n)}async function Jt(n,e){if(typeof window>"u"||window._runningInNodeJS)throw new a("WebRTC is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(typeof e!="function")throw new a("Callback is required.",{code:"INVALID_PARAMETER"});if(!this?.session?.accessToken?.jwtToken)throw new a("Access token is required.",{code:"INVALID_PARAMETER"});n=g.Params(n,{cid:o=>{if(typeof o!="string")throw new a('"cid" should be type: <string>.',{code:"INVALID_PARAMETER"});if(o&&o.slice(0,4)!=="cid:")throw new a('"cid" should be a valid connection id.',{code:"INVALID_PARAMETER"});return o},ice:["string",()=>"stun:stun.skapi.com:3468"],media:o=>o,channels:["text-chat","file-transfer","video-chat","voice-chat","gaming",{ordered:"boolean",maxPacketLifeTime:"number",maxRetransmits:"number",protocol:"string"},()=>[{ordered:true,maxPacketLifeTime:10,protocol:"default"}]]},["cid"]);let{cid:t,ice:i}=n;if(!(n?.media instanceof MediaStream)&&(n?.media?.video||n?.media?.audio)&&window.location.hostname!=="localhost"&&window.location.protocol!=="https:")throw new a("Media stream is only supported on either localhost or https.",{code:"INVALID_REQUEST"});let r=this.__socket?await this.__socket:this.__socket;if(!r)throw new a("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});if(r.readyState!==1)throw new a("Realtime connection is not ready.",{code:"INVALID_REQUEST"});let s={iceServers:[{urls:i}]};I?.[t]||(I[t]=new RTCPeerConnection(s)),n?.media&&(this.__mediaStream=await Ht(n.media),this.__mediaStream.getTracks().forEach(o=>{I[t].addTrack(o,this.__mediaStream);})),W[t]=e,C[t]||(C[t]={});for(let o=0;o<n.channels.length;o++){let c=n.channels[o];if(typeof c=="string")switch(c){case "text-chat":c={ordered:true,maxRetransmits:10,protocol:"text-chat"};break;case "file-transfer":c={ordered:false,maxPacketLifeTime:3e3,protocol:"file-transfer"};break;case "video-chat":c={ordered:true,maxRetransmits:10,protocol:"video-chat"};break;case "voice-chat":c={ordered:true,maxRetransmits:10,protocol:"voice-chat"};break;case "gaming":c={ordered:false,maxPacketLifeTime:100,protocol:"gaming"};break;default:c={ordered:true,maxRetransmits:10,protocol:"default"};break}let l=c.protocol||"default";if(Object.keys(C[t]).includes(l))throw new a(`Data channel with the protocol "${l}" already exists.`,{code:"INVALID_REQUEST"});let d=I[t].createDataChannel(l,c);C[t][l]=d;}for(let o in C[t]){let c=C[t][o];Xt.bind(this)(t,c);}return Gt.bind(this)(t,["onnegotiationneeded"]),await Ve.bind(this)(t),{hangup:()=>K[t]&&K[t](false),connection:new Promise(o=>{K[t]=(c=>{if(this.log("receiver picked up the call",t),!c)return Q.bind(this)({cid:t}),null;I[t].onnegotiationneeded=()=>{this.log("onnegotiationneeded",`sending offer to "${t}".`),Ve.bind(this)(t),W[t]&&W[t]({type:"negotiationneeded",target:I[t],timestamp:new Date().toISOString(),signalingState:I[t].signalingState,connectionState:I[t].iceConnectionState,gatheringState:I[t].iceGatheringState});},o({target:I[t],channels:C[t],hangup:()=>Q.bind(this)({cid:t}),media:this.__mediaStream});}).bind(this);})}}function zt(n){return async(e,t)=>{e=e||{},e=D(e).data;let i=n.sender_cid,r=await this.__socket;if(!H[i])return null;if(typeof t!="function")throw new a("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 a("Media stream is only supported on either localhost or https.",{code:"INVALID_REQUEST"});let{ice:s="stun:stun.skapi.com:3468"}=e;return I?.[i]||(I[i]=new RTCPeerConnection({iceServers:[{urls:s}]})),e?.media&&(this.__mediaStream=await Ht(e.media),this.__mediaStream.getTracks().forEach(o=>{I[i].addTrack(o,this.__mediaStream);})),delete H[i],W[i]=t,C[i]||(C[i]={}),I[i].ondatachannel=o=>{this.log("ondatachannel",`received data channel "${o.channel.label}".`);let c=o.channel;C[i][c.label]=c,Xt.bind(this)(i,c);},Gt.bind(this)(i,["onnegotiationneeded"]),await $e.bind(this)(null,i),await qe.bind(this)(null,i),r.send(JSON.stringify({action:"rtc",uid:i,content:{pickup:this.user.user_id},token:this.session.accessToken.jwtToken})),{target:I[i],channels:C[i],hangup:()=>Q.bind(this)({cid:i}),media:this.__mediaStream}}}async function Ve(n){if(!this?.session?.accessToken?.jwtToken)throw new a("Access token is required.",{code:"INVALID_PARAMETER"});this.log("sendOffer",n);let e=await this.__socket,t=await I[n].createOffer();await I[n].setLocalDescription(t);let i=I[n].localDescription;this.log("rtcSdpOffer to",i),e.send(JSON.stringify({action:"rtc",uid:n,content:{sdpoffer:i},token:this.session.accessToken.jwtToken}));}async function Pr(n,e){if(!this?.session?.accessToken?.jwtToken)throw new a("Access token is required.",{code:"INVALID_PARAMETER"});this.log("sendIceCandidate to",e);let t=await this.__socket;if(!n.candidate){this.log("candidate-end","all ice candidates have been sent");return}let i=W[e]||(()=>{}),r=n.candidate;this.log("ice gathering state set to",I[e].iceGatheringState),i({type:"icecandidate",target:I[e],timestamp:new Date().toISOString(),candidate:n.candidate.candidate,sdpMid:n.candidate.sdpMid,sdpMLineIndex:n.candidate.sdpMLineIndex,usernameFragment:n.candidate.usernameFragment,protocol:n.candidate.protocol,gatheringState:I[e].iceGatheringState,connectionState:I[e].iceConnectionState}),t.send(JSON.stringify({action:"rtc",uid:e,content:{candidate:r},token:this.session.accessToken.jwtToken}));}function Gt(n,e){let t=new Set(e),i=W[n]||(o=>{}),r=I[n],s={ontrack:o=>{i({type:"track",target:r,timeStamp:o.timeStamp,streams:o.streams,track:o.track});},onicecandidate:o=>{Pr.bind(this)(o,n),o.candidate?i({type:"icecandidate",target:r,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:r.iceGatheringState,connectionState:r.iceConnectionState}):i({type:"icecandidateend",target:r,timestamp:new Date().toISOString()});},onicecandidateerror:o=>{i({type:"icecandidateerror",target:r,timestamp:new Date().toISOString(),errorCode:o.errorCode,errorText:o.errorText,url:o.url,hostCandidate:o.hostCandidate,gatheringState:r.iceGatheringState,connectionState:r.iceConnectionState});},oniceconnectionstatechange:()=>{i({type:"iceconnectionstatechange",target:r,timestamp:new Date().toISOString(),state:r.iceConnectionState,gatheringState:r.iceGatheringState,signalingState:r.signalingState});},onicegatheringstatechange:()=>{i({type:"icegatheringstatechange",target:r,timestamp:new Date().toISOString(),state:r.iceGatheringState,connectionState:r.iceConnectionState,signalingState:r.signalingState});},onsignalingstatechange:()=>{i({type:"signalingstatechange",target:r,timestamp:new Date().toISOString(),state:r.signalingState,connectionState:r.iceConnectionState,gatheringState:r.iceGatheringState});},onnegotiationneeded:()=>{Ve.bind(this)(n),i({type:"negotiationneeded",target:r,timestamp:new Date().toISOString(),signalingState:r.signalingState,connectionState:r.iceConnectionState,gatheringState:r.iceGatheringState});},onconnectionstatechange:()=>{i({type:"connectionstatechange",target:r,timestamp:new Date().toISOString(),state:r.connectionState,iceState:r.iceConnectionState,signalingState:r.signalingState});let o=r.connectionState;(o==="disconnected"||o==="failed"||o==="closed")&&Q.bind(this)({cid:n});}};for(let[o,c]of Object.entries(s))t.has(o)||(r[o]=c);}function Xt(n,e,t){let i=new Set(t),r=W[n]||(o=>{}),s={onmessage:o=>{let c={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),r(c);},onerror:o=>{let c={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),r(c);},onclose:o=>{let c={type:o.type,target:e,timeStamp:o.timeStamp,readyState:e.readyState,label:e.label,id:e.id};this.log(`${e.label}: closed`,null),r(c),C[n]&&(delete C[n][e.label],Object.keys(C[n]).length===0&&Q.bind(this)({cid:n}));},onbufferedamountlow:o=>{let c={target:e,bufferedAmount:e.bufferedAmount,bufferedAmountLowThreshold:e.bufferedAmountLowThreshold,type:o.type,timeStamp:o.timeStamp};this.log(`${e.label}: bufferedamountlow`,e.bufferedAmount),r(c);},onopen:o=>{this.log("dataChannel",`data channel: "${e.label}" is open and ready to send messages.`);let c={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};r(c);}};for(let[o,c]of Object.entries(s))i.has(o)||(e[o]=c);}var Y,Z=null,ge=true,se=0;async function Sr(){if(typeof window>"u"||window._runningInNodeJS)throw new a("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.getProfile(),!this.session)throw new a("No access.",{code:"INVALID_REQUEST"});let n=await this.record_endpoint;return new WebSocket(n.websocket_private+"?token="+this.session.accessToken.jwtToken)}var je=null;async function Zt(){if(typeof window>"u"||window._runningInNodeJS)throw new a("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});ge=true;let n=this.__socket?await this.__socket:this.__socket;Q.bind(this)({close_all:true}),Y&&Be.bind(this)({group:null}),se=0,Z&&(Z.terminate(),Z=null);try{n&&n.close();}catch{}return window.removeEventListener("visibilitychange",je),this.__socket=null,null}async function ke(n,e=50,t){if(typeof window>"u"||window._runningInNodeJS)throw new a("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(typeof n!="function")throw new a("Callback must be a function.",{code:"INVALID_REQUEST"});if(t==="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(ge&&(je=()=>{!document.hidden&&!ge&&ke.bind(this)(n,0,"reconnect");},this.__socket instanceof Promise))return this.__socket;Z&&(Z.terminate(),Z=null),this.__socket=new Promise(async i=>{await ne.bind(this)(),setTimeout(async()=>{let r=await Sr.bind(this)();r.onopen=()=>{ge=false,se=0,t!=="reconnect"&&window.addEventListener("visibilitychange",je),this.log("realtime onopen","Connected to WebSocket server."),n({type:"success",message:"Connected to WebSocket server."}),Y&&r.send(JSON.stringify({action:"joinRoom",rid:Y,token:this.session.accessToken.jwtToken}));let s=`
206
+ var Ln=Object.defineProperty;var On=Object.getOwnPropertyDescriptor;var ee=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var y=(n,e,t,i)=>{for(var r=On(e,t),s=n.length-1,o;s>=0;s--)(o=n[s])&&(r=(o(e,t,r))||r);return r&&Ln(e,t,r),r};var J=typeof globalThis<"u"?globalThis:void 0,he=J?.window;function Fn(n){if(Buffer)return Buffer.from(n).toString("base64");let e="",t=new Uint8Array(n),i=32768;for(let r=0;r<t.length;r+=i){let s=t.subarray(r,r+i);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(he)he.global=he,he.global._runningInNodeJS=false;else if(J&&(J.global=J,typeof J.window>"u")){class n{constructor(){this.result=null;this.error=null;this.onload=null;this.onloadend=null;this.onerror=null;}readAsDataURL(i){i.arrayBuffer().then(r=>{let s=Fn(r),o=i.type||"application/octet-stream";this.result=`data:${o};base64,${s}`,this.onload&&this.onload({target:this}),this.onloadend&&this.onloadend({target:this});}).catch(r=>{this.error=r,this.onerror&&this.onerror({target:this});});}readAsArrayBuffer(i){i.arrayBuffer().then(r=>{this.result=r,this.onload&&this.onload({target:this}),this.onloadend&&this.onloadend({target:this});}).catch(r=>{this.error=r,this.onerror&&this.onerror({target:this});});}readAsText(i,r="utf-8"){i.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});});}}J.FileReader=n;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(i,r){this._method=i,this._url=r,this.readyState=1;}setRequestHeader(i,r){this._headers[i]=r;}getResponseHeader(i){return null}abort(){this._aborted=true,this.onabort&&this.onabort({});}send(i){if(this._aborted)return;let r={method:this._method,headers:this._headers};i&&this._method!=="GET"&&this._method!=="HEAD"&&(r.body=i),fetch(this._url,r).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);});}}J.XMLHttpRequest=e,J.window={_runningInNodeJS:true,alert:t=>console.error("[Alert]",t),sessionStorage:{getItem:t=>null,setItem:(t,i)=>{},removeItem:t=>{}},localStorage:{getItem:t=>{let i=ee("fs"),r=ee("path");try{let s=r.resolve(process.cwd(),"states","localStorage",`${t}.skapi`);return i.existsSync(s)?i.readFileSync(s,"utf8"):null}catch{return null}},setItem:(t,i)=>{let r=ee("fs"),s=ee("path");try{let o=s.resolve(process.cwd(),"states","localStorage");r.existsSync(o)||r.mkdirSync(o,{recursive:!0});let c=s.resolve(o,`${t}.skapi`);r.writeFileSync(c,i,"utf8");}catch{}},removeItem:t=>{let i=ee("fs"),r=ee("path");try{let s=r.resolve(process.cwd(),"states","localStorage",`${t}.skapi`);i.existsSync(s)&&i.unlinkSync(s);}catch{}}},location:{href:"",origin:"",hostname:"",protocol:"",replace:t=>{}},navigator:{userAgent:`nodejs/${J?.process?.versions?.node||"unknown"}`,mediaDevices:{getUserMedia:async t=>{throw new Error("getUserMedia is not supported in Node.js environment.")}}},addEventListener:()=>{},removeEventListener:()=>{}};}var a=class extends Error{constructor(e,t){if(Array.isArray(e)&&e.length<=2){let i=e[1];if(e.length>2)for(let r=2;r<e.length&&typeof e[r]=="string";r++)i+=e[r];super((i||"Something went wrong.").trim()),this.name=t?.name||"SKAPI",this.code=t?.code||e[0]||"ERROR",t?.cause&&(this.cause=t.cause);}else super((e?.message||(typeof e=="string"?e:"Something went wrong.")).trim()),typeof e=="string"?(this.name=t?.name||"SKAPI",this.code=t?.code||"ERROR",t?.cause&&(this.cause=t.cause)):e instanceof Error?(this.cause=e,this.name=e.name,e.hasOwnProperty("code")&&(this.code=e.code)):typeof e=="object"&&e?.code&&e?.message&&(this.name=t?.name||"SKAPI",this.code=t?.code||"ERROR",this.cause=e?.cause);}};var z="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",ve=BigInt(z.length),Mn=2*1024*1024,Vn=["aud","cognito:username","event_id","exp","iat","iss","jti","origin_jti","secret_key","token_use"],Qe={auth_time:"log",sub:"user_id"},$n=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f","g","h","i","j","k","l"],Ge=["us31","us72","ap51","ap22","ap41","eu71","ap21","us32","us71","af51","ap31","ap43","ap23","ap42","ca01","eu01","eu72","eu51","eu73","eu11","me51","sa31"],He=typeof TextEncoder<"u"?new TextEncoder:null;function qn(){if(typeof globalThis<"u")return globalThis.Buffer}function jn(n){if(He)return He.encode(n);let e=unescape(encodeURIComponent(n)),t=new Uint8Array(e.length);for(let i=0;i<e.length;i++)t[i]=e.charCodeAt(i);return t}function Bn(n){if(n instanceof Uint8Array)return n;if(typeof n=="string")return jn(n);if(typeof ArrayBuffer<"u"&&n instanceof ArrayBuffer)return new Uint8Array(n);if(typeof ArrayBuffer<"u"&&ArrayBuffer.isView(n))return new Uint8Array(n.buffer,n.byteOffset,n.byteLength);if(Array.isArray(n))return Uint8Array.from(n);let e=qn();if(e)return new Uint8Array(e.from(n));throw new Error("No byte conversion available in this environment.")}var m=class m{static hash(e){typeof e!="string"&&(console.warn("coercing non-string value to empty string"),e="");let t=m.sb(e),i=1732584193,r=-271733879,s=-1732584194,o=271733878,c,l,d,h;for(let u=0;u<t.length;u+=16)c=i,l=r,d=s,h=o,i=m.ff(i,r,s,o,t[u],7,-680876936),o=m.ff(o,i,r,s,t[u+1],12,-389564586),s=m.ff(s,o,i,r,t[u+2],17,606105819),r=m.ff(r,s,o,i,t[u+3],22,-1044525330),i=m.ff(i,r,s,o,t[u+4],7,-176418897),o=m.ff(o,i,r,s,t[u+5],12,1200080426),s=m.ff(s,o,i,r,t[u+6],17,-1473231341),r=m.ff(r,s,o,i,t[u+7],22,-45705983),i=m.ff(i,r,s,o,t[u+8],7,1770035416),o=m.ff(o,i,r,s,t[u+9],12,-1958414417),s=m.ff(s,o,i,r,t[u+10],17,-42063),r=m.ff(r,s,o,i,t[u+11],22,-1990404162),i=m.ff(i,r,s,o,t[u+12],7,1804603682),o=m.ff(o,i,r,s,t[u+13],12,-40341101),s=m.ff(s,o,i,r,t[u+14],17,-1502002290),r=m.ff(r,s,o,i,t[u+15],22,1236535329),i=m.gg(i,r,s,o,t[u+1],5,-165796510),o=m.gg(o,i,r,s,t[u+6],9,-1069501632),s=m.gg(s,o,i,r,t[u+11],14,643717713),r=m.gg(r,s,o,i,t[u],20,-373897302),i=m.gg(i,r,s,o,t[u+5],5,-701558691),o=m.gg(o,i,r,s,t[u+10],9,38016083),s=m.gg(s,o,i,r,t[u+15],14,-660478335),r=m.gg(r,s,o,i,t[u+4],20,-405537848),i=m.gg(i,r,s,o,t[u+9],5,568446438),o=m.gg(o,i,r,s,t[u+14],9,-1019803690),s=m.gg(s,o,i,r,t[u+3],14,-187363961),r=m.gg(r,s,o,i,t[u+8],20,1163531501),i=m.gg(i,r,s,o,t[u+13],5,-1444681467),o=m.gg(o,i,r,s,t[u+2],9,-51403784),s=m.gg(s,o,i,r,t[u+7],14,1735328473),r=m.gg(r,s,o,i,t[u+12],20,-1926607734),i=m.hh(i,r,s,o,t[u+5],4,-378558),o=m.hh(o,i,r,s,t[u+8],11,-2022574463),s=m.hh(s,o,i,r,t[u+11],16,1839030562),r=m.hh(r,s,o,i,t[u+14],23,-35309556),i=m.hh(i,r,s,o,t[u+1],4,-1530992060),o=m.hh(o,i,r,s,t[u+4],11,1272893353),s=m.hh(s,o,i,r,t[u+7],16,-155497632),r=m.hh(r,s,o,i,t[u+10],23,-1094730640),i=m.hh(i,r,s,o,t[u+13],4,681279174),o=m.hh(o,i,r,s,t[u],11,-358537222),s=m.hh(s,o,i,r,t[u+3],16,-722521979),r=m.hh(r,s,o,i,t[u+6],23,76029189),i=m.hh(i,r,s,o,t[u+9],4,-640364487),o=m.hh(o,i,r,s,t[u+12],11,-421815835),s=m.hh(s,o,i,r,t[u+15],16,530742520),r=m.hh(r,s,o,i,t[u+2],23,-995338651),i=m.ii(i,r,s,o,t[u],6,-198630844),o=m.ii(o,i,r,s,t[u+7],10,1126891415),s=m.ii(s,o,i,r,t[u+14],15,-1416354905),r=m.ii(r,s,o,i,t[u+5],21,-57434055),i=m.ii(i,r,s,o,t[u+12],6,1700485571),o=m.ii(o,i,r,s,t[u+3],10,-1894986606),s=m.ii(s,o,i,r,t[u+10],15,-1051523),r=m.ii(r,s,o,i,t[u+1],21,-2054922799),i=m.ii(i,r,s,o,t[u+8],6,1873313359),o=m.ii(o,i,r,s,t[u+15],10,-30611744),s=m.ii(s,o,i,r,t[u+6],15,-1560198380),r=m.ii(r,s,o,i,t[u+13],21,1309151649),i=m.ii(i,r,s,o,t[u+4],6,-145523070),o=m.ii(o,i,r,s,t[u+11],10,-1120210379),s=m.ii(s,o,i,r,t[u+2],15,718787259),r=m.ii(r,s,o,i,t[u+9],21,-343485551),i=m.ad(i,c),r=m.ad(r,l),s=m.ad(s,d),o=m.ad(o,h);return m.rh(i)+m.rh(r)+m.rh(s)+m.rh(o)}static rh(e){let t="";for(let i=0;i<=3;i++)t+=m.alphabet.charAt(e>>i*8+4&15)+m.alphabet.charAt(e>>i*8&15);return t}static ad(e,t){let i=(e&65535)+(t&65535);return (e>>16)+(t>>16)+(i>>16)<<16|i&65535}static rl(e,t){return e<<t|e>>>32-t}static cm(e,t,i,r,s,o){return m.ad(m.rl(m.ad(m.ad(t,e),m.ad(r,o)),s),i)}static ff(e,t,i,r,s,o,c){return m.cm(t&i|~t&r,e,t,s,o,c)}static gg(e,t,i,r,s,o,c){return m.cm(t&r|i&~r,e,t,s,o,c)}static hh(e,t,i,r,s,o,c){return m.cm(t^i^r,e,t,s,o,c)}static ii(e,t,i,r,s,o,c){return m.cm(i^(t|~r),e,t,s,o,c)}static sb(e){let t,i=(e.length+8>>6)+1,r=new Array(i*16);for(t=0;t<i*16;t++)r[t]=0;for(t=0;t<e.length;t++)r[t>>2]|=e.charCodeAt(t)<<t%4*8;return r[t>>2]|=128<<t%4*8,r[i*16-2]=e.length*8,r}};m.alphabet="0123456789abcdef";var V=m;function Xe(n){if(n===0)return z[0];let e="";for(;n>0;)e=z[n%62]+e,n=Math.floor(n/62);return e}function j(n){return n.split("").reverse().reduce((e,t,i)=>e+z.indexOf(t)*62**i,0)}function oe(n=6){let e="",t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",i=t.length,r=0;for(;r<n;)e+=t.charAt(Math.floor(Math.random()*i)),r+=1;return e}function De(){return typeof window>"u"||!!window?._runningInNodeJS}function $(){return !De()&&typeof document<"u"&&typeof document.createElement=="function"}function pe(n){let e;try{e=JSON.stringify(n);}catch{throw new a("Invalid data type.",{code:"INVALID_REQUEST"})}if(new Blob([e]).size>Mn)throw new a("Data should not exceed 2MB",{code:"INVALID_REQUEST"})}function We(n){return n===""||n==="on"||n==="true"}function Je(n){return n==="false"}function ze(n,e,t){e.name&&t(n,e.name,e.value);}var me=$(),Kn=typeof SubmitEvent<"u",Qn=typeof HTMLFormElement<"u";function N(n,e,t){let i={},r=[];function s(l,d,h){if(e?.ignoreEmpty&&h==="")return;if(e?.nullIfEmpty&&h===""&&(h=null),typeof t=="function"){let A=t(d,h);A!==void 0&&(h=A);}let u=d.split("[").map(A=>{let f=A.replace("]",""),R=Number(f);return !isNaN(R)&&!f.includes(".")?f=R:(f[0]==='"'&&f[f.length-1]==='"'||f[0]==="'"&&f[f.length-1]==="'")&&(f=f.replace(/"/g,"").replace(/'/g,"")),f}),p=l;if(typeof u[0]=="number")throw new a("Form key cannot start with an array index.",{code:"INVALID_REQUEST"});for(let A=0;A<u.length;A++){let f=u[A];A<u.length-1?(p[f]===void 0&&(typeof u[A+1]=="number"?p[f]=[]:p[f]={}),p=p[f]):p[f]===void 0?p[f]=h:Array.isArray(p[f])?p[f].push(h):p[f]=[p[f],h];}}function o(l,d,h){if(h instanceof File)l.push({name:d,file:h});else if(h instanceof FileList&&h&&h.length>0)for(let u=0;u<=h.length-1;u++){let p=h.item(u);p&&l.push({name:d,file:p});}}let c=l=>{l.name&&(l.type==="number"?l.value&&s(i,l.name,Number(l.value)):l.type==="checkbox"||l.type==="radio"?l.checked?l.type==="checkbox"&&l.value===""||We(l.value)?s(i,l.name,true):Je(l.value)?s(i,l.name,false):l.value&&s(i,l.name,l.value):l.type==="checkbox"&&(We(l.value)?s(i,l.name,false):Je(l.value)&&s(i,l.name,true)):l.type==="file"?l.files&&l.files.length>0&&o(r,l.name,l.files):s(i,l.name,l.value));};if(me&&(n instanceof HTMLInputElement||n instanceof HTMLSelectElement||n instanceof HTMLTextAreaElement))return c(n),pe(i),{data:i,files:r};if(me&&n instanceof FormData){for(let l of n.entries()){let d=l[0],h=l[1];if(h instanceof File||h instanceof FileList)o(r,d,h);else if(h instanceof Blob){let u=h;if(u.type==="application/json")try{let p=JSON.parse(u.text());s(i,d,p);}catch{s(i,d,u);}}else s(i,d,h);}return pe(i),{data:i,files:r}}if(me&&Kn&&n instanceof SubmitEvent&&(n=n.target),me&&Qn&&n instanceof HTMLFormElement){let l=n.querySelectorAll("input"),d=n.querySelectorAll("select"),h=n.querySelectorAll("textarea");for(let u=0;u<d.length;u++)ze(i,d[u],s);for(let u=0;u<h.length;u++)ze(i,h[u],s);for(let u=0;u<l.length;u++)c(l[u]);return pe(i),{data:i,files:r}}return pe(n),{data:n,files:r}}function ae(n){let e={};for(let t in n){let i=n[t];if(!Vn.includes(t))if(Qe[t])e[Qe[t]]=i;else if(t.includes("custom:"))e[t.replace("custom:","")]=i;else if(t==="address"){let r=i;if(r&&typeof r=="object"&&Object.keys(r).length){if(r?.formatted)try{e[t]=JSON.parse(r.formatted);}catch{e[t]=r.formatted;}}else e[t]=r;}else e[t]=i;}for(let t of ["address_public","birthdate_public","email_public","gender_public","phone_number_public","access_group"])t.includes("_public")?e.hasOwnProperty(t.split("_")[0])?e[t]=e.hasOwnProperty(t)?!!Number(e[t]):false:delete e[t]:e[t]=e.hasOwnProperty(t)?Number(e[t]):0;for(let t of ["email","phone_number"])e.hasOwnProperty(t)?e[t+"_verified"]=e[t+"_verified"]===true:delete e[t+"_verified"];return e}function Ue(n){if(n=Yn(n),n.split("-").length===7){let e=n.split("-"),t,i;try{t=Ge[j(e[1][0])],i=e.slice(2).join("-");}catch{throw new Error("INVALID_PARAMETER: Service ID is invalid.")}if(!t)throw new Error("INVALID_PARAMETER: Service ID is invalid.");return {service:t+e[0]+e[1].slice(1),owner:i}}return {service:n,owner:""}}function Ze(n,e){let t=Ge.indexOf(n.slice(0,4)),i=$n[t],s=`${n.slice(4,-4)}-${i}${n.slice(-4)}-${e}`;return Zn(s)}function Hn(n){let e=0n;for(let t of n){let i=z.indexOf(t);if(i<0)throw new Error(`INVALID_PARAMETER: Invalid base62 character: ${t}`);e=e*ve+BigInt(i);}return e}function Wn(n,e=1){if(n<0n)throw new Error("INVALID_PARAMETER: Negative values are not supported.");if(n===0n)return "0".repeat(Math.max(1,e));let t="",i=n;for(;i>0n;){let r=Number(i%ve);t=z[r]+t,i/=ve;}return t.length<e&&(t="0".repeat(e-t.length)+t),t}function Jn(n){if(n===0n)return Uint8Array.from([0]);let e=[],t=n;for(;t>0n;)e.push(Number(t&0xffn)),t>>=8n;return e.reverse(),Uint8Array.from(e)}function zn(n){let e=0n;for(let t of n)e=(e<<8n)+BigInt(t);return e}function Gn(n){let e=String(n).replace(/-/g,"");if(!/^[0-9a-fA-F]{32}$/.test(e))throw new Error("INVALID_PARAMETER: Invalid UUID format.");let t=new Uint8Array(16);for(let i=0;i<16;i++)t[i]=parseInt(e.slice(i*2,i*2+2),16);return t}function Xn(n){let e=Array.from(Bn(n),t=>t.toString(16).padStart(2,"0")).join("");return [e.slice(0,8),e.slice(8,12),e.slice(12,16),e.slice(16,20),e.slice(20)].join("-")}function Zn(n){let e=String(n);if(e.split("-").length===2)return e;let t=e.match(/^([0-9A-Za-z]+)-([0-9A-Za-z]+)-([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/);if(!t)throw new Error("INVALID_PARAMETER: Input must match <base62>-<base62>-<uuid>.");let[,i,r,s]=t;if(i.length<2)throw new Error("INVALID_PARAMETER: The first part must contain at least 2 characters.");if(r.length>=z.length)throw new Error("INVALID_PARAMETER: The middle section is too long to encode.");let o=i.slice(0,2),c=i.slice(2),l=r+o,d=z[r.length]+c+l,h=Gn(s),u=Wn(zn(h));return `${d}-${u}`}function Yn(n){let e=String(n);if(e.split("-").length!==2)return e;let t=e.split("-");if(t.length!==2||!t[0]||!t[1])throw new Error("INVALID_PARAMETER: Corrupt compressed token.");let[i,r]=t,s=z.indexOf(i[0]);if(s<0)throw new Error("INVALID_PARAMETER: Corrupt compressed token.");let o=i.slice(1),c=s+2;if(o.length<c)throw new Error("INVALID_PARAMETER: Corrupt compressed token.");let l=o.slice(0,o.length-c),d=o.slice(o.length-c),h=d.slice(s),u=d.slice(0,s),p=h+l;if(!/^[0-9A-Za-z]+$/.test(p)||!/^[0-9A-Za-z]+$/.test(u))throw new Error("INVALID_PARAMETER: Corrupt compressed token.");let A=Hn(r),f=Jn(A);if(f.length>16)throw new Error("INVALID_PARAMETER: Corrupt compressed token.");let R=new Uint8Array(16);R.set(f,16-f.length);let P=Xn(R);return `${p}-${u}-${P}`}function tr(n,e="User ID"){let t=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;if(n){if(typeof n!="string")throw new a(`${e} should be type: string.`,{code:"INVALID_PARAMETER"});if(!n.match(t))throw new a(`${e} is invalid.`,{code:"INVALID_PARAMETER"})}else throw new a(`${e} is empty.`,{code:"INVALID_PARAMETER"});return n}function nr(n){if(n&&(typeof n!="string"||n.charAt(0)!=="+"||isNaN(Number(n.substring(1)))))throw new a('"phone_number" is invalid. The format should be "+00123456789". Type: string.',{code:"INVALID_PARAMETER"});return n||""}function rr(n){if(n){if(typeof n!="string")throw new a('"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(n.length!==10||n.split("-").length!==3||!e.test(n))throw new a('"birthdate" is invalid. The format should be "yyyy-mm-dd". Type: string.',{code:"INVALID_PARAMETER"})}}return n||""}function ir(n){if(n){if(typeof n!="string")throw new a('"password" should be type: string.',{code:"INVALID_PARAMETER"});if(n.length<6)throw new a('"password" should be at least 6 characters.',{code:"INVALID_PARAMETER"});if(n.length>60)throw new a('"password" can be up to 60 characters max.',{code:"INVALID_PARAMETER"})}else throw new a('"password" is required.',{code:"INVALID_PARAMETER"});return n}function sr(n,e="email"){if(n){if(typeof n!="string")throw new a(`"${e}"should be type: string.`,{code:"INVALID_PARAMETER"});if(n.length<5)throw new a(`"${e}" should be at least 5 characters.`,{code:"INVALID_PARAMETER"});if(/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/.test(n)&&(n=n.trim(),n.split("@")[1].split(".").length>=2))return n.toLowerCase()}else throw new a(`"${e}" is required.`,{code:"INVALID_PARAMETER"});throw new a(`"${n}" is an invalid email.`,{code:"INVALID_PARAMETER"})}function or(n){let e=typeof window<"u",t=(()=>{let r=e&&window.location.origin||null;return r&&r.slice(-1)==="/"&&(r=r.slice(0,-1)),r})(),i=r=>{if(typeof r=="string"){if(r==="*")return "*";{let s=r.trim();if(s[0]==="/"&&t){if(t.slice(0,5)==="file:")throw new a(`"${r}" is an invalid url. Relative URL does not work on local file system. Use full URL string.`,{code:"INVALID_PARAMETER"});s=t+s;}else if(s[0]==="."&&t){if(t.slice(0,5)==="file:")throw new a(`"${r}" is an invalid url. Relative URL does not work on local file system. Use full URL string.`,{code:"INVALID_PARAMETER"});let c=e?window.location.href.split("?")[0]:"";c.slice(-1)!=="/"&&(c+="/"),s=c+s.slice(1);}let o;try{o=new URL(s);}catch{throw new a(`"${r}" is an invalid url.`,{code:"INVALID_PARAMETER"})}if(o.protocol)return o.href}}throw new a(`"${r}" is an invalid url.`,{code:"INVALID_PARAMETER"})};return Array.isArray(n)?n.map(r=>i(r)):i(n)}function ar(n,e,t=[],i){let r=N(n,i),s=r.data;e.service="string",e.owner="string";let o={};for(let c in e)if(s&&typeof s=="object"&&!Array.isArray(s)&&s.hasOwnProperty(c))if(typeof s[c]=="function")o[c]=s[c];else try{o[c]=JSON.parse(JSON.stringify(s[c]));}catch{o[c]=s[c];}i?.precall&&i.precall({data:o,files:r?.files||[]});try{return er(o,e,t)}catch(c){throw new a(c.message,{code:"INVALID_PARAMETER"})}}var g={UserId:tr,PhoneNumber:nr,Birthdate:rr,Password:ir,Email:sr,Url:or,Params:ar};var C=null;function Ne(n){let e={tkid:"ticket_id",cond:"condition",stmp:"timestamp",actn:"action",cnt:"count",ttl:"time_to_live",plch:"placeholder",hash:"hash",desc:"description",pmc:"limit_per_user"},t={};for(let i in n)if(i==="tkid"){let r=n[i].split("#");if(r.length===1){t.ticket_id=r[0];continue}t.ticket_id=r[1],t.consume_id=r[2],t.user_id=r[3];let s=r[2].slice(-4);if(t.is_test=s===":CHK",!n.stmp){let o=r[2].slice(0,-4);/^[0-9]+$/.test(o)?t.timestamp=parseInt(o,10):t.timestamp=j(r[2].slice(0,-4));}}else e[i]?t[e[i]]=n[i]:t[i]=n[i];return t}async function et(n){if(!n.ticket_id)throw new a("Ticket ID is required.",{code:"INVALID_PARAMETER"});if(!n.method)throw new a('Method is required. Should be either "GET" or "POST"',{code:"INVALID_PARAMETER"});let e=n.ticket_id;await this.__connection;let t=await E.bind(this)(`https://${this.service.slice(0,4)}.${this.customApiDomain}/auth/consume/${this.service}/${this.owner}/${e}`,n?.data||{},{method:n.method,auth:!!n?.auth});return Ne(t)}async function tt(n,e){await this.__connection;let t=await E.bind(this)("ticket",Object.assign({exec:"list"},n||{}),{auth:true,fetchOptions:e});return t.list=t.list.map(Ne),t}async function nt(n,e){await this.__connection;let t=await E.bind(this)("ticket",Object.assign({exec:"consumed"},n||{}),{auth:true,fetchOptions:e});return t.list=t.list.map(Ne),t}async function rt(n){return E.bind(this)("register-ticket",Object.assign({exec:"reg"},n),{auth:true})}async function it(n){return E.bind(this)("register-ticket",Object.assign({exec:"unreg"},n),{auth:true})}async function ne(){if(await this.__connection,this.session){let n=Math.floor(Date.now()/1e3),t=this.session.getIdToken().getExpiration();if(t<n){this.log("request:requesting new token",null);try{await F.bind(this)().getSession({refreshToken:!0}),this.log("request:received new tokens",{exp:this.session?.idToken?.payload?.exp,currentTime:n,expiresIn:t-n,token:this.session?.accessToken?.jwtToken,refreshToken:this.session?.refreshToken?.token});}catch(i){throw this.log("request:new token error",i),new a("User login is required.",{code:"INVALID_REQUEST"})}}else this.log("request:tokens",{exp:this.session.idToken.payload.exp,currentTime:n,expiresIn:t-n,token:this.session.accessToken.jwtToken,refreshToken:this.session.refreshToken.token});return this.session?.idToken?.jwtToken}else throw this.log("request:no session",null),G.bind(this)(),new a("User login is required.",{code:"INVALID_REQUEST"})}function Ye(n,e){return new Promise((t,i)=>{e.refreshSession(n.getRefreshToken(),(r,s)=>{this.log("getSession:refreshSessionCallback",{refreshErr:r,refreshedSession:s}),r?(G.bind(this)(),i(r)):s.isValid()?t(s):(G.bind(this)(),i(new a("Invalid session.",{code:"INVALID_REQUEST"})));});})}function F(){if(!this.userPool)throw new a("User pool is missing",{code:"INVALID_REQUEST"});let n=()=>{let s=C.getSignInUserSession().getIdToken().payload||null,o=ae(s);return this.log("normalized user attribute",o),this.__user=o,o},e=async s=>new Promise((o,c)=>{this.log("getSession:option",s);let{refreshToken:l=false,skipUserUpdateEventTrigger:d=false}=s||{};if(l&&d&&(d=false),C=this.userPool.getCurrentUser(),!C){this.log("getSession:cognitoUser",C),G.bind(this)(),c(null);return}let h=u=>{let p=u.getIdToken().payload;if(this.log("getSession:respond:sessionAttribute",p),p["custom:service"]!==this.service)throw this.log("getSession:respond","invalid service, signing out"),G.bind(this)(),new a("Invalid session.",{code:"INVALID_REQUEST"});return this.session=u,n(),d||this._runOnUserUpdateListeners(this.user),this.session};C.getSession((u,p)=>{if(this.log("getSession:getSessionCallback",{err:u,session:p}),!p){G.bind(this)(),c(new a("Current session does not exist.",{code:"INVALID_REQUEST"}));return}if(u){Ye.bind(this)(p,C).then(b=>o(h(b))).catch(c);return}let A=Math.floor(Date.now()/1e3),f=p.getIdToken(),R=f.getExpiration(),P=R<A;if(this.log("getSession:currentTime",A),this.log("getSession:idTokenExp",R),this.log("getSession:isExpired",P),this.log("getSession:existingBearerToken",this.bearerToken),this.bearerToken=f.getJwtToken(),P||l||!p.isValid())Ye.bind(this)(p,C).then(b=>o(h(b))).catch(c);else try{o(h(p));}catch(b){c(b);}});}),t=(s,o)=>{let c=o||s.includes(this.service+"-")?s:this.service+"-"+V.hash(s);return {cognitoUser:new CognitoUser({Username:c,Pool:this.userPool}),cognitoUsername:c}};return {getSession:e,authenticateUser:(s,o,c=false,l=false)=>new Promise((d,h)=>{this.__request_signup_confirmation=null,this.__disabledAccount=null;let u=t(s,c),p=u.cognitoUsername,A=new AuthenticationDetails({Username:p,Password:o});u.cognitoUser.authenticateUser(A,{newPasswordRequired:(f,R)=>{this.__disabledAccount=null,this.__request_signup_confirmation=p,f["custom:signup_ticket"]==="PASS"||f["custom:signup_ticket"]==="MEMBER"||f["custom:signup_ticket"]==="OIDPASS"?u.cognitoUser.completeNewPasswordChallenge(o,{},{onSuccess:P=>{C=u.cognitoUser,e().then(b=>d(this.user));},onFailure:P=>{h(new a(P.message||"Failed to authenticate user.",{code:P.code}));}}):h(new a("User's signup confirmation is required.",{code:"SIGNUP_CONFIRMATION_NEEDED"}));},onSuccess:f=>e({skipUserUpdateEventTrigger:true}).then(R=>{this.__disabledAccount=null,this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user),d(this.user);}),onFailure:f=>{let R=[],{parsed:P,code:b}=_e(f),x=typeof f?.message=="string"?f.message:"";if(b==="NotAuthorizedException"?x.includes("User is disabled.")?(this.__disabledAccount=p,R=["This account is disabled.","USER_IS_DISABLED"]):l?R=["The account already exists.","ACCOUNT_EXISTS"]:R=["Incorrect username or password.","INCORRECT_USERNAME_OR_PASSWORD"]:b==="UserNotFoundException"?R=["Incorrect username or password.","INCORRECT_USERNAME_OR_PASSWORD"]:b==="UserNotConfirmedException"?(this.__request_signup_confirmation=p,R=["User's signup confirmation is required.","SIGNUP_CONFIRMATION_NEEDED"]):(b==="TooManyRequestsException"||b==="LimitExceededException")&&(R=["Too many attempts. Please try again later.","REQUEST_EXCEED"]),P.code==="SIGNUP_CONFIRMATION_NEEDED"&&(this.__request_signup_confirmation=p),R.length){let k=R[1],T=R[0];h(new a(T,{code:k,cause:f}));}else h(P);}});}),createCognitoUser:t,signup:(s,o,c)=>new Promise((l,d)=>{this.userPool.signUp(s,o,c,null,(h,u)=>{if(h){let{parsed:p,code:A}=_e(h),f=[];A==="UsernameExistsException"?f=["The account already exists.","EXISTS"]:A==="InvalidPasswordException"?f=["Invalid password. Password must be at least 6 characters.","INVALID_PARAMETER"]:A==="InvalidParameterException"?f=[p.message||"Invalid parameter.","INVALID_PARAMETER"]:A==="TooManyRequestsException"||A==="LimitExceededException"?f=["Too many attempts. Please try again later.","REQUEST_EXCEED"]:A==="CodeDeliveryFailureException"?f=["Failed to deliver verification code.","CODE_DELIVERY_FAILURE"]:A==="UserLambdaValidationException"&&(f=[p.message||"Signup validation failed.","INVALID_REQUEST"]),f.length?d(new a(f[0],{code:f[1],cause:h})):d(p);return}l(u);});})}}function _e(n){let e=typeof n?.code=="string"&&n.code.trim()?n.code.trim():"ERROR",i=((typeof n?.message=="string"?n.message:typeof n=="string"?n:"An error occurred.")||"An error occurred.").trim();i||(i="An error occurred.");let r=i.match(/#([A-Za-z0-9_]+)\s*:\s*([\s\S]+)/),s=r?.[1]?.trim()||e,o=r?.[2]?.trim()||i;return {parsed:new a(o,{code:s,cause:n}),code:e}}async function st(n){await this.__authConnection;let e=n?.refreshToken||false;if(!e)return this.user;try{return await F.bind(this)().getSession(Object.assign({skipUserUpdateEventTrigger:!e,refreshToken:e},n)),this.user}catch{return null}}async function ot(n){await this.__connection,n=g.Params(n,{token:"string",id:"string",merge:s=>{if(s===void 0)return false;if(typeof s=="string")return [s];if(Array.isArray(s)){for(let o of s)if(typeof o!="string")throw new a('"merge" array items should be type: <string>.',{code:"INVALID_PARAMETER"})}if(typeof s!="boolean"&&!Array.isArray(s))throw new a('"merge" should be type: <boolean | string[]>.',{code:"INVALID_PARAMETER"});return s}});let e=await E.bind(this)("openid-logger",n),t=e.logger.split("#"),i=this.service+"-"+t[0],r=t[1];return {userProfile:await F.bind(this)().authenticateUser(i,r,true,true),openid:e.openid}}function fr(n){let e=typeof globalThis<"u"?globalThis:void 0;if(e?.Buffer)return e.Buffer.from(n,"base64").toString("utf8");if(typeof atob=="function"){let t=atob(n),i=new Uint8Array(t.length);for(let r=0;r<t.length;r++)i[r]=t.charCodeAt(r);return typeof TextDecoder<"u"?new TextDecoder().decode(i):t}throw new Error("No base64 decoder available in this environment")}function hr(n){let e=n.split(".");if(e.length!==3)throw new Error("Invalid JWT format");let i=e[1].replace(/-/g,"+").replace(/_/g,"/"),r=fr(i);return JSON.parse(r)}async function at(n){await this.__authConnection,this.log("loginWithToken:params",n),n=g.Params(n,{idToken:"string",accessToken:"string",refreshToken:"string"},["idToken"]);let e=hr(n.idToken);if(this.log("loginWithToken:idTokenPayload",e),e["custom:service"]!==this.service)throw new a("Token does not belong to this service.",{code:"INVALID_REQUEST"});let t=Math.floor(Date.now()/1e3);if(e.exp&&e.exp<t)throw new a("Token has expired.",{code:"INVALID_REQUEST"});if(this.__user=ae(e),this.session=null,n.accessToken&&n.refreshToken)try{if(this.session=new CognitoUserSession({IdToken:new CognitoIdToken({IdToken:n.idToken}),AccessToken:new CognitoAccessToken({AccessToken:n.accessToken}),RefreshToken:new CognitoRefreshToken({RefreshToken:n.refreshToken})}),this.log("loginWithToken:session",this.session),this.log("loginWithToken:CognitoUser",CognitoUser),this.log("loginWithToken:userPool",this.userPool),CognitoUser&&this.userPool){this.log("loginWithToken:cognito:username",e["cognito:username"]);let i={Username:e["cognito:username"],Pool:this.userPool};this.log("loginWithToken:cognitoUserParams",i),C=new CognitoUser(i),C.setSignInUserSession(this.session),this.log("loginWithToken:cognitoUserRestored",{cognitoUserType:typeof C,cognitoUserKeys:Object.keys(C||{}),cognitoUser:C});}}catch(i){this.log("loginWithToken:err",i);try{this.log("loginWithToken:err:stringified",JSON.stringify(i));}catch{this.log("loginWithToken:err:stringifyFail",String(i));}try{let r=Object.keys(i||{}),s=Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(i||{}):[],o=Object.getOwnPropertyDescriptors?Object.getOwnPropertyDescriptors(i||{}):{};this.log("loginWithToken:createSessionError:allKeys",{keys:r,symbols:s,descriptors:o});}catch(r){this.log("loginWithToken:createSessionError:allKeysFail",String(r));}}return this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user),this.user}async function M(){return await this.__connection,this.__user?.service===this.service?this.__user?.owner===this.host:(await ce.bind(this)(),false)}async function G(n=false){let e=null;C&&(n?e=new Promise((i,r)=>{C.globalSignOut({onSuccess:s=>{this.log("globalSignOut:success",s),i(s);},onFailure:s=>{this.log("globalSignOut:error",s),r(s);}});}):C.signOut());let t={session:null,__startKeyHistory:{},__cached_requests:{},__user:null};e&&(e=await e);for(let i in t)this[i]=t[i];return this._runOnUserUpdateListeners(null),this._runOnLoginListeners(null),e}async function ce(n){await this.__connection;let{data:e}=N(n);return await G.bind(this)(e?.global),"SUCCESS: The user has been logged out."}async function ct(){if(!this.__request_signup_confirmation)throw new a("Least one login attempt is required.",{code:"INVALID_REQUEST"});return await E.bind(this)("confirm-signup",{username:this.__request_signup_confirmation})}async function lt(n=false){if(typeof n=="string")n=g.Url(n);else if(typeof n!="boolean")throw new a("Argument should be type: <boolean | string>.",{code:"INVALID_REQUEST"});if(!this.__disabledAccount)throw new a("Least one signin attempt of disabled account is required.",{code:"INVALID_REQUEST"});return await E.bind(this)("recover-account",{username:this.__disabledAccount,redirect:n}),"SUCCESS: Recovery e-mail has been sent."}async function Ce(n){let e=g.Params(n,{username:"string",email:"string",password:"string"},["password"]);if(await this.__authConnection,e.email)try{g.Email(e.email);}catch{e.username=e.email,delete e.email;}if(!e.username&&!e.email)throw new a('Least one of "username" or "email" is required.',{code:"INVALID_PARAMETER"});return await F.bind(this)().authenticateUser(e.username||e.email,e.password)}async function ut(n,e){await this.__authConnection;let t={username:"string",password:d=>g.Password(d),email:d=>g.Email(d),name:"string",address:d=>{if(!d)return "";if(typeof d=="string")return d;if(typeof d=="object")return JSON.stringify(d)},gender:"string",birthdate:d=>d?g.Birthdate(d):"",phone_number:d=>d?g.PhoneNumber(d):"",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:d=>d?g.Url(d):"",profile:d=>d?g.Url(d):"",family_name:"string",given_name:"string",middle_name:"string",nickname:"string",website:d=>d?g.Url(d):""},i=g.Params(n||{},t,["email","password"]);await ce.bind(this)(),e=g.Params(e||{},{email_subscription:d=>{if(typeof d!="boolean")throw new a('"option.email_subscription" should be type: <boolean>.',{code:"INVALID_PARAMETER"});if(!e?.signup_confirmation)throw new a('"option.signup_confirmation" is required for email subscription.',{code:"INVALID_PARAMETER"});return d},signup_confirmation:d=>{let h=d;if(typeof d=="string")h=g.Url(d);else if(typeof d=="boolean")h=d;else throw new a('"option.signup_confirmation" should be type: <string | boolean>.',{code:"INVALID_PARAMETER"});if(h&&!i.email)throw new a('"email" is required for signup confirmation.',{code:"INVALID_PARAMETER"});return h},login:d=>{if(typeof d=="boolean"){if(e.signup_confirmation&&d)throw new a('"login" is not allowed when "option.signup_confirmation" is true.',{code:"INVALID_PARAMETER"});return d}throw new a('"option.login" should be type: boolean.',{code:"INVALID_PARAMETER"})}});let r=e?.login||false;if(i.signup_confirmation=e?.signup_confirmation||false,i.email_subscription=e?.email_subscription||false,i.email_public&&!i.signup_confirmation)throw new a('"option.signup_confirmation" should be true if "email_public" is set to true.',{code:"INVALID_PARAMETER"});i.service=this.service,i.owner=this.owner;let s=F.bind(this)().createCognitoUser(i.username||i.email);for(let d of ["email_public","address_public","gender_public","birthdate_public","phone_number_public"])i[d]=i[d]?"1":"0";i.access_group&&(i.access_group=i.access_group.toString());let o=(await E.bind(this)("signupkey",{username:s.cognitoUsername,signup_confirmation:typeof i.signup_confirmation=="boolean"?JSON.stringify(i.signup_confirmation):i.signup_confirmation,email_subscription:i.email_subscription})).split(":"),c=o.slice(1).join(":"),l=[new CognitoUserAttribute({Name:"custom:signup",Value:o[0]}),new CognitoUserAttribute({Name:"locale",Value:c.split("#")[1]}),new CognitoUserAttribute({Name:"custom:signup_ticket",Value:c})];for(let d in t){let h=["email_public","address_public","gender_public","birthdate_public","phone_number_public","misc","service","owner"];i[d]!==""&&(d==="username"||d==="password"||d==="access_group"||(h.includes(d)?l.push(new CognitoUserAttribute({Name:"custom:"+d,Value:i[d]})):l.push(new CognitoUserAttribute({Name:d,Value:i[d]}))));}return await F.bind(this)().signup(s.cognitoUsername,i.password,l),i.signup_confirmation?(C=s.cognitoUser,this.__request_signup_confirmation=s.cognitoUsername,"SUCCESS: The account has been created. User's signup confirmation is required."):r?Ce.bind(this)({email:i.username||i.email,password:i.password}):"SUCCESS: The account has been created."}async function dt(){await this.__connection;let n=await E.bind(this)("remove-account",{disable:this.__user.user_id},{auth:true});return await ce.bind(this)(),n}async function gt(n){await this.__connection;let e=g.Params(n,{email:r=>g.Email(r),code:["number","string"],new_password:r=>g.Password(r)},["email","code","new_password"]),t=e.code,i=e.new_password;return typeof t=="number"&&(t=t.toString()),new Promise(async(r,s)=>{F.bind(this)().createCognitoUser(e.email).cognitoUser.confirmPassword(t,i,{onSuccess:c=>{r("SUCCESS: New password has been set.");},onFailure:c=>{s(new a(c?.message||"Failed to reset password.",{code:c?.code||"ERROR",cause:c}));}});})}async function ft(n,e){await this.__connection;let t;if(!C)throw new a("The user has to be logged in.",{code:"INVALID_REQUEST"});if(n==="email"||n==="phone_number"){if(!this.__user.hasOwnProperty(n))throw new a(`No ${n==="email"?"e-mail":"phone number"} to verify`,{code:"INVALID_REQUEST"});if(this.__user?.[`${n}_verified`])return `SUCCESS: "${n}" is verified.`;t=(e?g.Params(e,{code:"string"}):{}).code||"";}else return;return new Promise((i,r)=>{let s={onSuccess:o=>{t?F.bind(this)().getSession({refreshToken:true}).then(()=>{this.__user&&(this.__user[n+"_verified"]=true),i(`SUCCESS: "${n}" is verified.`);}).catch(c=>{r(c);}):i("SUCCESS: Verification code has been sent.");},onFailure:o=>{r(new a(o.message||"Failed to request verification code.",{code:o?.code}));}};t?C?.verifyAttribute(n,t,s):(s.inputVerificationCode=null,C?.getAttributeVerificationCode(n,s));})}function ht(n){return ft.bind(this)("phone_number",n)}function pt(n){return ft.bind(this)("email",n)}async function mt(n){await this.__connection;let e=g.Params(n,{email:t=>g.Email(t)},["email"]);return new Promise(async(t,i)=>{F.bind(this)().createCognitoUser(e.email).cognitoUser.forgotPassword({onSuccess:s=>{t("SUCCESS: Verification code has been sent.");},onFailure:s=>{let{parsed:o,code:c}=_e(s),l={UserNotFoundException:"NOT_EXISTS",InvalidParameterException:"INVALID_PARAMETER",NotAuthorizedException:"INVALID_REQUEST",LimitExceededException:"REQUEST_EXCEED",TooManyRequestsException:"REQUEST_EXCEED",CodeDeliveryFailureException:"CODE_DELIVERY_FAILURE"}[c]||o.code||c||"ERROR";i(new a(o.message,{code:l,cause:s}));}});})}async function bt(n){if(await this.__connection,!this.session)throw new a("User login is required.",{code:"INVALID_REQUEST"});let e=g.Params(n,{current_password:"string",new_password:"string"});if(!e?.current_password)throw new a('"current_password" is required to change password.',{code:"INVALID_PARAMETER"});if(!e?.new_password)throw new a('"new_password" is required to change password.',{code:"INVALID_PARAMETER"});return g.Password(e.current_password),g.Password(e.new_password),new Promise((t,i)=>{C.changePassword(e.current_password,e.new_password,(r,s)=>{if(r){if(r?.code==="InvalidParameterException")i(new a("Invalid password parameter.",{code:"INVALID_PARAMETER"}));else if(r?.code==="NotAuthorizedException")i(new a("Incorrect password.",{code:"INVALID_REQUEST"}));else if(r?.code==="TooManyRequestsException"||r?.code==="LimitExceededException")i(new a("Too many attempts. Please try again later.",{code:"REQUEST_EXCEED"}));else {let{parsed:o}=_e(r);i(o);}return}t("SUCCESS: Password has been changed.");});})}async function _t(n){if(await this.__connection,!this.session)throw new a("User login is required.",{code:"INVALID_REQUEST"});let e=g.Params(n||{},{user_id:r=>g.UserId(r),email:r=>g.Email(r),address:r=>{if(!r)return "";if(typeof r=="string")return r;if(typeof r=="object")return JSON.stringify(r)},name:"string",gender:"string",birthdate:r=>r?g.Birthdate(r):"",phone_number:r=>r?g.PhoneNumber(r):"",email_public:"boolean",phone_number_public:"boolean",address_public:"boolean",gender_public:"boolean",birthdate_public:"boolean",misc:"string",picture:r=>r?g.Url(r):"",profile:r=>r?g.Url(r):"",family_name:"string",given_name:"string",middle_name:"string",nickname:"string",website:r=>r?g.Url(r):""});if(e&&typeof e=="object"&&!Object.keys(e).length)return this.user;e.email&&(e.preferred_username=this.service+"-"+V.hash(e.email));let t=[["email_public","email_verified","User's e-mail should be verified to set"],["phone_number_public","phone_number_verified","User's phone number should be verified to set"]];if(this.__user){for(let r of t)if(e[r[0]]&&!this.__user[r[1]])throw new a(`${r[2]} "${r[0]}" to true.`,{code:"INVALID_REQUEST"})}let i=[];for(let r in e){if(e[r]===this.user[r]){i.push(r);continue}if(["email_public","phone_number_public","address_public","gender_public","birthdate_public","misc"].includes(r)){let o=e[r];typeof o=="boolean"&&(o=o?"1":"0"),e["custom:"+r]=o,i.push(r);}}for(let r of i)delete e[r];if(e.user_id)if(e.user_id===this.user.user_id)delete e.user_id;else return E.bind(this)("admin-edit-profile",{attributes:e},{auth:true});if(e&&typeof e=="object"&&Object.keys(e).length){let r=[];for(let s in e)r.push(new CognitoUserAttribute({Name:s,Value:e[s]}));return await new Promise((s,o)=>{C?.updateAttributes(r,(c,l)=>{c&&o([c?.code||c?.name,c?.message||"Failed to update user settings."]),s(l);});}),await F.bind(this)().getSession({refreshToken:true}),this.user}return this.user}async function yt(n,e){n=N(n).data,n||(n={searchFor:"timestamp",condition:">",value:0},e||(e={}),e.ascending=false),await this.__connection;let t={user_id:r=>Array.isArray(r)?r.map(s=>g.UserId(s)):g.UserId(r),email:"string",phone_number:"string",locale:r=>{if(typeof r!="string"||typeof r=="string"&&r.length>5)throw new a('Value of "locale" should be a country code.',{code:"INVALID_PARAMETER"});return r},name:"string",address:"string",gender:"string",birthdate:r=>g.Birthdate(r),subscribers:"number",timestamp:"number",access_group:"number",approved:"string"},i=["searchFor","value"];if(n=g.Params(n,{searchFor:["user_id","name","email","phone_number","address","gender","birthdate","locale","subscribers","timestamp","access_group","approved"],condition:[">",">=","=","<","<=","gt","gte","eq","lt","lte",()=>"="],value:r=>{let s=t[n.searchFor];if(typeof s=="function")return s(r);if(typeof r!==s)throw new a(`Value does not match the type of "${n.searchFor}" index.`,{code:"INVALID_PARAMETER"});return r},range:r=>{let s=t[n.searchFor];if(typeof s=="function")return s(r);if(typeof r!==s)throw new a(`Range does not match the type of "${n.searchFor}" index.`,{code:"INVALID_PARAMETER"});return r}},i),n?.condition&&n?.condition!=="="&&n.hasOwnProperty("range"))throw new a("Conditions does not apply on range search.",{code:"INVALID_PARAMETER"});if(n.searchFor==="user_id"&&(n.condition!=="="||n.range))throw new a(`Conditions are not allowed on "${n.searchFor}"`,{code:"INVALID_PARAMETER"});if(typeof n?.value=="string"&&!n?.value)throw new a("Value should not be an empty string.",{code:"INVALID_PARAMETER"});if(typeof n?.searchFor=="string"&&!n?.searchFor)throw new a('"searchFor" should not be an empty string.',{code:"INVALID_PARAMETER"});return E.bind(this)("get-users",n,{auth:true,fetchOptions:e})}async function wt(n){await this.__connection;let e=await E.bind(this)("last-verified-email",n,{auth:true});return e.includes("SUCCESS")?(await F.bind(this)().getSession({refreshToken:true}),this.user):e}async function Et(n){return await this.__connection,n=g.Params(n,{username:g.Email,redirect:g.Url},["username"]),await E.bind(this)("request-username-change",n,{auth:true})}var re=null,At=typeof SubmitEvent<"u",mr=typeof HTMLFormElement<"u",ue=$(),Le=0;function It(n){if(!n)return null;let e=Number(n);if(Number.isFinite(e))return Math.max(0,e*1e3);let t=Date.parse(n);return Number.isNaN(t)?null:Math.max(0,t-Date.now())}function Oe(n,e){return e>0?n/e*100:0}var Rt=n=>{let{auth:e,type:t,endpoints:i}=n,r=i[0],s=i[1];if(Le++,t==="admin"){let o=Object.entries(r).filter(([c,l])=>c.includes(e?"_private":"_public")&&c!=="get_users_private"&&c!=="service_public"&&typeof l=="string").map(([,c])=>c);if(!o.length)throw new a("No available admin gateways.",{code:"INVALID_REQUEST"});return o[Le%o.length]}if(t==="record"){let o=Object.entries(s).filter(([c,l])=>c.includes(e?"record_private":"record_public")&&typeof l=="string").map(([,c])=>c);if(!o.length)throw new a("No available record gateways.",{code:"INVALID_REQUEST"});return o[Le%o.length]}throw new a("Invalid gateway type.",{code:"INVALID_REQUEST"})};async function br(n,e){let t=await Promise.all([this.admin_endpoint,this.record_endpoint]),i=t[0],r=t[1],s=n.split("?"),o=s.length>1?"?"+s[1]:"";switch(n=s[0],n){case "get-users":return i.get_users_private+n+o;case "service":return i.service_public+n+o;case "get-newsletters":case "get-public-newsletters":case "subscribe-newsletter":case "subscribe-public-newsletter":case "signupkey":case "admin-newsletter-request":case "admin-signup":case "confirm-signup":case "openid-logger":case "block-account":case "admin-edit-profile":case "remove-account":case "post-secure":case "recover-account":case "mock":case "grant-access":case "last-verified-email":case "ticket":case "register-ticket":case "get-newsletter-subscription":case "request-username-change":case "send-inquiry":case "register-newsletter-group":case "newsletter-group-endpoint":case "invitation-list":case "csr":return Rt.bind(this)({auth:e,type:"admin",endpoints:t})+n+o;case "post-record":return (e?r.post_private:r.post_public)+n+o;case "get-records":return (e?r.get_private:r.get_public)+n+o;case "del-files":case "del-records":return r.del_private+n+o;case "store-subscription":case "get-vapid-public-key":case "push-notification":case "delete-subscription":case "subscription":case "get-subscription":case "get-table":case "get-tag":case "get-uniqueid":case "get-index":case "get-signed-url":case "grant-private-access":case "request-private-access-key":case "get-ws-group":case "check-schema":case "get-feed":case "castspell":case "dopamine":case "getspell":return Rt.bind(this)({auth:e,type:"record",endpoints:t})+n+o;default:return g.Url(n)+o}}var le={};function Tt(){re&&(re.terminate(),re=null);}async function E(n,e=null,t,i){this.log("request",{url:n,data:e,options:t,_etc:i||{}}),t=t||{};let{auth:r=false,method:s="post",bypassAwaitConnection:o=false}=t;s=s.toUpperCase();let c=null,l=e?.service||this.service,d=e?.owner||this.owner,h=null,u=await br.bind(this)(n,!!r);if(!o&&(c=await this.__connection,!c))throw new a("Invalid connection. The service could have been disabled, or has a restricted CORS.",{code:"INVALID_REQUEST"});let p=t?.tokenHeaders?.idToken===true;(r||p)&&(h=await ne.bind(this)());let A={},{fetchMore:f=false,progress:R}=t?.fetchOptions||{};if(t?.fetchOptions&&Object.keys(t.fetchOptions).length){for(let S of ["limit","startKey","ascending"])t.fetchOptions.hasOwnProperty(S)&&(A[S]=t.fetchOptions[S]);A=g.Params(A,{limit:S=>{if(typeof S!="number")throw new a("Fetch limit should be a number.",{code:"INVALID_REQUEST"});if(S>1e3)throw new a("Fetch limit should be below 1000.",{code:"INVALID_REQUEST"});return S},startKey:S=>S,ascending:"boolean"});}let P=i?.ignoreService?{}:{service:l,owner:d};Object.assign(P,A),e=N(e).data,e?e&&typeof e=="object"&&(e=Object.assign(P,e)):e=P;let b=`${s}:${r?"auth":"public"}:${n}`,x=(()=>{if(e&&typeof e=="object"&&Object.keys(e).length&&!(ue&&e instanceof FormData)){let S=function(D){return typeof D=="object"&&D!==null?Object.keys(D).sort().reduce((U,L)=>(typeof D[L]=="object"&&D[L]!==null?U[L]=S(D[L]):U[L]=D[L],U),{}):D};return V.hash(b+"/"+JSON.stringify(S(e)))}return V.hash(b+"/"+l)})(),{requestKey:k,requestKeyWithStartKey:T}=_r.bind(this)({params:e,url:n,fetchMore:f,hashedParams:x});if(!k||k&&typeof k=="object")return k;if(this.log("requestKey",T),typeof T=="string"&&le[T]instanceof Promise)return this.log("request:returning pending",T),le[T];let v={Accept:"*/*"};if(Object.prototype.hasOwnProperty.call(t,"contentType")&&t.contentType!==void 0){let S=t.contentType===null?"application/x-www-form-urlencoded":t.contentType;S&&(v["Content-Type"]=S);}else v["Content-Type"]="application/json";if(h&&(v.Authorization=h),t?.tokenHeaders){let S=(L,Cn)=>typeof L=="string"?L:L===true?Cn:null,D=S(t.tokenHeaders.accessToken,this.session?.accessToken?.jwtToken||null),U=S(t.tokenHeaders.idToken,this.bearerToken||this.session?.idToken?.jwtToken||h||null);D&&(v["x-access-token"]=D),U&&(v["x-id-token"]=U);}let xe={public_identifier:this.__public_identifier,service:l,owner:d};v["Content-Meta"]=JSON.stringify(xe);let q={headers:v};if(t?.responseType&&(q.responseType=t.responseType),s==="GET"){if(e){let S=[];if(ue&&e instanceof FormData?S=Array.from(e.entries()).map(([D,U])=>{let L=typeof U=="string"?U:U.name;return encodeURIComponent(D)+"="+encodeURIComponent(L)}):S=Object.keys(e).map(D=>{let U=e[D];return typeof U!="string"&&(U=JSON.stringify(U)),encodeURIComponent(D)+"="+encodeURIComponent(U)}),S.length){let D=u.includes("?")?u.endsWith("?")||u.endsWith("&")?"":"&":"?";u+=D+S.join("&");}}q.body=null;}else if(ue&&e instanceof FormData)q.body=e;else if(v["Content-Type"]==="application/x-www-form-urlencoded"&&e&&typeof e=="object"){let S=new URLSearchParams;for(let D of Object.keys(e)){let U=e[D];S.append(D,typeof U=="string"?U:JSON.stringify(U));}q.body=S.toString();}else typeof e=="string"?q.body=e:q.body=e?JSON.stringify(e):null;if(q.method=s,re===null){let S={batchSize:this.requestBatchSize,breakWhenError:false,onProgress:D=>{this.onBatchProcess.forEach(U=>U(D));}};re=new pr(S);}return this.log("request-opt",q),new Promise((S,D)=>{re.add([async()=>{let U=Pt.bind(this)(u,q,R);le[T]=U;try{let L=yr.bind(this)({hashedParam:k,requestKeyWithStartKey:T,url:n,fetched:await U});return delete le[T],this.log("request:end",L),S(L),L}catch(L){throw delete le[T],this.log("request:err",L),D(L),L}}]);})}function _r(n){let{params:e={},url:t,fetchMore:i=false,hashedParams:r}=n||{};if(e.startKey){if(!(typeof e.startKey=="object"&&Object.keys(e.startKey).length)&&e.startKey!=="start"&&e.startKey!=="end")throw new a(`"${e.startKey}" is invalid startKey key.`,{code:"INVALID_PARAMETER"});e.startKey==="start"&&(i=false,delete e.startKey);}if(!i){if(this.__cached_requests?.[t]?.[r]&&delete this.__cached_requests[t][r],this.__startKeyHistory?.[t]?.[r]){if(Array.isArray(this.__startKeyHistory[t][r])&&this.__startKeyHistory[t][r].length)for(let l of this.__startKeyHistory[t][r]){let d=r+V.hash(l);this.__cached_requests?.[t]&&this.__cached_requests?.[t]?.[d]&&delete this.__cached_requests[t][d];}delete this.__startKeyHistory[t][r];}return {requestKeyWithStartKey:r,requestKey:r}}if(!Array.isArray(this.__startKeyHistory?.[t]?.[r]))return {requestKeyWithStartKey:r,requestKey:r};let s=this.__startKeyHistory[t][r],o=s[s.length-1],c=r;if(o){if(o==="end")return {requestKey:{list:[],startKey:"end",endOfList:true,startKeyHistory:s},requestKeyWithStartKey:c};c+=V.hash(o),e.startKey=JSON.parse(o);}return this.__cached_requests?.[t]?.[c]?{requestKey:this.__cached_requests[t][c],requestKeyWithStartKey:c}:{requestKeyWithStartKey:c,requestKey:r}}function Pt(n,e,t){return new Promise((i,r)=>{let s=new XMLHttpRequest;s.open(e.method||"GET",n);for(var o in e.headers||{})s.setRequestHeader(o,e.headers[o]);e.responseType&&(s.responseType=e.responseType),s.onload=()=>{if(s.status<400)if(e.responseType=="json"||e.responseType=="blob")i(s.response);else {let c=s.responseText;try{c=JSON.parse(c);}catch{}i(c);}else if(s.status===429){let c=s.getResponseHeader("Retry-After"),l=It(c);l!==null?setTimeout(()=>{Pt(n,e,t).then(i,r);},l):r("Too many requests");}else {let c=s.status,l=["INVALID_CORS","INVALID_REQUEST","SERVICE_DISABLED","INVALID_PARAMETER","ERROR","EXISTS","NOT_EXISTS"],d=e.responseType=="blob"?s.response:s.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();r(new a(p||d,{code:l.includes(u)?u:"ERROR"}));}else if(typeof d=="object"&&d?.message){let h=d?.code||(c?c.toString():null)||"ERROR",u=d.message,p=d?.cause;typeof u=="string"&&(u=u.trim()),r(new a(u,{cause:p,code:h}));}else r(d);}},s.onerror=()=>r("Network error"),s.onabort=()=>r("Aborted"),s.ontimeout=()=>r("Timeout"),typeof t=="function"&&(s.onprogress=c=>{t({status:"download",progress:Oe(c.loaded,c.total),loaded:c.loaded,total:c.total,abort:()=>s.abort()});},s.upload&&(s.upload.onprogress=c=>{t({status:"upload",progress:Oe(c.loaded,c.total),loaded:c.loaded,total:c.total,abort:()=>s.abort()});})),s.send(e.body);})}function yr(n){let{hashedParam:e,requestKeyWithStartKey:t,url:i,fetched:r}=n;if(!r?.startKey)return r;this.__startKeyHistory.hasOwnProperty(i)||(this.__startKeyHistory[i]={}),this.__startKeyHistory[i].hasOwnProperty(e)||(this.__startKeyHistory[i][e]=[]);let s=r.startKey==="end"?"end":JSON.stringify(r.startKey);return this.__startKeyHistory[i][e].includes(s)||this.__startKeyHistory[i][e].push(s),this.__cached_requests?.[i]||(this.__cached_requests[i]={}),this.__cached_requests[i][t]=r,Object.assign({startKeyHistory:this.__startKeyHistory[i][e]},r)}async function we(n,e){await this.__connection;let{record_id:t,service:i=this.service,progress:r}=e;if(!t)throw new a('"record_id" is required.',{code:"INVALID_PARAMETER"});if(At&&n instanceof SubmitEvent&&(n=n.target),mr&&n instanceof HTMLFormElement&&(n=new FormData(n)),!ue||!(n instanceof FormData))throw new a('"fileList" should be a FormData or HTMLFormElement.',{code:"INVALID_PARAMETER"});let o={reserved_key:oe(),service:i,request:"post"};e?.record_id&&(o.id=e.record_id);let c,l=(A,f,R)=>new Promise((P,b)=>{c=new XMLHttpRequest,c.open("POST",A),c.onload=()=>{let x=c.responseText;try{x=JSON.parse(x);}catch{}if(c.status>=200&&c.status<300)P(x);else if(c.status===429){let k=c.getResponseHeader("Retry-After"),T=It(k);T!==null?setTimeout(()=>{l(A,f,R).then(P,b);},T):b("Too many requests");}else b(x);},c.onerror=()=>b("Network error"),c.onabort=()=>b("Aborted"),c.ontimeout=()=>b("Timeout"),c.upload&&typeof R=="function"&&(c.upload.onprogress=R),c.send(f);});function d(A){let f="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";if(A===0)return f[0];let R="";for(;A>0;)R=f[A%62]+R,A=Math.floor(A/62);return R}let h=[],u=[],p=[];for(let[A,f]of n.entries()){if(!(f instanceof File))continue;let R=Object.assign({key:A+"/"+f.name,sizeKey:d(f.size),contentType:f.type||null},o),{fields:P=null,url:b,cdn:x}=await E.bind(this)("get-signed-url",R,{auth:!!this.__user});p.push(x);let k=new FormData;for(let T in P)k.append(T,P[T]);k.append("file",f);try{await l(b,k,typeof r=="function"?T=>r({status:"upload",progress:Oe(T.loaded,T.total),currentFile:f,completed:h,failed:u,loaded:T.loaded,total:T.total,abort:()=>c.abort()}):null),h.push(f);}catch{u.push(f);}}return {completed:h,failed:u,bin_endpoints:p}}var ye={};function w(n){let{preventMultipleCalls:e=false}=n||{};return function(t,i,r){let s=r.value;r.value=function(...o){let c=o[0],l=true,d=null,h="",u={},p=false;if(At&&c instanceof SubmitEvent){c.preventDefault();let b=window.location.href;d=c.target;let x=new URL(d.action);h=x.href;let k=h?h.match(/(?<=\{).*?(?=\})/g):"";if(k)for(let T of k){if(!T)continue;let v=d.querySelector(`[name="${T}"]`);if(v)if(v.type==="file")for(let Q=0;Q<=v.files.length-1;Q++)v.files[Q]&&(u[T]||(u[T]=[]),u[T].push(new Promise((xe,q)=>{let S=new FileReader;S.onload=function(){xe(S.result);},S.readAsDataURL(v.files[Q]),S.onerror=q;})));else h=h.replace(`{${T}}`,v.value);}d.getAttribute("action")===null?l=false:p=x.href===b;}let A=async b=>{if(h)for(let x in u)u[x].length&&(h=h.replace(`{${x}}`,(await Promise.all(u[x])).join(",")));return d&&l&&(window.sessionStorage.setItem(`${this.service}:${V.hash(h)}`,JSON.stringify(b)),p?window.location.replace(h):window.location.href=h),b},f,R=b=>{throw b instanceof a?b.name=i+"()":b=b instanceof Error?b:new a(b,{name:i+"()"}),b},P=async()=>{try{if(f=s.bind(this)(...o),f instanceof Promise){let b=await f;return A(b)}return A(f)}catch(b){throw R(b)}};if(e){let b=`${i}:${this?.__public_identifier||""}:${this?.service||""}:${this?.owner||""}`;return ye?.[b]||(ye[b]=P().finally(()=>{delete ye[b];})),ye[b]}return P()};}}async function St(){await this.__connection;let n=`${this.service}:${V.hash(window.location.href.split("?")[0])}`,e=window.sessionStorage.getItem(n);if(window.sessionStorage.removeItem(n),e!==null){try{e=JSON.parse(e);}catch{}return e}return null}var wr=128,Er=64,Rr=128,Ar=256,Ir="\u{10FFFF}",Tr=/[\u0000-\u001F\u007F]|\u{10FFFF}/u,Pr=/[\/!*#]/;function X(n,e,t={}){let{allowEmpty:i=false,maxLength:r,blockKeyDelimiters:s=false,disallowLeadingDollar:o=false,onlyAlphanumeric:c=false}=t;if(typeof n!="string")throw new a(`"${e}" should be type: <string>.`,{code:"INVALID_PARAMETER"});if(c&&/[^a-zA-Z0-9]/.test(n))throw new a(`"${e}" should only contain alphanumeric characters.`,{code:"INVALID_PARAMETER"});if(!i&&n.length===0)throw new a(`"${e}" is required.`,{code:"INVALID_PARAMETER"});if(r&&n.length>r)throw new a(`"${e}" should be <= ${r} characters.`,{code:"INVALID_PARAMETER"});if(Tr.test(n)||n.includes(Ir))throw new a(`"${e}" cannot include control characters or unsupported sentinel characters.`,{code:"INVALID_PARAMETER"});if(s&&Pr.test(n))throw new a(`"${e}" cannot include reserved delimiters: / ! * #`,{code:"INVALID_PARAMETER"});if(o&&n.startsWith("$"))throw new a(`"${e}" cannot start with "$".`,{code:"INVALID_PARAMETER"});return n}function Fe(n,e="table.name"){return X(n,e,{allowEmpty:false,maxLength:wr,blockKeyDelimiters:true})}function Me(n,e="tag"){return X(n,e,{allowEmpty:false,maxLength:Er,blockKeyDelimiters:true})}function de(n,e="index.name"){return X(n,e,{allowEmpty:false,maxLength:Rr,blockKeyDelimiters:true,disallowLeadingDollar:true})}function kt(n,e="index.value"){return X(n,e,{allowEmpty:true,maxLength:Ar})}function xt(n){if(!n.record_id&&!n.unique_id)return null;let e={};return n?.service&&(e.service=n.service),n?.owner&&(e.owner=n.owner),n?.record_id?e.record_id=X(n.record_id,"record_id",{allowEmpty:false,onlyAlphanumeric:true}):n?.unique_id&&(e.unique_id=n.unique_id),e}function Ve(n){if(n===void 0)return 0;if(typeof n=="number"){if(n>99||n<0)throw new a('"table.access_group" value should be within a range of 0 ~ 99.',{code:"INVALID_REQUEST"})}else if(typeof n=="string"){if(n={private:"private",public:0,authorized:1,admin:99}[n],n===void 0)throw new a('"table.access_group" is invalid.',{code:"INVALID_PARAMETER"})}else throw new a('"table.access_group" should be type: <number | string>.',{code:"INVALID_PARAMETER"});if(!this.__user&&n)throw new a("Unsigned users have no access to records with access group.",{code:"INVALID_REQUEST"});return n}var Ee=4503599627370496;function Re(n){if(typeof n=="number"){if(n>Ee||n<-Ee)throw new a(`Number value should be within range -${Ee} ~ +${Ee}`,{code:"INVALID_PARAMETER"});return n}if(typeof n=="boolean")return n;if(typeof n=="string")return kt(n,"index.value");throw new a('"index.value" should be type: <number | boolean | string>.',{code:"INVALID_PARAMETER"})}function vt(n,e){if(!e.index||!("value"in e.index))throw new a('"index.value" is required.',{code:"INVALID_PARAMETER"});if(e.index.name==="$record_id")throw new a(`Cannot do "index.range" on ${e.index.name}`,{code:"INVALID_PARAMETER"});if(typeof e.index.value!=typeof n)throw new a('"index.range" type should match the type of "index.value".',{code:"INVALID_PARAMETER"});return typeof n=="string"?kt(n,"index.range"):n}var Ae={};async function ie(n,e){let t={user_id:"",record_id:"",updated:0,uploaded:0,readonly:false,table:{name:"",access_group:0,subscription:{is_subscription_record:false,upload_to_feed:false,notify_subscribers:false,feed_referencing_records:false,notify_referencing_records:false}},referenced_count:0,source:{referencing_limit:null,prevent_multiple_referencing:false,can_remove_referencing_records:false,only_granted_can_reference:false},ip:"",bin:{}},i=false;function r(o){let c=o=="**"?"private":parseInt(o);return c=c==0?"public":c==1?"authorized":c==99?"admin":c,c}let s={ip:o=>{let c=o.split("#"),l=c[0];c.length>1&&(t.unique_id=c[1]),l.slice(-1)==="R"?(t.readonly=true,l=l.slice(0,-1)):t.readonly=false,/^\d{1,3}-\d{1,3}-\d{1,3}-\d{1,3}$/.test(l)&&(l=l.split("-").join("."),i=true),t.ip=l;},rec:o=>{if(!o)return;t.record_id=o;let c=o.substring(0,o.length-9),l=j(c);t.uploaded=l;},usr:o=>{t.user_id=o;},tbl:o=>{if(o&&!t.table.name){let c=o.split("/");t.table.name=c[0],t.table.access_group=r(c[2]),c?.[3]&&(t.table.subscription.is_subscription_record=true);}},usr_tbl:o=>{let c=o.split("/");t.user_id||(t.user_id=c[0]),t.table.name||(t.table.name=c[1],t.table.access_group=r(c[3]),c?.[4]&&(t.table.subscription.is_subscription_record=true));},idx:o=>{if(!o)return;let c=o.split("!"),l=c.splice(0,1)[0],d=Sr("!"+c.join("!"));t.index={name:l,value:d};},ref:o=>{o&&(t.reference=o.split("/")[0]);},tags:o=>{t.tags=o;},upd:o=>{t.updated=o;},acpt_mrf:o=>{t.source.prevent_multiple_referencing=!o;},ref_limt:o=>{t.source.referencing_limit=o;},rfd:o=>{t.referenced_count=o;},bin:async o=>{let c={},l=t?.reference||null;if(Array.isArray(o)){let d=await Promise.all(o.map(async h=>{try{let u=h.split("/").slice(3).join("/"),p=u.split("/");if(p.length<12)return null;let A=decodeURIComponent(p[p.length-1]),f=decodeURIComponent(p[10]),R=p[9],P=p[8],b=r(p[6]),x=h;if(b!=="public")try{x=await Ie.bind(this)(h,{dataType:"endpoint",_ref:l});}catch(T){console.error("Error getting signed url for private file:",T),x=h;}let k={access_group:b,filename:A,url:x,path:u,size:j(R),uploaded:j(P),getFile:(T,v)=>{let Q={dataType:T||"download",progress:v,_ref:l,_update:k};return Ie.bind(this)(x,Q)}};return {pathKey:f,obj:k}}catch{return null}}));for(let h of d)if(h){if(c[h.pathKey]){c[h.pathKey].push(h.obj);continue}c[h.pathKey]=[h.obj];}}t.bin=c;},prv_acs:o=>{for(let c in o)["notify_subscribers","upload_to_feed","feed_referencing_records","notify_referencing_records"].includes(c)?t.table.subscription[c]=o[c]:t.source[c]=o[c];},data:o=>{let c=o;o==="!D%{}"?c={}:o==="!L%[]"&&(c=[]),t.data=c;}};if(n.record_id)return n;for(let o in s)if(n.hasOwnProperty(o)){let c=s[o](n[o]);c instanceof Promise&&await c;}return i&&(t.user_id="anonymous:"+t.user_id),t}function Sr(n){let e=n.substring(3);switch(n.substring(0,3)){case "!S%":return e;case "!N%":let i=e.split("."),r=Number(i[0])-4503599627370496;return i.length===1?r:parseFloat(r.toString()+"."+i[1]);case "!B%":return e==="1";case "!L%":case "!D%":try{return JSON.parse(e)}catch{throw new a("Value parse error.",{code:"PARSE_ERROR"})}default:return n}}async function Dt(n){let{endpoints:e}=n;if(typeof e=="string"&&(e=[e]),!Array.isArray(e))throw new a('"endpoints" should be type: array | string.',{code:"INVALID_PARAMETER"});let t=await E.bind(this)("del-files",{endpoints:e,storage:"records"},{auth:true,method:"post"}),i=[];for(let r in t)i.push(ie.bind(this)(t[r]));return Promise.all(i)}async function Ie(n,e){if(typeof n!="string")throw new a('"url" should be type: string.',{code:"INVALID_PARAMETER"});let t=n.split("?"),i=t.shift()||"",r=t.length?"?"+t.join("?"):"",s=g.Url(i);n=s+r;let o=false,c=s.split("/"),d=c[2].split("."),h=null;d.length===3&&d[1]==="skapi"&&(h=d[0],o=true);let u=c.slice(3),p=false;if(!o&&(u[0]==="auth"||u[0]==="publ"))try{g.UserId(u[2]),g.UserId(u[3]),p=u[0]=="auth",o=!0;}catch{throw new a("Invalid file url.",{code:"INVALID_PARAMETER"})}let A=h?null:u[1];if(e=g.Params(e,{expires:["number",()=>0],dataType:["base64","blob","endpoint","text","info",()=>"download"],progress:"function",_ref:[null,"string"],_update:b=>b}),e?.dataType==="info")return {url:n,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:j(u[9]),uploaded:j(u[8])};let f=n.split("/").slice(-1)[0],R=e.expires;if(R){if(!o)throw new a("Expires option can only be used on skapi cdn endpoints.",{code:"INVALID_PARAMETER"});if(R<0)throw new a('"config.expires" should be > 0. (seconds)',{code:"INVALID_PARAMETER"});let b={request:h?"get-host":"get",id:h||u[5],key:n,expires:R};A&&(b.service=A),n=(await E.bind(this)("get-signed-url",b,{auth:true})).url;}else if(p){let b=Math.floor(Date.now()/1e3);if(!this.bearerToken&&(!this.session?.idToken?.payload?.exp||this.session.idToken.payload.exp<b)){this.log("getFile:requesting new token",null);try{await F.bind(this)().getSession({refreshToken:!0}),this.log("getFile:received new tokens",{exp:this.session?.idToken?.payload?.exp,currTime:b,expiresIn:this.session?.idToken?.payload?.exp-b,token:this.session?.accessToken?.jwtToken,refreshToken:this.session?.refreshToken?.token});}catch(v){throw this.log("getFile:new token error",v),new a("User login is required.",{code:"INVALID_REQUEST"})}}let x=this.bearerToken||this.session?.idToken?.jwtToken;if(!x||!this.user?.user_id)throw new a("User login is required.",{code:"INVALID_REQUEST"});n+=`${n.includes("?")?"&":"?"}t=${encodeURIComponent(x)}`;let k=u[6]==="**"?"**":parseInt(u[6]),T=this.user?.access_group??-1;if(this.user.user_id!==u[3]&&(k==="**"||T<k)){let v=u[5];if(this.__private_access_key[v]&&typeof this.__private_access_key[v]=="string")n+=`&p=${encodeURIComponent(this.__private_access_key[v])}`;else if(this.owner!==this.host)try{let Q=await this.requestPrivateRecordAccessKey({record_id:v,reference_id:e?._ref});n+=`&p=${encodeURIComponent(Q)}`;}catch{}}}if(e?.dataType==="endpoint")return e._update&&(e._update.url=n),n;if(e?.dataType==="download"){let b=document.createElement("a");return b.href=n,document.body.appendChild(b),b.setAttribute("download",f),b.target="_blank",b.click(),document.body.removeChild(b),null}return new Promise(async(b,x)=>{try{let k=await E.bind(this)(n,null,{method:"get",contentType:null,responseType:e?.dataType==="text"?"text":"blob",fetchOptions:{progress:e?.progress}},{ignoreService:!0});if(e?.dataType==="base64"){let T=new FileReader;T.onloadend=()=>b(T.result),T.readAsDataURL(k);}else b(k);}catch(k){x(k);}})}async function Ut(n,e=false){n=N(n,{ignoreEmpty:true}).data||{};let t="",i=xt(n);if(i)n=i,t=n.record_id||n.unique_id,typeof t=="string"&&(typeof this.__private_access_key?.[t]=="string"&&(n.private_key=this.__private_access_key?.[t]||void 0),this.__my_unique_ids[t]&&(e?delete this.__my_unique_ids[t]:n.record_id=this.__my_unique_ids[t]));else {let r=await M.bind(this)(),s=n?.reference,o=false;typeof s=="object"&&Object.keys(s).length&&(s?.record_id||s?.unique_id?(t=s.record_id||s.unique_id,t&&typeof this.__private_access_key?.[t]=="string"&&(n.private_key=this.__private_access_key?.[t]||void 0),n.reference=t):s?.user_id&&(o=s.user_id===this.user?.user_id,n.reference=s.user_id)),typeof n?.table=="string"&&(n.table={name:n.table,access_group:0}),n.index&&n.index.hasOwnProperty("range")&&n.index.hasOwnProperty("condition")&&delete n.index.range;let c=l=>({table:{name:d=>Fe(d,"table.name"),access_group:Ve.bind(this),subscription:d=>g.UserId(d,'User ID in "subscription"')},reference:"string",index:{name:["$updated","$uploaded","$referenced_count","$user_id",d=>de(d,"index.name")],value:d=>{let h={$updated:"number",$uploaded:"number",$referenced_count:"number",$user_id:g.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 a(`"index.value" should be type: ${u}.`,{code:"INVALID_PARAMETER"});return d}return typeof d=="string"&&!d?"":Re(d)},condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq"],range:d=>vt(d,l)},tag:d=>{if(d==null)return d;if(typeof d=="string")return Me(d,"tag");throw new a('"tag" should be type: string.',{code:"INVALID_PARAMETER"})},private_key:"string"});n=g.Params(n||{},c(n),o||r?[]:["table"],{ignoreEmpty:true});}return {query:n,is_reference_fetch:t}}async function Nt(n,e){await this.__connection;let t=await Ut.bind(this)(n),i=t.is_reference_fetch,r=await E.bind(this)("get-records",t.query,{fetchOptions:e,auth:!!this.__user,method:this.__user?"post":"get"});i&&r?.reference_private_key&&typeof r.reference_private_key=="string"&&(this.__private_access_key[i]=r.reference_private_key);let s=[];for(let o in r.list)s.push(ie.bind(this)(r.list[o]));return r.list=await Promise.all(s),r}function Ct(n){let e="",t=[],i=g.Params(n||{},{record_id:s=>X(s,"record_id",{allowEmpty:false,onlyAlphanumeric:true}),unique_id:["string",null],readonly:"boolean",table:{name:s=>Fe(s,"table.name"),subscription:[null,{is_subscription_record:"boolean",upload_to_feed:"boolean",notify_subscribers:"boolean",feed_referencing_records:"boolean",notify_referencing_records:"boolean"}],access_group:Ve.bind(this)},source:{referencing_limit:s=>{if(s===null)return null;if(typeof s=="number"){if(0>s)throw new a('"reference_limit" should be >= 0',{code:"INVALID_PARAMETER"});if(s>4503599627370546)throw new a('"reference_limit" should be <= 4503599627370546',{code:"INVALID_PARAMETER"});return s}throw new a('"reference_limit" should be type: <number | null>',{code:"INVALID_PARAMETER"})},prevent_multiple_referencing:"boolean",can_remove_referencing_records:"boolean",only_granted_can_reference:"boolean",allow_granted_to_grant_others:"boolean",referencing_index_restrictions:s=>{if(s===void 0)return;if(!s||Array.isArray(s)&&!s.length)return null;let o={name:l=>de(l,'"name" in "index_restrictions"'),value:l=>Re(l),condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne",()=>null],range:l=>{if(l!==null&&typeof s.value!=typeof l)throw new a('Index restriction "range" type should match the type of "value".',{code:"INVALID_PARAMETER"});if(!s.hasOwnProperty("value"))throw new a('Index restriction "value" is required.',{code:"INVALID_PARAMETER"});return l}};Array.isArray(s)||(s=[s]);let c=s.map(l=>g.Params(l,o,["name"]));if(c.length)for(let l of c)l.condition&&l.hasOwnProperty("range")&&delete l.range;return c}},reference:s=>{if(s===null)return {record_id:null};if(s){if(typeof s=="string")return e=s,this.__my_unique_ids[s]?this.__my_unique_ids[s]:s;if(typeof s!="object")throw new a('"reference" should be type: <string | object>.',{code:"INVALID_PARAMETER"});return g.Params(s,{unique_id:"string",record_id:o=>o==null?o:(e=o,typeof this.__private_access_key?.[o]=="string"&&(n.reference_private_key=this.__private_access_key[o]||void 0),X(o,"reference.record_id",{allowEmpty:false,onlyAlphanumeric:true}))})}},index:[null,{name:s=>de(s,"index.name"),value:s=>Re(s)}],tags:s=>{if(s==null)return s;if(typeof s=="string"&&(s=s.split(",").map(o=>o.trim())),!Array.isArray(s))throw new a('"tag" should be type: <string | string[]>.',{code:"INVALID_PARAMETER"});return s.map(o=>Me(o,"tag"))},remove_bin:s=>{if(!s)return null;let o=[];if(Array.isArray(s))for(let c of s)if(typeof c=="string")o.push(decodeURIComponent(c.split("?")[0]));else if(c.url&&c.size&&c.filename){let d=c.url.split("/").slice(0,3).join("/")+"/"+c.path;o.push(d);}else throw new a('"remove_bin" should be type: <string[] | BinaryFile[] | null>',{code:"INVALID_PARAMETER"});else throw new a('"remove_bin" should be type: <string[] | BinaryFile[] | null>',{code:"INVALID_PARAMETER"});return o},progress:"function",data:s=>s},[],{precall:s=>{let o=s?.data||{};if(!o?.record_id&&!o.table)throw new a('"table.name" is required.',{code:"INVALID_PARAMETER"});typeof o.table=="string"&&(o.table={name:o.table,access_group:0}),s.files&&(t=s.files);}}),r=n.progress||null;if(delete i.progress,!this.__user){let s=!!(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 a("Public users cannot update existing records.",{code:"INVALID_REQUEST"});if(i.table.access_group!=="public"&&i.table.access_group!==0)throw new a("Public users can only post records to public tables.",{code:"INVALID_REQUEST"});if(s)throw new a("Public users cannot post subscription records.",{code:"INVALID_REQUEST"});if(i.remove_bin)throw new a("Public users cannot remove files from records.",{code:"INVALID_REQUEST"});if(i.unique_id)throw new a("Public users cannot set unique_id for records.",{code:"INVALID_REQUEST"})}return {config:i,progress:r,is_reference_post:e,files:t}}async function Lt(n){if(await this.__connection,!Array.isArray(n)||!n.length)throw new a('"params" should be a non-empty array.',{code:"INVALID_PARAMETER"});!this.__user;let t=[],i,r,s=null,c={_is_bulk_:n.map((p,A)=>{if(!p||typeof p!="object"||Array.isArray(p))throw new a(`"params[${A}]" should be type: <object>.`,{code:"INVALID_PARAMETER"});let f=Ct.bind(this)(p),R=f.config;if(f.is_reference_post&&t.push(f.is_reference_post),typeof R.progress=="function"&&s===null&&(s=R.progress),R.service!==void 0){if(i===void 0)i=R.service;else if(i!==R.service)throw new a('All bulk params should share the same "service" value.',{code:"INVALID_PARAMETER"})}if(R.owner!==void 0){if(r===void 0)r=R.owner;else if(r!==R.owner)throw new a('All bulk params should share the same "owner" value.',{code:"INVALID_PARAMETER"})}return delete R.progress,delete R.service,delete R.owner,R}),service:"",owner:""};i!==void 0&&(c.service=i),r!==void 0&&(c.owner=r);let l={auth:!!this.__user,method:"post"},d={};Object.keys(d).length&&Object.assign(l,{fetchOptions:d});let h=await E.bind(this)("post-record",c,l),u=await Promise.all(h.map(p=>ie.bind(this)(p,"called from postRecord")));for(let p=0;p<h.length;p++){let A=h[p],f=u[p];if(typeof A?.reference_private_key=="string")for(let R of t)this.__private_access_key[R]=A.reference_private_key;f?.unique_id&&(this.__my_unique_ids[f.unique_id]=f.record_id);}return u}async function Ot(n,e,t){if(await this.__connection,!e)throw new a('"config" argument is required.',{code:"INVALID_PARAMETER"});let i=Ct.bind(this)(e),r=i.config,s=i.progress,o=i.is_reference_post,c={auth:!!this.__user,method:"post"},l=[],d=N(n);t&&Array.isArray(t)&&t.length&&(l=l.concat(t)),d.files&&Array.isArray(d.files)&&d.files.length&&(l=l.concat(d.files));let h=null;h=Object.assign({data:d.data},r);let u={};typeof s=="function"&&(u.progress=s),Object.keys(u).length&&Object.assign(c,{fetchOptions:u});let p=await E.bind(this)("post-record",h,c);if($()&&l.length){let f=new FormData;for(let b of l)f.append(b.name,b.file,b.file.name);let R={record_id:p.rec,progress:s};r.hasOwnProperty("service")&&(R.service=r.service);let{bin_endpoints:P}=await we.bind(this)(f,R);p.bin?p.bin.push(...P):p.bin=P;}o&&typeof p?.reference_private_key=="string"&&(this.__private_access_key[o]=p.reference_private_key);let A=await ie.bind(this)(p,"called from postRecord");return A.unique_id&&(this.__my_unique_ids[A.unique_id]=A.record_id,$()&&window.sessionStorage.setItem(`${this.service}:uniqueids`,JSON.stringify(this.__my_unique_ids))),A}async function Ft(n,e){let t=await E.bind(this)("get-table",g.Params(n||{},{table:"string",condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}),Object.assign({auth:!!this.__user},{fetchOptions:e})),i={cnt_rec:"number_of_records",tbl:"table",srvc:"service"};if(Array.isArray(t?.list))for(let r of t.list)for(let s in i)r.hasOwnProperty(s)&&(r[i[s]]=r[s],delete r[s]);return t}async function Mt(n,e){if(!n?.table)throw new a('"table" is required.',{code:"INVALID_PARAMETER"});let t=g.Params(n||{},{table:"string",index:s=>de(s,"index.name"),order:{by:["average_number","total_number","number_count","average_bool","total_bool","bool_count","string_count","index_name","number_of_records"],value:["string","number","boolean"],condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}},["table"]);if(t.hasOwnProperty("order")){if(!t.order?.by)throw new a('"order.by" is required.',{code:"INVALID_PARAMETER"});if(t.order.hasOwnProperty("condition")&&!t.order.hasOwnProperty("value"))throw new a('"value" is required for "condition".',{code:"INVALID_PARAMETER"});if(t.hasOwnProperty("index")&&t.index.substring(t.index.length-1)!==".")throw new a('"index" should be a parent index name of the compound index when using "order.by"',{code:"INVALID_PARAMETER"})}let i=await E.bind(this)("get-index",t,Object.assign({auth:!!this.__user},{fetchOptions:e})),r={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(i?.list)&&(i.list=i.list.map(s=>{let o=s.idx.split("/"),c={table:o[1],index:o[2],number_of_records:s.cnt_rec};for(let l in r)Object.prototype.hasOwnProperty.call(s,l)&&(c[r[l]]=s[l]);return c})),i}async function Vt(n,e){let t=await E.bind(this)("get-tag",g.Params(n||{},{table:"string",tag:"string",condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}),Object.assign({auth:!!this.__user},{fetchOptions:e}));return Array.isArray(t?.list)&&(t.list=t.list.map(i=>{let r=i.tag.split("/");return {table:r[1],tag:r[0],number_of_records:i.cnt_rec}})),t}async function $t(n,e){let t=await E.bind(this)("get-uniqueid",g.Params(n||{},{unique_id:"string",condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}),Object.assign({auth:!!this.__user},{fetchOptions:e}));if(Array.isArray(t?.list))for(let i in t.list){let r=t.list[i];t.list[i]={unique_id:r.unq,record_id:r.rec};}return t}async function qt(n,e){await this.__connection;let t=await Ut.bind(this)(n,true),i=t.is_reference_fetch,r=await E.bind(this)("del-records",t.query,{auth:true,fetchOptions:e});return i&&typeof r?.reference_private_key=="string"&&(this.__private_access_key[i]=r.reference_private_key),r?.message||r}function jt(n){return Ht.bind(this)({record_id:n.record_id,user_id:n.user_id,execute:"add"})}function Bt(n){return Ht.bind(this)({record_id:n.record_id,user_id:n.user_id||null,execute:"remove"})}async function Kt(n,e){let t={record_id:n.record_id||void 0,user_id:n.user_id||void 0,execute:"list"};if(!t.record_id&&!t.user_id)throw new a("Either record_id or user_id must be provided.",{code:"INVALID_PARAMETER"});if(t.user_id)if(typeof t.user_id=="string")g.UserId(t.user_id),t.user_id=[t.user_id];else if(Array.isArray(t.user_id))for(let s of t.user_id)g.UserId(s);else throw new a("user_id should be type: <string | string[]>",{code:"INVALID_PARAMETER"});let i=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),r=await E.bind(this)("grant-private-access",t,{auth:true,fetchOptions:e});return r.list=r.list.map(i),r}function Qt(n){let e=n.record_id,t=n.reference_id||void 0;if(!e)throw new a("Record ID is required.",{code:"INVALID_PARAMETER"});if(typeof e!="string")throw new a("Record ID should be type: <string | string[]>",{code:"INVALID_PARAMETER"});if(t&&typeof t!="string")throw new a("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(Ae[e])return Ae[e];let i=E.bind(this)("request-private-access-key",{record_id:e,reference_id:t},{auth:true}).then(r=>{let s=typeof r=="string"?r:r?.private_key;if(typeof s!="string")throw new a("Invalid private access key response.",{code:"ERROR"});return this.__private_access_key[e]=s,s}).finally(()=>{delete Ae[e];});return Ae[e]=i,i}function Ht(n){n.execute;let t=g.Params(n,{record_id:"string",user_id:i=>{if(!i)throw new a("User ID is required.",{code:"INVALID_PARAMETER"});let r=i;if(typeof r=="string"&&(r=[r]),r.length>100)throw new a("Cannot process more than 100 users at once.",{code:"INVALID_REQUEST"});for(let s of r)g.UserId(s,'User ID in "user_id"');return r},execute:["add","remove"]},["execute","record_id","user_id"]);return t.user_id||(t.user_id=null),E.bind(this)("grant-private-access",t,{auth:true})}var I={},O={},B={},W={},H={},Te={},Pe={};function Wt(n,e,t){n[e]||(n[e]=[]),n[e].push(t);}async function Se(n,e,t){let i=[];if(n[e]){for(let r of n[e])if(r){let s=t(r);s instanceof Promise&&(s=await s),i.push(s);}delete n[e];}return i}async function qe(n,e){if(!this?.session?.accessToken?.jwtToken)throw new a("Access token is required.",{code:"INVALID_PARAMETER"});let t=await this.__socket;async function i(r,s,o){this.log("answerSdpOffer from",s),await I[s].setRemoteDescription(new RTCSessionDescription(r));let c=await I[s].createAnswer();await I[s].setLocalDescription(c),o.send(JSON.stringify({action:"rtc",uid:s,content:{sdpanswer:c},token:this.session.accessToken.jwtToken}));}I?.[e]?n?(await Se(Pe,e,r=>i.bind(this)(r,e,t)),await i.bind(this)(n,e,t)):await Se(Pe,e,r=>i.bind(this)(r,e,t)):n&&Wt(Pe,e,n);}async function je(n,e){if(this.log("receiveIceCandidate",n),I?.[e]&&I[e]?.remoteDescription&&I[e]?.remoteDescription?.type){if(!n)return Se(Te,e,t=>I[e].addIceCandidate(t));await Se(Te,e,t=>I[e].addIceCandidate(t)),await I[e].addIceCandidate(n);}else Wt(Te,e,n);}async function K(n){if(typeof window>"u"||window._runningInNodeJS)throw new a("WebRTC is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});g.Params(n,{cid:s=>{if(typeof s!="string")throw new a('"cid" should be type: <string>.',{code:"INVALID_PARAMETER"});if(s&&s.slice(0,4)!=="cid:")throw new a('"cid" should be a valid connection id.',{code:"INVALID_PARAMETER"});return s},close:"boolean"});let e=await this.__socket,{cid:t,close_all:i=false}=n||{};if(!i&&!t)throw new a('"cid" is required.',{code:"INVALID_PARAMETER"});let r=s=>{if(!s)throw new a('"cid" is required.',{code:"INVALID_PARAMETER"});if(delete Pe[s],delete Te[s],O[s]&&Object.values(O[s]).forEach(o=>{o.readyState!=="closed"&&o.close();}),delete O[s],I?.[s]){I[s].connectionState!=="closed"&&(I[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:I[s],timestamp:new Date().toISOString(),state:I[s].connectionState,iceState:I[s].iceConnectionState,signalingState:I[s].signalingState};H[s]&&H[s](o),this.log("closeRTC",o);}delete H[s],delete W[s],delete B[s],delete I[s];};if(i)for(let s in I)r(s);else r(t);this.log("Cleaning up media stream..."),this.__mediaStream&&(this.__mediaStream.getTracks().forEach(s=>{s.stop();}),this.__mediaStream=null);}async function Jt(n){if(n instanceof MediaStream)return n;if(!n.video&&!n.audio){let e=new MediaStream,t=document.createElement("canvas");t.width=1,t.height=1;let r=t.captureStream().getVideoTracks()[0];return e.addTrack(r),e}return window.navigator.mediaDevices.getUserMedia(n)}async function zt(n,e){if(typeof window>"u"||window._runningInNodeJS)throw new a("WebRTC is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(typeof e!="function")throw new a("Callback is required.",{code:"INVALID_PARAMETER"});if(!this?.session?.accessToken?.jwtToken)throw new a("Access token is required.",{code:"INVALID_PARAMETER"});n=g.Params(n,{cid:o=>{if(typeof o!="string")throw new a('"cid" should be type: <string>.',{code:"INVALID_PARAMETER"});if(o&&o.slice(0,4)!=="cid:")throw new a('"cid" should be a valid connection id.',{code:"INVALID_PARAMETER"});return o},ice:["string",()=>"stun:stun.skapi.com:3468"],media:o=>o,channels:["text-chat","file-transfer","video-chat","voice-chat","gaming",{ordered:"boolean",maxPacketLifeTime:"number",maxRetransmits:"number",protocol:"string"},()=>[{ordered:true,maxPacketLifeTime:10,protocol:"default"}]]},["cid"]);let{cid:t,ice:i}=n;if(!(n?.media instanceof MediaStream)&&(n?.media?.video||n?.media?.audio)&&window.location.hostname!=="localhost"&&window.location.protocol!=="https:")throw new a("Media stream is only supported on either localhost or https.",{code:"INVALID_REQUEST"});let r=this.__socket?await this.__socket:this.__socket;if(!r)throw new a("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});if(r.readyState!==1)throw new a("Realtime connection is not ready.",{code:"INVALID_REQUEST"});let s={iceServers:[{urls:i}]};I?.[t]||(I[t]=new RTCPeerConnection(s)),n?.media&&(this.__mediaStream=await Jt(n.media),this.__mediaStream.getTracks().forEach(o=>{I[t].addTrack(o,this.__mediaStream);})),H[t]=e,O[t]||(O[t]={});for(let o=0;o<n.channels.length;o++){let c=n.channels[o];if(typeof c=="string")switch(c){case "text-chat":c={ordered:true,maxRetransmits:10,protocol:"text-chat"};break;case "file-transfer":c={ordered:false,maxPacketLifeTime:3e3,protocol:"file-transfer"};break;case "video-chat":c={ordered:true,maxRetransmits:10,protocol:"video-chat"};break;case "voice-chat":c={ordered:true,maxRetransmits:10,protocol:"voice-chat"};break;case "gaming":c={ordered:false,maxPacketLifeTime:100,protocol:"gaming"};break;default:c={ordered:true,maxRetransmits:10,protocol:"default"};break}let l=c.protocol||"default";if(Object.keys(O[t]).includes(l))throw new a(`Data channel with the protocol "${l}" already exists.`,{code:"INVALID_REQUEST"});let d=I[t].createDataChannel(l,c);O[t][l]=d;}for(let o in O[t]){let c=O[t][o];Zt.bind(this)(t,c);}return Xt.bind(this)(t,["onnegotiationneeded"]),await $e.bind(this)(t),{hangup:()=>B[t]&&B[t](false),connection:new Promise(o=>{B[t]=(c=>{if(this.log("receiver picked up the call",t),!c)return K.bind(this)({cid:t}),null;I[t].onnegotiationneeded=()=>{this.log("onnegotiationneeded",`sending offer to "${t}".`),$e.bind(this)(t),H[t]&&H[t]({type:"negotiationneeded",target:I[t],timestamp:new Date().toISOString(),signalingState:I[t].signalingState,connectionState:I[t].iceConnectionState,gatheringState:I[t].iceGatheringState});},o({target:I[t],channels:O[t],hangup:()=>K.bind(this)({cid:t}),media:this.__mediaStream});}).bind(this);})}}function Gt(n){return async(e,t)=>{e=e||{},e=N(e).data;let i=n.sender_cid,r=await this.__socket;if(!W[i])return null;if(typeof t!="function")throw new a("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 a("Media stream is only supported on either localhost or https.",{code:"INVALID_REQUEST"});let{ice:s="stun:stun.skapi.com:3468"}=e;return I?.[i]||(I[i]=new RTCPeerConnection({iceServers:[{urls:s}]})),e?.media&&(this.__mediaStream=await Jt(e.media),this.__mediaStream.getTracks().forEach(o=>{I[i].addTrack(o,this.__mediaStream);})),delete W[i],H[i]=t,O[i]||(O[i]={}),I[i].ondatachannel=o=>{this.log("ondatachannel",`received data channel "${o.channel.label}".`);let c=o.channel;O[i][c.label]=c,Zt.bind(this)(i,c);},Xt.bind(this)(i,["onnegotiationneeded"]),await qe.bind(this)(null,i),await je.bind(this)(null,i),r.send(JSON.stringify({action:"rtc",uid:i,content:{pickup:this.user.user_id},token:this.session.accessToken.jwtToken})),{target:I[i],channels:O[i],hangup:()=>K.bind(this)({cid:i}),media:this.__mediaStream}}}async function $e(n){if(!this?.session?.accessToken?.jwtToken)throw new a("Access token is required.",{code:"INVALID_PARAMETER"});this.log("sendOffer",n);let e=await this.__socket,t=await I[n].createOffer();await I[n].setLocalDescription(t);let i=I[n].localDescription;this.log("rtcSdpOffer to",i),e.send(JSON.stringify({action:"rtc",uid:n,content:{sdpoffer:i},token:this.session.accessToken.jwtToken}));}async function kr(n,e){if(!this?.session?.accessToken?.jwtToken)throw new a("Access token is required.",{code:"INVALID_PARAMETER"});this.log("sendIceCandidate to",e);let t=await this.__socket;if(!n.candidate){this.log("candidate-end","all ice candidates have been sent");return}let i=H[e]||(()=>{}),r=n.candidate;this.log("ice gathering state set to",I[e].iceGatheringState),i({type:"icecandidate",target:I[e],timestamp:new Date().toISOString(),candidate:n.candidate.candidate,sdpMid:n.candidate.sdpMid,sdpMLineIndex:n.candidate.sdpMLineIndex,usernameFragment:n.candidate.usernameFragment,protocol:n.candidate.protocol,gatheringState:I[e].iceGatheringState,connectionState:I[e].iceConnectionState}),t.send(JSON.stringify({action:"rtc",uid:e,content:{candidate:r},token:this.session.accessToken.jwtToken}));}function Xt(n,e){let t=new Set(e),i=H[n]||(o=>{}),r=I[n],s={ontrack:o=>{i({type:"track",target:r,timeStamp:o.timeStamp,streams:o.streams,track:o.track});},onicecandidate:o=>{kr.bind(this)(o,n),o.candidate?i({type:"icecandidate",target:r,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:r.iceGatheringState,connectionState:r.iceConnectionState}):i({type:"icecandidateend",target:r,timestamp:new Date().toISOString()});},onicecandidateerror:o=>{i({type:"icecandidateerror",target:r,timestamp:new Date().toISOString(),errorCode:o.errorCode,errorText:o.errorText,url:o.url,hostCandidate:o.hostCandidate,gatheringState:r.iceGatheringState,connectionState:r.iceConnectionState});},oniceconnectionstatechange:()=>{i({type:"iceconnectionstatechange",target:r,timestamp:new Date().toISOString(),state:r.iceConnectionState,gatheringState:r.iceGatheringState,signalingState:r.signalingState});},onicegatheringstatechange:()=>{i({type:"icegatheringstatechange",target:r,timestamp:new Date().toISOString(),state:r.iceGatheringState,connectionState:r.iceConnectionState,signalingState:r.signalingState});},onsignalingstatechange:()=>{i({type:"signalingstatechange",target:r,timestamp:new Date().toISOString(),state:r.signalingState,connectionState:r.iceConnectionState,gatheringState:r.iceGatheringState});},onnegotiationneeded:()=>{$e.bind(this)(n),i({type:"negotiationneeded",target:r,timestamp:new Date().toISOString(),signalingState:r.signalingState,connectionState:r.iceConnectionState,gatheringState:r.iceGatheringState});},onconnectionstatechange:()=>{i({type:"connectionstatechange",target:r,timestamp:new Date().toISOString(),state:r.connectionState,iceState:r.iceConnectionState,signalingState:r.signalingState});let o=r.connectionState;(o==="disconnected"||o==="failed"||o==="closed")&&K.bind(this)({cid:n});}};for(let[o,c]of Object.entries(s))t.has(o)||(r[o]=c);}function Zt(n,e,t){let i=new Set(t),r=H[n]||(o=>{}),s={onmessage:o=>{let c={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),r(c);},onerror:o=>{let c={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),r(c);},onclose:o=>{let c={type:o.type,target:e,timeStamp:o.timeStamp,readyState:e.readyState,label:e.label,id:e.id};this.log(`${e.label}: closed`,null),r(c),O[n]&&(delete O[n][e.label],Object.keys(O[n]).length===0&&K.bind(this)({cid:n}));},onbufferedamountlow:o=>{let c={target:e,bufferedAmount:e.bufferedAmount,bufferedAmountLowThreshold:e.bufferedAmountLowThreshold,type:o.type,timeStamp:o.timeStamp};this.log(`${e.label}: bufferedamountlow`,e.bufferedAmount),r(c);},onopen:o=>{this.log("dataChannel",`data channel: "${e.label}" is open and ready to send messages.`);let c={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};r(c);}};for(let[o,c]of Object.entries(s))i.has(o)||(e[o]=c);}var Y,Z=null,ge=true,se=0;async function xr(){if(typeof window>"u"||window._runningInNodeJS)throw new a("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.getProfile(),!this.session)throw new a("No access.",{code:"INVALID_REQUEST"});let n=await this.record_endpoint;return new WebSocket(n.websocket_private+"?token="+this.session.accessToken.jwtToken)}var Be=null;async function Yt(){if(typeof window>"u"||window._runningInNodeJS)throw new a("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});ge=true;let n=this.__socket?await this.__socket:this.__socket;K.bind(this)({close_all:true}),Y&&Ke.bind(this)({group:null}),se=0,Z&&(Z.terminate(),Z=null);try{n&&n.close();}catch{}return window.removeEventListener("visibilitychange",Be),this.__socket=null,null}async function ke(n,e=50,t){if(typeof window>"u"||window._runningInNodeJS)throw new a("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(typeof n!="function")throw new a("Callback must be a function.",{code:"INVALID_REQUEST"});if(t==="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(ge&&(Be=()=>{!document.hidden&&!ge&&ke.bind(this)(n,0,"reconnect");},this.__socket instanceof Promise))return this.__socket;Z&&(Z.terminate(),Z=null),this.__socket=new Promise(async i=>{await ne.bind(this)(),setTimeout(async()=>{let r=await xr.bind(this)();r.onopen=()=>{ge=false,se=0,t!=="reconnect"&&window.addEventListener("visibilitychange",Be),this.log("realtime onopen","Connected to WebSocket server."),n({type:"success",message:"Connected to WebSocket server."}),Y&&r.send(JSON.stringify({action:"joinRoom",rid:Y,token:this.session.accessToken.jwtToken}));let s=`
207
207
  let interval = 15000; // Set interval time 15 seconds
208
208
 
209
209
  function runInterval() {
@@ -212,9 +212,9 @@ var Nn=Object.defineProperty;var Cn=Object.getOwnPropertyDescriptor;var ee=(n=>t
212
212
  }
213
213
 
214
214
  runInterval(); // Start interval
215
- `,o=new Blob([s],{type:"application/javascript"});Z=new Worker(URL.createObjectURL(o)),Z.onmessage=c=>{r.readyState===1&&r.send(JSON.stringify({action:"keepAlive"}));},i(r);},r.onmessage=async s=>{let o="";try{o=JSON.parse(decodeURI(s.data)),this.log("socket onmessage",o);}catch{return}let c;switch(true){case !!o?.["#message"]:c="message";break;case !!o?.["#private"]:c="private";break;case !!o?.["#notice"]:c="notice";break;case !!o?.["#rtc"]:c="rtc";break;case !!o?.["#error"]:c="error";break}if(!c)return;let l={type:c,message:o?.["#rtc"]||o?.["#message"]||o?.["#private"]||o?.["#notice"]||o?.["#error"]||null,sender:o?.["#user_id"]||null,sender_cid:o?.["#scid"]?"cid:"+o["#scid"]:null,sender_rid:o?.["#srid"]||null,code:o?.["#code"]||null};if(c==="notice")n(l);else if(c==="rtc"){if(l.sender!==this.user.user_id){let d=l.message;if(d.hungup){K[l.sender_cid]&&(K[l.sender_cid](false),delete K[l.sender_cid]),H[l.sender_cid]&&delete H[l.sender_cid],I?.[l.sender_cid]&&Q.bind(this)({cid:l.sender_cid}),l.type="rtc:closed",n(l);return}if(d.candidate&&qe.bind(this)(d.candidate,l.sender_cid),d.sdpoffer&&($e.bind(this)(d.sdpoffer,l.sender_cid),H[l.sender_cid]||(H[l.sender_cid]=l.sender_cid,delete l.message,l.connectRTC=zt.bind(this)(l),l.type="rtc:incoming",l.hangup=(()=>{I[l.sender_cid]?Q.bind(this)({cid:l.sender_cid}):H[l.sender_cid]&&(delete H[l.sender_cid],r.send(JSON.stringify({action:"rtc",uid:l.sender_cid,content:{hungup:this.user.user_id},token:this.session.accessToken.jwtToken})));}).bind(this),n(l))),d.pickup&&K[l.sender_cid]&&(K[l.sender_cid](true),delete K[l.sender_cid]),d.sdpanswer&&I[l.sender_cid])if(I[l.sender_cid].signalingState==="have-local-offer")await I[l.sender_cid].setRemoteDescription(new RTCSessionDescription(d.sdpanswer));else throw new a("Invalid signaling state.",{code:"INVALID_REQUEST"})}}else n(l);},r.onclose=()=>{ge?(this.log("realtime onclose","WebSocket connection closed."),n({type:"close",message:"WebSocket connection closed."})):(this.log("realtime onclose","WebSocket unexpected close."),n({type:"error",message:"Skapi: WebSocket unexpected close."}),se++,se<3?(this.log("realtime onclose","Reconnecting to WebSocket server..."+se),n({type:"reconnect",message:"Reconnecting to WebSocket server..."+se}),ke.bind(this)(n,3e3,"reconnect")):(this.log("realtime onclose","Max reconnection attempts reached."),n({type:"error",message:"Skapi: Max reconnection attempts reached."})));},r.onerror=()=>{this.log("realtime onerror","WebSocket connection error."),n({type:"error",message:"Skapi: WebSocket connection error."});};},e);});}async function Yt(n,e,t){if(typeof window>"u"||window._runningInNodeJS)throw new a("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});let i=this.__socket?await this.__socket:this.__socket;if(!i)throw new a("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});if(!e)throw new a("No recipient.",{code:"INVALID_REQUEST"});await ne.bind(this)(),n=D(n).data;let r="";if(t&&(t=g.Params(t,{config:{always:"boolean"},title:"string",body:"string"},["title","body"]),r=JSON.stringify({title:t.title,body:t.body}),new Blob([r]).size>3072))throw new a("Notification size exceeds 3kb.",{code:"INVALID_PARAMETER"});if(i.readyState===1){try{g.UserId(e),i.send(JSON.stringify({action:"sendMessage",uid:e,content:n,notification:r,notificationConfig:t?.config||{},token:`IdT:${this.service}:${this.owner}:`+(this.bearerToken||this.session?.idToken?.jwtToken||"null")}));}catch(s){if(this.log("postRealtime:err",{err:s}),Y!==e)throw new a(`User has not joined to the recipient group. Run joinRealtime({ group: "${e}" })`,{code:"INVALID_REQUEST"});i.send(JSON.stringify({action:"broadcast",rid:e,content:n,notification:r,notificationConfig:t?.config||{},token:`IdT:${this.service}:${this.owner}:`+(this.bearerToken||this.session?.idToken?.jwtToken||"null")}));}return {type:"success",message:"Message sent."}}throw new a("Realtime connection is not open. Try reconnecting with connectRealtime().",{code:"INVALID_REQUEST"})}async function Be(n){if(typeof window>"u"||window._runningInNodeJS)throw new a("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});let e=this.__socket?await this.__socket:this.__socket;if(!e)throw new a("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});await ne.bind(this)(),n=D(n,{nullIfEmpty:true}).data;let{group:t=null}=n;if(!t&&!Y)return {type:"success",message:"Left realtime message group."};if(t!==null&&typeof t!="string")throw new a('"group" must be a string | null.',{code:"INVALID_PARAMETER"});return e.send(JSON.stringify({action:"joinRoom",rid:t,token:this.session.accessToken.jwtToken})),Y=t,{type:"success",message:t?`Joined realtime message group: "${t}".`:"Left realtime message group."}}async function en(n,e){n=g.Params(n,{user_id:i=>g.UserId(i,'User ID in "user_id"'),group:["string",()=>{if(!Y)throw new a('No group has been joined. Otherwise "group" is required.',{code:"INVALID_REQUEST"});return Y}]});let t=await R.bind(this)("get-ws-group",n,{fetchOptions:e,auth:true,method:"post"});return t.list=t.list.map(i=>({user_id:i.uid.split("#")[1],cid:"cid:"+i.cid})),t}async function tn(n,e){if(await this.__connection,n||(n={searchFor:"group",value:" ",condition:">"}),n=g.Params(n,{searchFor:["group","number_of_users",()=>"group"],value:["string","number",()=>n?.searchFor&&n?.searchFor==="number_of_users"?0:" "],condition:[">",">=","=","<","<=","!=","gt","gte","eq","lt","lte","ne"],range:["string","number"]}),n.condition||(n.value===" "||!n.value?n.condition=">":n.condition="="),n.range&&n.condition&&delete n.condition,n.searchFor==="number_of_users"&&typeof n.value!="number")throw new a('"value" must be a number.',{code:"INVALID_PARAMETER"});if(n.searchFor==="group"&&typeof n.value!="string")throw new a('"value" must be a string.',{code:"INVALID_PARAMETER"});if(n.hasOwnProperty("range")&&typeof n.range!=typeof n.value)throw new a(`"range" must be a ${typeof n.value}.`,{code:"INVALID_PARAMETER"});let t=await R.bind(this)("get-ws-group",n,{fetchOptions:e,auth:true,method:"post"});return t.list=t.list.map(i=>({group:i.rid.split("#")[1],number_of_users:i.cnt})),t}var kr=typeof FormData<"u",xr=typeof HTMLFormElement<"u",vr=typeof SubmitEvent<"u";async function nn(n){let e=false,t=r=>{for(let s in r)if(typeof r[s]=="string"&&r[s].includes("$CLIENT_SECRET")){e=true;break}};if(n=g.Params(n,{url:r=>{if(!r||typeof r!="string")throw new a('"url" should be type: <string>.',{code:"INVALID_PARAMETER"});return g.Url(r),r.includes("$CLIENT_SECRET")&&(e=true),r},clientSecretName:"string",method:r=>{if(r&&typeof r!="string")throw new a('"method" should be either "GET" or "POST" or "DELETE" or "PUT".',{code:"INVALID_PARAMETER"});let s=r.toLowerCase();if(s!=="get"&&s!=="post"&&s!=="delete"&&s!=="put")throw new a('"method" should be either "GET" or "POST" or "DELETE" or "PUT".',{code:"INVALID_PARAMETER"});return s},headers:r=>{if(r&&typeof r!="object")throw new a('"headers" should be type: <object>.',{code:"INVALID_PARAMETER"});return t(r),r},data:r=>{if(r&&typeof r!="object")throw new a('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return t(r),r},params:r=>{if(r&&typeof r!="object")throw new a('"params" should be type: <object>.',{code:"INVALID_PARAMETER"});return t(r),r}},["clientSecretName","method","url"]),!e)throw new a(`At least one parameter value should include "$CLIENT_SECRET" in ${n.method.toLowerCase()==="post"?'"data"':'"params"'} or "headers".`,{code:"INVALID_PARAMETER"});await this.__connection;let i=!!this.__user;return R.bind(this)("csr",n,{auth:i})}async function rn(n){await this.__connection;let e={name:"string",email:t=>(g.Email(t),t),subject:"string",message:"string"};return n=g.Params(n,e,["name","email","subject","message"]),await R.bind(this)("send-inquiry",n),"SUCCESS: Inquiry has been sent."}async function sn(n,e){if(await this.__connection,kr&&n instanceof FormData||xr&&n instanceof HTMLFormElement||vr&&n instanceof SubmitEvent){if(!e)throw new a("Url string as a second argument is required when form is passed.",{code:"INVALID_PARAMETER"});let i=D(n);n={url:e,data:i.data,sync:true};}let t={url:i=>g.Url(i),data:i=>i,sync:["boolean",()=>true]};if(Array.isArray(n))for(let i of n)i=g.Params(i,t);else n=g.Params(n,t);return R.bind(this)("post-secure",n,{auth:true})}async function on(n,e){await this.__connection;let{auth:t=false,method:i="POST",bypassAwaitConnection:r=false,responseType:s,contentType:o,progress:c}=e||{};if(e=Object.assign({auth:t,method:i,bypassAwaitConnection:r,responseType:s,contentType:o},{fetchOptions:{progress:c}}),typeof n!="object"&&(o==="application/json"||o===void 0))throw new a('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return R.bind(this)("mock",n,e)}async function an(n,e){await this.__connection,n=g.Params(n||{},{access_group:i=>{if(i==="authorized"&&(i=1),i==="public"&&(i=0),typeof i!="number")throw new a('"access_group" should be type number.',{code:"INVALID_PARAMETER"});if(i<0)throw new a('"access_group" should be zero or a positive number.',{code:"INVALID_PARAMETER"});if(i>this.__user.access_group)throw new a("User has no access.",{code:"INVALID_REQUEST"});return i}});let t=await R.bind(this)("get-feed",n,{auth:true,fetchOptions:e});for(let i in t.list)t.list[i]=await ie.bind(this)(t.list[i]);return t}function fe(n){if(n===this.__user.user_id)throw new a(`"user_id" cannot be the user's own ID.`,{code:"INVALID_PARAMETER"});return g.UserId(n,'"user_id"')}async function cn(n,e){if(n=D(n,{ignoreEmpty:true}).data,n=g.Params(n,{subscriber:i=>g.UserId(i,'User ID in "subscriber"'),subscription:fe.bind(this),blocked:"boolean"}),!n.subscriber&&!n.subscription)throw new a('At least either "subscriber" or "subscription" should have a value.',{code:"INVALID_PARAMETER"});let t=await R.bind(this)("get-subscription",n,Object.assign({auth:true},{fetchOptions:e}));return t.list=t.list.map((i=>{let r={};if(i.sub){let s=i.sub.split("#");r.subscriber=s[2],r.subscription=s[0];}else r.subscriber=i.subscriber,r.subscription=i.subscription;return r.timestamp=i?.timestamp||i.stmp,r.blocked=i?.blocked||i.grp.substring(0,1)==="N",Object.assign(r,i.opt),r})),t}async function ln(n){await this.__connection,n=g.Params(n,{user_id:fe.bind(this),get_feed:["boolean",()=>false],get_notified:["boolean",()=>false],get_email:i=>{if(i&&!this.__user.email||!this.__user.email_verified)throw new a("User has no verified email address.",{code:"INVALID_REQUEST"});return !!i}},["user_id"]);let e=await R.bind(this)("subscription",{subscribe:n.user_id,option:{get_feed:n.get_feed,get_notified:n.get_notified,get_email:n.get_email||false}},{auth:true}),t={};if(e.sub){let i=e.sub.split("#");t.subscriber=i[2],t.subscription=i[0];}else t.subscriber=e.subscriber,t.subscription=e.subscription;return t.timestamp=e?.timestamp||e.stmp,t.blocked=e?.blocked||e.grp.substring(0,1)==="N",Object.assign(t,e.opt),t}async function un(n){await this.__connection;let{user_id:e}=g.Params(n,{user_id:fe.bind(this)},["user_id"]);return await R.bind(this)("subscription",{unsubscribe:e},{auth:true})}async function dn(n){await this.__connection;let{user_id:e}=g.Params(n,{user_id:fe.bind(this)},["user_id"]);return await R.bind(this)("subscription",{block:e},{auth:true})}async function gn(n){await this.__connection;let{user_id:e}=g.Params(n,{user_id:fe.bind(this)},["user_id"]);return await R.bind(this)("subscription",{unblock:e},{auth:true})}async function fn(n,e){await this.__connection;let t=await M.bind(this)();n=g.Params(n,{user_id:o=>{if(o!==this.__user.user_id&&!t)throw new a("No access.",{code:"INVALID_REQUEST"});return o},group:o=>{if(o==="public"&&(o=0),o==="authorized"&&(o=1),typeof o!="number")throw new a('"group" should be type number | "public" | "authorized".',{code:"INVALID_PARAMETER"});return o}});let i=await R.bind(this)("get-newsletter-subscription",n,{auth:true,fetchOptions:e||null}),r=i?.list||i,s=[];Array.isArray(r)||(r=[]);for(let o of r){let c=o.subt.split("#"),l=true;c[0].charAt(0)==="@"&&(l=false,c[0]=c[0].substring(1));let d=parseInt(c[0]);s.push({timestamp:o.stmp,group:d,subscribed_email:c[1],active:l});}return i?.list?(i.list=s,i):s}async function hn(n){await this.__connection;let e=g.Params(n||{},{email:t=>Array.isArray(t)&&t.length>0?t.length===1?g.Email(t[0]):t.map(i=>g.Email(i)):g.Email(t),group:["number","public","authorized","admin",t=>{if(typeof t!="string"||t.length>20||!/^[a-zA-Z0-9]+$/.test(t))throw new a('"group" should be an alphanumeric string without spaces and less than 20 characters.',{code:"INVALID_PARAMETER"});return t}],redirect:t=>g.Url(t)},this.__user?["group"]:["email","group"]);return R.bind(this)(`subscribe-${this.__user?"":"public-"}newsletter`,e,{auth:!!this.__user})}async function pn(n){await this.__connection,n=g.Params(n,{group:["number","public","authorized","admin"]},["group"]);let e=Object.assign({action:"unsubscribe"},n);return R.bind(this)("subscribe-newsletter",e,{auth:true})}async function mn(n,e){let t=await M.bind(this)(),i={message_id:"string",timestamp:"number",read:"number",complaint:"number",subject:"string",bounced:"number"};n||(e=Object.assign({ascending:false},e||{})),n=D(n).data,n=n||{searchFor:"timestamp",value:Date.now(),condition:"<",group:"public"},n=g.Params(n,{searchFor:["message_id","timestamp","subject","complaint","read","bounced"],value:l=>{if(typeof l!==i[n.searchFor])throw new a(`"value" type does not match the type of "${n.searchFor}" index.`,{code:"INVALID_PARAMETER"});if(typeof l=="string"&&!l)throw new a('"value" should not be empty string.',{code:"INVALID_PARAMETER"});return l},range:l=>{if(!n.hasOwnProperty("value")||typeof l!=typeof n.value)throw new a('"range" should match type of "value".',{code:"INVALID_PARAMETER"});return l},condition:[">",">=","=","<","<=","gt","gte","eq","lt","lte",()=>"="],group:l=>{if(l==="public")return 0;if(!this.session)throw new a("User should be logged in.",{code:"INVALID_REQUEST"});if(l==="authorized")return 1;if(typeof l=="number"){if(!t&&l>parseInt(this.user?.access_group||this.session?.idToken?.payload?.access_group))throw new a("User has no access.",{code:"INVALID_REQUEST"});return l}throw new a('"group" should be type: number | "public" | "authorized".',{code:"INVALID_PARAMETER"})}},["searchFor","value","group"]);let r=n.group===0?"get-public-newsletters":"get-newsletters",s=await R.bind(this)(r,n,Object.assign({method:"get",auth:r==="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"},c={message_id:"",timestamp:0,complaint:0,read:0,subject:"",bounced:"",url:"",delivered:0};return s.list=s.list.map(l=>{let d={};for(let h in o)d[h]=l[o[h]]||c[h];return d.bounced=String(d.bounced),d}),s}async function _n(n){let e=g.Params(n,{user_id:i=>g.UserId(i,'"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 M.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}return await R.bind(this)("block-account",e,{auth:true})}async function bn(n){let e=g.Params(n,{user_id:i=>g.UserId(i,'"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 M.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}return await R.bind(this)("block-account",e,{auth:true})}async function yn(n){let e=g.Params(n,{user_id:i=>g.UserId(i,'"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 M.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}return await R.bind(this)("remove-account",e,{auth:true})}async function wn(n,e){let t={email:s=>g.Email(s),password:s=>g.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=>g.Birthdate(s),phone_number:s=>g.PhoneNumber(s),picture:s=>{if(s)return g.Url(s)},profile:s=>{if(s)return g.Url(s)},website:s=>{if(s)return g.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 a('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof s!="number"||s<1||s>100)throw new a('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"});return s}},i=g.Params(n,t,["email"]);if(e=g.Params(e,{confirmation_url:s=>{let o=s;if(typeof s=="string")o=g.Url(s);else throw new a('"options.confirmation_url" should be type: <string>.',{code:"INVALID_PARAMETER"});if(o&&!i.email)throw new a('"email" is required for signup confirmation.',{code:"INVALID_PARAMETER"});return o},email_subscription:s=>{if(typeof s!="boolean")throw new a('"options.email_subscription" should be type: <boolean>.',{code:"INVALID_PARAMETER"});if(!e?.confirmation_url)throw new a('"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 a('"options.template" should be type: <object> with "url" and "subject".',{code:"INVALID_PARAMETER"});return {url:g.Url(s.url),subject:s.subject}}}),i.signup_confirmation=e?.confirmation_url||true,i.email_subscription=e?.email_subscription||false,i.template=e?.template||{},!await M.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}return await R.bind(this)("admin-signup",i,{auth:true})}async function En(n){let e={email:r=>g.Email(r),password:r=>g.Password(r),openid_id:"string",name:"string",username:"string",gender:"string",address:r=>{if(!r)return "";if(typeof r=="string")return r;if(typeof r=="object")return JSON.stringify(r)},birthdate:r=>g.Birthdate(r),phone_number:r=>g.PhoneNumber(r),picture:r=>r?g.Url(r):"",profile:r=>r?g.Url(r):"",website:r=>r?g.Url(r):"",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:r=>{try{typeof r=="string"&&(r=parseInt(r));}catch{throw new a('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof r!="number"||r<1||r>100)throw new a('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"});return r}},t=g.Params(n,e,["email","password"]);if(!await M.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}return await R.bind(this)("admin-signup",t,{auth:true})}async function Rn(n){if(n=g.Params(n,{user_id:t=>g.UserId(t,'"user_id"'),access_group:t=>{try{typeof t=="string"&&(t=parseInt(t));}catch{throw new a('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof t=="number"&&t>0&&t<100)return t;throw new a('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"})}},["user_id","access_group"]),!await M.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}return await R.bind(this)("grant-access",n,{auth:true})}async function An(n,e){if(n=g.Params(n,{email:"string"}),!await M.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}let i=await R.bind(this)("invitation-list",Object.assign({mode:"search"},n),{fetchOptions:e,auth:true});return i.list=i.list.map(r=>ae(r.user)),i}async function In(n){if(n=g.Params(n,{email:t=>g.Email(t)},["email"]),!await M.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}return await R.bind(this)("invitation-list",Object.assign({mode:"cancel"},n),{auth:true})}async function Tn(n){if(n=g.Params(n,{email:t=>g.Email(t)},["email"]),!await M.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}return await R.bind(this)("invitation-list",Object.assign({mode:"resend"},n),{auth:true})}async function Pn(n){if(typeof window>"u"||window._runningInNodeJS)throw new a("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.__connection,!n.endpoint)throw new a("Missing parameter: endpoint",{code:"INVALID_PARAMETER"});if(!n.keys||!n.keys.p256dh||!n.keys.auth)throw new a("Missing parameter: keys.p256dh or keys.auth",{code:"INVALID_PARAMETER"});return await R.bind(this)("store-subscription",{endpoint:n.endpoint,keys:n.keys},{auth:true}),"SUCCESS: Subscribed to receive notifications."}async function Sn(n){if(typeof window>"u"||window._runningInNodeJS)throw new a("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.__connection,!n.endpoint)throw new a("Missing parameter: endpoint",{code:"INVALID_PARAMETER"});if(!n.keys||!n.keys.p256dh||!n.keys.auth)throw new a("Missing parameter: keys.p256dh or keys.auth",{code:"INVALID_PARAMETER"});return await R.bind(this)("delete-subscription",{endpoint:n.endpoint,keys:n.keys},{auth:true}),"SUCCESS: Unsubscribed from notifications."}async function kn(){if(typeof window>"u"||window._runningInNodeJS)throw new a("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});return await this.__connection,{VAPIDPublicKey:await R.bind(this)("get-vapid-public-key",null,{auth:true})}}async function xn(n,e){if(typeof window>"u"||window._runningInNodeJS)throw new a("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});await this.__connection;let{title:t,body:i}=D(n||{},{nullIfEmpty:true}).data;if(!t)throw new a("Missing parameter: message title",{code:"INVALID_PARAMETER"});if(!i)throw new a("Missing parameter: message body",{code:"INVALID_PARAMETER"});let r={title:t,body:i};return e?(typeof e=="string"&&(e=[e]),r.user_ids=e):r.user_ids="all_users",await R.bind(this)("push-notification",r,{auth:true}),"SUCCESS: Notification sent."}async function vn(n){await this.__connection,n=g.Params(n,{spell:"string",name:"string",magic:t=>t},["spell","name"]);await R.bind(this)("castspell",n);return `The spell "${n.spell}" has been cast.`}async function Dn(n){return await this.__connection,n=g.Params(n||{},{search:["spell","name",()=>"spell"],value:"string"}),await R.bind(this)("getspell",n)}async function Un(n){await this.__connection,n=g.Params(n,{message:"string",name:"string"},["message","name"]);let e=await R.bind(this)("dopamine",n,{auth:true}),t=e?.previous_message?.message,i=e?.previous_message?.name;if($())t&&i&&window.alert(`${i} said: ${t}`),window.location.href=e.video;else return t&&i?`${i} said: ${t}
215
+ `,o=new Blob([s],{type:"application/javascript"});Z=new Worker(URL.createObjectURL(o)),Z.onmessage=c=>{r.readyState===1&&r.send(JSON.stringify({action:"keepAlive"}));},i(r);},r.onmessage=async s=>{let o="";try{o=JSON.parse(decodeURI(s.data)),this.log("socket onmessage",o);}catch{return}let c;switch(true){case !!o?.["#message"]:c="message";break;case !!o?.["#private"]:c="private";break;case !!o?.["#notice"]:c="notice";break;case !!o?.["#rtc"]:c="rtc";break;case !!o?.["#error"]:c="error";break}if(!c)return;let l={type:c,message:o?.["#rtc"]||o?.["#message"]||o?.["#private"]||o?.["#notice"]||o?.["#error"]||null,sender:o?.["#user_id"]||null,sender_cid:o?.["#scid"]?"cid:"+o["#scid"]:null,sender_rid:o?.["#srid"]||null,code:o?.["#code"]||null};if(c==="notice")n(l);else if(c==="rtc"){if(l.sender!==this.user.user_id){let d=l.message;if(d.hungup){B[l.sender_cid]&&(B[l.sender_cid](false),delete B[l.sender_cid]),W[l.sender_cid]&&delete W[l.sender_cid],I?.[l.sender_cid]&&K.bind(this)({cid:l.sender_cid}),l.type="rtc:closed",n(l);return}if(d.candidate&&je.bind(this)(d.candidate,l.sender_cid),d.sdpoffer&&(qe.bind(this)(d.sdpoffer,l.sender_cid),W[l.sender_cid]||(W[l.sender_cid]=l.sender_cid,delete l.message,l.connectRTC=Gt.bind(this)(l),l.type="rtc:incoming",l.hangup=(()=>{I[l.sender_cid]?K.bind(this)({cid:l.sender_cid}):W[l.sender_cid]&&(delete W[l.sender_cid],r.send(JSON.stringify({action:"rtc",uid:l.sender_cid,content:{hungup:this.user.user_id},token:this.session.accessToken.jwtToken})));}).bind(this),n(l))),d.pickup&&B[l.sender_cid]&&(B[l.sender_cid](true),delete B[l.sender_cid]),d.sdpanswer&&I[l.sender_cid])if(I[l.sender_cid].signalingState==="have-local-offer")await I[l.sender_cid].setRemoteDescription(new RTCSessionDescription(d.sdpanswer));else throw new a("Invalid signaling state.",{code:"INVALID_REQUEST"})}}else n(l);},r.onclose=()=>{ge?(this.log("realtime onclose","WebSocket connection closed."),n({type:"close",message:"WebSocket connection closed."})):(this.log("realtime onclose","WebSocket unexpected close."),n({type:"error",message:"Skapi: WebSocket unexpected close."}),se++,se<3?(this.log("realtime onclose","Reconnecting to WebSocket server..."+se),n({type:"reconnect",message:"Reconnecting to WebSocket server..."+se}),ke.bind(this)(n,3e3,"reconnect")):(this.log("realtime onclose","Max reconnection attempts reached."),n({type:"error",message:"Skapi: Max reconnection attempts reached."})));},r.onerror=()=>{this.log("realtime onerror","WebSocket connection error."),n({type:"error",message:"Skapi: WebSocket connection error."});};},e);});}async function en(n,e,t){if(typeof window>"u"||window._runningInNodeJS)throw new a("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});let i=this.__socket?await this.__socket:this.__socket;if(!i)throw new a("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});if(!e)throw new a("No recipient.",{code:"INVALID_REQUEST"});await ne.bind(this)(),n=N(n).data;let r="";if(t&&(t=g.Params(t,{config:{always:"boolean"},title:"string",body:"string"},["title","body"]),r=JSON.stringify({title:t.title,body:t.body}),new Blob([r]).size>3072))throw new a("Notification size exceeds 3kb.",{code:"INVALID_PARAMETER"});if(i.readyState===1){try{g.UserId(e),i.send(JSON.stringify({action:"sendMessage",uid:e,content:n,notification:r,notificationConfig:t?.config||{},token:`IdT:${this.service}:${this.owner}:`+(this.bearerToken||this.session?.idToken?.jwtToken||"null")}));}catch(s){if(this.log("postRealtime:err",{err:s}),Y!==e)throw new a(`User has not joined to the recipient group. Run joinRealtime({ group: "${e}" })`,{code:"INVALID_REQUEST"});i.send(JSON.stringify({action:"broadcast",rid:e,content:n,notification:r,notificationConfig:t?.config||{},token:`IdT:${this.service}:${this.owner}:`+(this.bearerToken||this.session?.idToken?.jwtToken||"null")}));}return {type:"success",message:"Message sent."}}throw new a("Realtime connection is not open. Try reconnecting with connectRealtime().",{code:"INVALID_REQUEST"})}async function Ke(n){if(typeof window>"u"||window._runningInNodeJS)throw new a("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});let e=this.__socket?await this.__socket:this.__socket;if(!e)throw new a("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});await ne.bind(this)(),n=N(n,{nullIfEmpty:true}).data;let{group:t=null}=n;if(!t&&!Y)return {type:"success",message:"Left realtime message group."};if(t!==null&&typeof t!="string")throw new a('"group" must be a string | null.',{code:"INVALID_PARAMETER"});return e.send(JSON.stringify({action:"joinRoom",rid:t,token:this.session.accessToken.jwtToken})),Y=t,{type:"success",message:t?`Joined realtime message group: "${t}".`:"Left realtime message group."}}async function tn(n,e){n=g.Params(n,{user_id:i=>g.UserId(i,'User ID in "user_id"'),group:["string",()=>{if(!Y)throw new a('No group has been joined. Otherwise "group" is required.',{code:"INVALID_REQUEST"});return Y}]});let t=await E.bind(this)("get-ws-group",n,{fetchOptions:e,auth:true,method:"post"});return t.list=t.list.map(i=>({user_id:i.uid.split("#")[1],cid:"cid:"+i.cid})),t}async function nn(n,e){if(await this.__connection,n||(n={searchFor:"group",value:" ",condition:">"}),n=g.Params(n,{searchFor:["group","number_of_users",()=>"group"],value:["string","number",()=>n?.searchFor&&n?.searchFor==="number_of_users"?0:" "],condition:[">",">=","=","<","<=","!=","gt","gte","eq","lt","lte","ne"],range:["string","number"]}),n.condition||(n.value===" "||!n.value?n.condition=">":n.condition="="),n.range&&n.condition&&delete n.condition,n.searchFor==="number_of_users"&&typeof n.value!="number")throw new a('"value" must be a number.',{code:"INVALID_PARAMETER"});if(n.searchFor==="group"&&typeof n.value!="string")throw new a('"value" must be a string.',{code:"INVALID_PARAMETER"});if(n.hasOwnProperty("range")&&typeof n.range!=typeof n.value)throw new a(`"range" must be a ${typeof n.value}.`,{code:"INVALID_PARAMETER"});let t=await E.bind(this)("get-ws-group",n,{fetchOptions:e,auth:true,method:"post"});return t.list=t.list.map(i=>({group:i.rid.split("#")[1],number_of_users:i.cnt})),t}var vr=typeof FormData<"u",Dr=typeof HTMLFormElement<"u",Ur=typeof SubmitEvent<"u";async function rn(n){let e=false,t=r=>{for(let s in r)if(typeof r[s]=="string"&&r[s].includes("$CLIENT_SECRET")){e=true;break}};if(n=g.Params(n,{url:r=>{if(!r||typeof r!="string")throw new a('"url" should be type: <string>.',{code:"INVALID_PARAMETER"});return g.Url(r),r.includes("$CLIENT_SECRET")&&(e=true),r},clientSecretName:"string",method:r=>{if(r&&typeof r!="string")throw new a('"method" should be either "GET" or "POST" or "DELETE" or "PUT".',{code:"INVALID_PARAMETER"});let s=r.toLowerCase();if(s!=="get"&&s!=="post"&&s!=="delete"&&s!=="put")throw new a('"method" should be either "GET" or "POST" or "DELETE" or "PUT".',{code:"INVALID_PARAMETER"});return s},headers:r=>{if(r&&typeof r!="object")throw new a('"headers" should be type: <object>.',{code:"INVALID_PARAMETER"});return t(r),r},data:r=>{if(r&&typeof r!="object")throw new a('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return t(r),r},params:r=>{if(r&&typeof r!="object")throw new a('"params" should be type: <object>.',{code:"INVALID_PARAMETER"});return t(r),r}},["clientSecretName","method","url"]),!e)throw new a(`At least one parameter value should include "$CLIENT_SECRET" in ${n.method.toLowerCase()==="post"?'"data"':'"params"'} or "headers".`,{code:"INVALID_PARAMETER"});await this.__connection;let i=!!this.__user;return E.bind(this)("csr",n,{auth:i,tokenHeaders:{accessToken:!!i}})}async function sn(n){await this.__connection;let e={name:"string",email:t=>(g.Email(t),t),subject:"string",message:"string"};return n=g.Params(n,e,["name","email","subject","message"]),await E.bind(this)("send-inquiry",n),"SUCCESS: Inquiry has been sent."}async function on(n,e){if(await this.__connection,vr&&n instanceof FormData||Dr&&n instanceof HTMLFormElement||Ur&&n instanceof SubmitEvent){if(!e)throw new a("Url string as a second argument is required when form is passed.",{code:"INVALID_PARAMETER"});let i=N(n);n={url:e,data:i.data,sync:true};}let t={url:i=>g.Url(i),data:i=>i,sync:["boolean",()=>true]};if(Array.isArray(n))for(let i of n)i=g.Params(i,t);else n=g.Params(n,t);return E.bind(this)("post-secure",n,{auth:true})}async function an(n,e){await this.__connection;let{auth:t=false,method:i="POST",bypassAwaitConnection:r=false,responseType:s,contentType:o,tokenHeaders:c,progress:l}=e||{};if(e=Object.assign({auth:t,method:i,bypassAwaitConnection:r,responseType:s,contentType:o,tokenHeaders:c},{fetchOptions:{progress:l}}),typeof n!="object"&&(o==="application/json"||o===void 0))throw new a('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return E.bind(this)("mock",n,e)}async function cn(n,e){await this.__connection,n=g.Params(n||{},{access_group:i=>{if(i==="authorized"&&(i=1),i==="public"&&(i=0),typeof i!="number")throw new a('"access_group" should be type number.',{code:"INVALID_PARAMETER"});if(i<0)throw new a('"access_group" should be zero or a positive number.',{code:"INVALID_PARAMETER"});if(i>this.__user.access_group)throw new a("User has no access.",{code:"INVALID_REQUEST"});return i}});let t=await E.bind(this)("get-feed",n,{auth:true,fetchOptions:e});for(let i in t.list)t.list[i]=await ie.bind(this)(t.list[i]);return t}function fe(n){if(n===this.__user.user_id)throw new a(`"user_id" cannot be the user's own ID.`,{code:"INVALID_PARAMETER"});return g.UserId(n,'"user_id"')}async function ln(n,e){if(n=N(n,{ignoreEmpty:true}).data,n=g.Params(n,{subscriber:i=>g.UserId(i,'User ID in "subscriber"'),subscription:fe.bind(this),blocked:"boolean"}),!n.subscriber&&!n.subscription)throw new a('At least either "subscriber" or "subscription" should have a value.',{code:"INVALID_PARAMETER"});let t=await E.bind(this)("get-subscription",n,Object.assign({auth:true},{fetchOptions:e}));return t.list=t.list.map((i=>{let r={};if(i.sub){let s=i.sub.split("#");r.subscriber=s[2],r.subscription=s[0];}else r.subscriber=i.subscriber,r.subscription=i.subscription;return r.timestamp=i?.timestamp||i.stmp,r.blocked=i?.blocked||i.grp.substring(0,1)==="N",Object.assign(r,i.opt),r})),t}async function un(n){await this.__connection,n=g.Params(n,{user_id:fe.bind(this),get_feed:["boolean",()=>false],get_notified:["boolean",()=>false],get_email:i=>{if(i&&!this.__user.email||!this.__user.email_verified)throw new a("User has no verified email address.",{code:"INVALID_REQUEST"});return !!i}},["user_id"]);let e=await E.bind(this)("subscription",{subscribe:n.user_id,option:{get_feed:n.get_feed,get_notified:n.get_notified,get_email:n.get_email||false}},{auth:true}),t={};if(e.sub){let i=e.sub.split("#");t.subscriber=i[2],t.subscription=i[0];}else t.subscriber=e.subscriber,t.subscription=e.subscription;return t.timestamp=e?.timestamp||e.stmp,t.blocked=e?.blocked||e.grp.substring(0,1)==="N",Object.assign(t,e.opt),t}async function dn(n){await this.__connection;let{user_id:e}=g.Params(n,{user_id:fe.bind(this)},["user_id"]);return await E.bind(this)("subscription",{unsubscribe:e},{auth:true})}async function gn(n){await this.__connection;let{user_id:e}=g.Params(n,{user_id:fe.bind(this)},["user_id"]);return await E.bind(this)("subscription",{block:e},{auth:true})}async function fn(n){await this.__connection;let{user_id:e}=g.Params(n,{user_id:fe.bind(this)},["user_id"]);return await E.bind(this)("subscription",{unblock:e},{auth:true})}async function hn(n,e){await this.__connection;let t=await M.bind(this)();n=g.Params(n,{user_id:o=>{if(o!==this.__user.user_id&&!t)throw new a("No access.",{code:"INVALID_REQUEST"});return o},group:o=>{if(o==="public"&&(o=0),o==="authorized"&&(o=1),typeof o!="number")throw new a('"group" should be type number | "public" | "authorized".',{code:"INVALID_PARAMETER"});return o}});let i=await E.bind(this)("get-newsletter-subscription",n,{auth:true,fetchOptions:e||null}),r=i?.list||i,s=[];Array.isArray(r)||(r=[]);for(let o of r){let c=o.subt.split("#"),l=true;c[0].charAt(0)==="@"&&(l=false,c[0]=c[0].substring(1));let d=parseInt(c[0]);s.push({timestamp:o.stmp,group:d,subscribed_email:c[1],active:l});}return i?.list?(i.list=s,i):s}async function pn(n){await this.__connection;let e=g.Params(n||{},{email:t=>Array.isArray(t)&&t.length>0?t.length===1?g.Email(t[0]):t.map(i=>g.Email(i)):g.Email(t),group:["number","public","authorized","admin",t=>{if(typeof t!="string"||t.length>20||!/^[a-zA-Z0-9]+$/.test(t))throw new a('"group" should be an alphanumeric string without spaces and less than 20 characters.',{code:"INVALID_PARAMETER"});return t}],redirect:t=>g.Url(t)},this.__user?["group"]:["email","group"]);return E.bind(this)(`subscribe-${this.__user?"":"public-"}newsletter`,e,{auth:!!this.__user})}async function mn(n){await this.__connection,n=g.Params(n,{group:["number","public","authorized","admin"]},["group"]);let e=Object.assign({action:"unsubscribe"},n);return E.bind(this)("subscribe-newsletter",e,{auth:true})}async function bn(n,e){let t=await M.bind(this)(),i={message_id:"string",timestamp:"number",read:"number",complaint:"number",subject:"string",bounced:"number"};n||(e=Object.assign({ascending:false},e||{})),n=N(n).data,n=n||{searchFor:"timestamp",value:Date.now(),condition:"<",group:"public"},n=g.Params(n,{searchFor:["message_id","timestamp","subject","complaint","read","bounced"],value:l=>{if(typeof l!==i[n.searchFor])throw new a(`"value" type does not match the type of "${n.searchFor}" index.`,{code:"INVALID_PARAMETER"});if(typeof l=="string"&&!l)throw new a('"value" should not be empty string.',{code:"INVALID_PARAMETER"});return l},range:l=>{if(!n.hasOwnProperty("value")||typeof l!=typeof n.value)throw new a('"range" should match type of "value".',{code:"INVALID_PARAMETER"});return l},condition:[">",">=","=","<","<=","gt","gte","eq","lt","lte",()=>"="],group:l=>{if(l==="public")return 0;if(!this.session)throw new a("User should be logged in.",{code:"INVALID_REQUEST"});if(l==="authorized")return 1;if(typeof l=="number"){if(!t&&l>parseInt(this.user?.access_group||this.session?.idToken?.payload?.access_group))throw new a("User has no access.",{code:"INVALID_REQUEST"});return l}throw new a('"group" should be type: number | "public" | "authorized".',{code:"INVALID_PARAMETER"})}},["searchFor","value","group"]);let r=n.group===0?"get-public-newsletters":"get-newsletters",s=await E.bind(this)(r,n,Object.assign({method:"get",auth:r==="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"},c={message_id:"",timestamp:0,complaint:0,read:0,subject:"",bounced:"",url:"",delivered:0};return s.list=s.list.map(l=>{let d={};for(let h in o)d[h]=l[o[h]]||c[h];return d.bounced=String(d.bounced),d}),s}async function _n(n){let e=g.Params(n,{user_id:i=>g.UserId(i,'"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 M.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}return await E.bind(this)("block-account",e,{auth:true})}async function yn(n){let e=g.Params(n,{user_id:i=>g.UserId(i,'"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 M.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}return await E.bind(this)("block-account",e,{auth:true})}async function wn(n){let e=g.Params(n,{user_id:i=>g.UserId(i,'"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 M.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}return await E.bind(this)("remove-account",e,{auth:true})}async function En(n,e){let t={email:s=>g.Email(s),password:s=>g.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=>g.Birthdate(s),phone_number:s=>g.PhoneNumber(s),picture:s=>{if(s)return g.Url(s)},profile:s=>{if(s)return g.Url(s)},website:s=>{if(s)return g.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 a('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof s!="number"||s<1||s>100)throw new a('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"});return s}},i=g.Params(n,t,["email"]);if(e=g.Params(e,{confirmation_url:s=>{let o=s;if(typeof s=="string")o=g.Url(s);else throw new a('"options.confirmation_url" should be type: <string>.',{code:"INVALID_PARAMETER"});if(o&&!i.email)throw new a('"email" is required for signup confirmation.',{code:"INVALID_PARAMETER"});return o},email_subscription:s=>{if(typeof s!="boolean")throw new a('"options.email_subscription" should be type: <boolean>.',{code:"INVALID_PARAMETER"});if(!e?.confirmation_url)throw new a('"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 a('"options.template" should be type: <object> with "url" and "subject".',{code:"INVALID_PARAMETER"});return {url:g.Url(s.url),subject:s.subject}}}),i.signup_confirmation=e?.confirmation_url||true,i.email_subscription=e?.email_subscription||false,i.template=e?.template||{},!await M.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}return await E.bind(this)("admin-signup",i,{auth:true})}async function Rn(n){let e={email:r=>g.Email(r),password:r=>g.Password(r),openid_id:"string",name:"string",username:"string",gender:"string",address:r=>{if(!r)return "";if(typeof r=="string")return r;if(typeof r=="object")return JSON.stringify(r)},birthdate:r=>g.Birthdate(r),phone_number:r=>g.PhoneNumber(r),picture:r=>r?g.Url(r):"",profile:r=>r?g.Url(r):"",website:r=>r?g.Url(r):"",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:r=>{try{typeof r=="string"&&(r=parseInt(r));}catch{throw new a('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof r!="number"||r<1||r>100)throw new a('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"});return r}},t=g.Params(n,e,["email","password"]);if(!await M.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}return await E.bind(this)("admin-signup",t,{auth:true})}async function An(n){if(n=g.Params(n,{user_id:t=>g.UserId(t,'"user_id"'),access_group:t=>{try{typeof t=="string"&&(t=parseInt(t));}catch{throw new a('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof t=="number"&&t>0&&t<100)return t;throw new a('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"})}},["user_id","access_group"]),!await M.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}return await E.bind(this)("grant-access",n,{auth:true})}async function In(n,e){if(n=g.Params(n,{email:"string"}),!await M.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}let i=await E.bind(this)("invitation-list",Object.assign({mode:"search"},n),{fetchOptions:e,auth:true});return i.list=i.list.map(r=>ae(r.user)),i}async function Tn(n){if(n=g.Params(n,{email:t=>g.Email(t)},["email"]),!await M.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}return await E.bind(this)("invitation-list",Object.assign({mode:"cancel"},n),{auth:true})}async function Pn(n){if(n=g.Params(n,{email:t=>g.Email(t)},["email"]),!await M.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}return await E.bind(this)("invitation-list",Object.assign({mode:"resend"},n),{auth:true})}async function Sn(n){if(typeof window>"u"||window._runningInNodeJS)throw new a("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.__connection,!n.endpoint)throw new a("Missing parameter: endpoint",{code:"INVALID_PARAMETER"});if(!n.keys||!n.keys.p256dh||!n.keys.auth)throw new a("Missing parameter: keys.p256dh or keys.auth",{code:"INVALID_PARAMETER"});return await E.bind(this)("store-subscription",{endpoint:n.endpoint,keys:n.keys},{auth:true}),"SUCCESS: Subscribed to receive notifications."}async function kn(n){if(typeof window>"u"||window._runningInNodeJS)throw new a("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.__connection,!n.endpoint)throw new a("Missing parameter: endpoint",{code:"INVALID_PARAMETER"});if(!n.keys||!n.keys.p256dh||!n.keys.auth)throw new a("Missing parameter: keys.p256dh or keys.auth",{code:"INVALID_PARAMETER"});return await E.bind(this)("delete-subscription",{endpoint:n.endpoint,keys:n.keys},{auth:true}),"SUCCESS: Unsubscribed from notifications."}async function xn(){if(typeof window>"u"||window._runningInNodeJS)throw new a("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});return await this.__connection,{VAPIDPublicKey:await E.bind(this)("get-vapid-public-key",null,{auth:true})}}async function vn(n,e){if(typeof window>"u"||window._runningInNodeJS)throw new a("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});await this.__connection;let{title:t,body:i}=N(n||{},{nullIfEmpty:true}).data;if(!t)throw new a("Missing parameter: message title",{code:"INVALID_PARAMETER"});if(!i)throw new a("Missing parameter: message body",{code:"INVALID_PARAMETER"});let r={title:t,body:i};return e?(typeof e=="string"&&(e=[e]),r.user_ids=e):r.user_ids="all_users",await E.bind(this)("push-notification",r,{auth:true}),"SUCCESS: Notification sent."}async function Dn(n){await this.__connection,n=g.Params(n,{spell:"string",name:"string",magic:t=>t},["spell","name"]);await E.bind(this)("castspell",n);return `The spell "${n.spell}" has been cast.`}async function Un(n){return await this.__connection,n=g.Params(n||{},{search:["spell","name",()=>"spell"],value:"string"}),await E.bind(this)("getspell",n)}async function Nn(n){await this.__connection,n=g.Params(n,{message:"string",name:"string"},["message","name"]);let e=await E.bind(this)("dopamine",n,{auth:true}),t=e?.previous_message?.message,i=e?.previous_message?.name;if($())t&&i&&window.alert(`${i} said: ${t}`),window.location.href=e.video;else return t&&i?`${i} said: ${t}
216
216
  Watch the video here: ${e.video}`:`Your message has been uploaded for future generations to receive.
217
- Watch the video here: ${e.video}`}var b=class{constructor(e,t,i,r){this.__version="1.5.0";this.session=null;this.connection=null;this.__my_unique_ids={};this.userPool=null;this.__socket=null;this.__mediaStream=null;this.host="skapi";this.hostDomain="skapi.com";this.target_cdn="d3e9syvbtso631";this.customApiDomain="skapi.dev";this.requestBatchSize=30;this.__disabledAccount=null;this.__cached_requests={};this.__startKeyHistory={};this.__request_signup_confirmation=null;this.__private_access_key={};this.__class_properties_has_been_cached=false;this.__user=null;this._userProfileListeners=[];this._onLoginListeners=[];this._onBatchProcessListeners=[];this.validate={userId(e){try{return g.UserId(e),!0}catch{return false}},url(e){try{return g.Url(e),!0}catch{return false}},phoneNumber(e){try{return g.PhoneNumber(e),!0}catch{return false}},birthdate(e){try{return g.Birthdate(e),!0}catch{return false}},email(e){try{return g.Email(e),!0}catch{return false}},params(e,t,i){return g.Params(e,t,i)}};this.util={MD5:V,generateRandom:oe,toBase62:Ge,fromBase62:B,decodeServiceId:De,formatServiceId:Xe,extractFormData:D,terminatePendingRequests:It,request:(e,t,i)=>R.bind(this)(e,t,i,{ignoreService:true})};this.__network_logs=false;this.__endpoint_version="v1";this.__public_identifier="";this.bearerToken="";this.registerTicket=nt.bind(this);this.unregisterTicket=rt.bind(this);if(!e||typeof e!="string")throw this._alert("Service ID is required."),new a("Service ID is required.",{code:"INVALID_PARAMETER"});let s=e.split("-").length;if(s===2||s===7)try{let f=De(e);i&&typeof i=="object"&&(r=i),t&&typeof t=="object"&&(i=t),t=f.owner,e=f.service;}catch{throw this._alert("Service ID is invalid."),new a("Service ID is invalid.",{code:"INVALID_PARAMETER"})}if(!t||typeof t!="string")throw this._alert("Owner ID is invalid."),new a("Owner ID is invalid.",{code:"INVALID_PARAMETER"});if(e.toLowerCase()==="service_id")throw this._alert('Replace "service_id" with your actual Service ID.'),new a("Service ID is required.",{code:"INVALID_PARAMETER"});if(t!==this.host)try{g.UserId(t,'"owner"');}catch{throw this._alert("Owner ID is invalid."),new a("Owner ID is invalid.",{code:"INVALID_PARAMETER"})}this.service=e,this.owner=t;let l=true;if(i&&(typeof i.autoLogin=="boolean"&&(l=i.autoLogin),typeof i.requestBatchSize=="number")){if(i.requestBatchSize<1)throw new a('"requestBatchSize" must be greater than 0.',{code:"INVALID_PARAMETER"});this.requestBatchSize=i.requestBatchSize;}i?.eventListener&&typeof i.eventListener=="object"&&(i.eventListener?.onLogin&&typeof i.eventListener.onLogin=="function"&&(this.onLogin=i.eventListener.onLogin),i.eventListener?.onUserUpdate&&typeof i.eventListener.onUserUpdate=="function"&&(this.onUserUpdate=i.eventListener.onUserUpdate),i.eventListener?.onBatchProcess&&typeof i.eventListener.onBatchProcess=="function"&&(this.onBatchProcess=i.eventListener.onBatchProcess)),this.target_cdn=r?.target_cdn||this.target_cdn,this.hostDomain=r?.hostDomain||this.hostDomain,this.customApiDomain=r?.customApiDomain||this.customApiDomain,this.__network_logs=!!r?.network_logs;let d=`https://${this.target_cdn}.cloudfront.net`,h=e.substring(0,4);this.admin_endpoint=fetch(`${d}/${h}/admin-${this.__endpoint_version}.json`).then(f=>f.blob()).then(f=>new Promise((y,P)=>{let _=new FileReader;_.onloadend=()=>y(_.result),_.onerror=P,_.readAsDataURL(f);})).then(f=>{try{return typeof f=="string"?JSON.parse(atob(f.split(",")[1])):null}catch{throw new a("Service does not exist. Create your service from skapi.com",{code:"NOT_EXISTS"})}}),this.record_endpoint=fetch(`${d}/${h}/record-${this.__endpoint_version}.json`).then(f=>f.blob()).then(f=>new Promise((y,P)=>{let _=new FileReader;_.onloadend=()=>y(_.result),_.onerror=P,_.readAsDataURL(f);})).then(f=>{try{return typeof f=="string"?JSON.parse(atob(f.split(",")[1])):null}catch{throw new a("Service does not exist. Create your service from skapi.com",{code:"NOT_EXISTS"})}});let u=$();if(u&&!window.sessionStorage)throw this._alert("This browser is not supported."),new Error("This browser is not supported.");let p=u?JSON.parse(window.sessionStorage.getItem(`${e}#${t}`)||"null"):null;if(this.log("constructor:restore",p),p?.connection){for(let f in p)this[f]=p[f];p.__public_identifier||(this.__public_identifier=`${this.service}:${this.owner}:${oe(16)}`);}this.__authConnection=(async()=>{let f=await this.admin_endpoint,y={UserPoolId:f.userpool_id,ClientId:f.userpool_client};ve()&&(y.Storage=window.localStorage),this.userPool=new CognitoUserPool(y);try{this.user||await F.bind(this)().getSession({skipUserUpdateEventTrigger:!0}),this.user&&(!p?.connection&&!l?G.bind(this)():(this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user)));}catch{}})();let A=u?window.sessionStorage.getItem(`${this.service}:uniqueids`):null;if(A)try{this.__my_unique_ids=JSON.parse(A);}catch{this.__my_unique_ids={};}this.__connection=(async()=>{let f=null;await this.record_endpoint,p?.connection||(f=this._updateConnection());let y=()=>{if(this.__class_properties_has_been_cached)return;let P=()=>{let _={},k=["__startKeyHistory","__disabledAccount","__cached_requests","__request_signup_confirmation","__public_identifier","connection"];if(this.connection){for(let S of k)_[S]=this[S];u&&window.sessionStorage.setItem(`${e}#${t}`,JSON.stringify(_)),this.__class_properties_has_been_cached=true;}};return f instanceof Promise?f.then(()=>P()):P()};return u&&(window.addEventListener("beforeunload",()=>{this.closeRealtime(),y();}),window.addEventListener("visibilitychange",()=>{y();})),await f,await this.__authConnection,this.connection})(),this.__connection.then(f=>{((f?.group||0)<3||this.__network_logs)&&this.version();});}get user(){return this.__user&&Object.keys(this.__user).length?JSON.parse(JSON.stringify(this.__user)):null}set user(e){}get onLogin(){return this._onLoginListeners}set onLogin(e){typeof e=="function"&&this._onLoginListeners.push(e);}get onUserUpdate(){return this._userProfileListeners}set onUserUpdate(e){typeof e=="function"&&this._userProfileListeners.push(e);}_runOnUserUpdateListeners(e){for(let t of this._userProfileListeners)typeof t=="function"&&t(e);}_runOnLoginListeners(e){for(let t of this._onLoginListeners)typeof t=="function"&&t(e);}get onBatchProcess(){return this._onBatchProcessListeners}set onBatchProcess(e){typeof e=="function"&&this._onBatchProcessListeners.push(e);}_alert(e){$()&&typeof window.alert=="function"&&window.alert(e);}async getConnectionInfo(){let e=await this.__connection,t=e?.user_agent||($()&&typeof window.navigator?.userAgent=="string"?window.navigator.userAgent:`skapi-node/${globalThis?.process?.versions?.node||"unknown"}`);return {user_ip:e.ip,user_agent:t,user_location:e.locale,service_name:e.service_name,version:this.__version}}async _updateConnection(){try{this.connection=await R.bind(this)("service",{service:this.service,owner:this.owner},{bypassAwaitConnection:!0,method:"get"});}catch(e){throw this.log("connection fail",e),this._alert("Service is not available: "+(e.message||e.toString())),this.connection=null,e}return this.connection}async version(){if(await this.__connection,$()){let t=`Built with:
217
+ Watch the video here: ${e.video}`}var _=class{constructor(e,t,i,r){this.__version="1.5.2-beta.0";this.session=null;this.connection=null;this.__my_unique_ids={};this.userPool=null;this.__socket=null;this.__mediaStream=null;this.host="skapi";this.hostDomain="skapi.com";this.target_cdn="d3e9syvbtso631";this.customApiDomain="skapi.dev";this.requestBatchSize=30;this.__disabledAccount=null;this.__cached_requests={};this.__startKeyHistory={};this.__request_signup_confirmation=null;this.__private_access_key={};this.__class_properties_has_been_cached=false;this.__user=null;this._userProfileListeners=[];this._onLoginListeners=[];this._onBatchProcessListeners=[];this.validate={userId(e){try{return g.UserId(e),!0}catch{return false}},url(e){try{return g.Url(e),!0}catch{return false}},phoneNumber(e){try{return g.PhoneNumber(e),!0}catch{return false}},birthdate(e){try{return g.Birthdate(e),!0}catch{return false}},email(e){try{return g.Email(e),!0}catch{return false}},params(e,t,i){return g.Params(e,t,i)}};this.util={MD5:V,generateRandom:oe,toBase62:Xe,fromBase62:j,decodeServiceId:Ue,formatServiceId:Ze,extractFormData:N,terminatePendingRequests:Tt,request:(e,t,i)=>E.bind(this)(e,t,i,{ignoreService:true})};this.__network_logs=false;this.__endpoint_version="v1";this.__public_identifier="";this.bearerToken="";this.registerTicket=rt.bind(this);this.unregisterTicket=it.bind(this);if(!e||typeof e!="string")throw this._alert("Service ID is required."),new a("Service ID is required.",{code:"INVALID_PARAMETER"});let s=e.split("-").length;if(s===2||s===7)try{let f=Ue(e);i&&typeof i=="object"&&(r=i),t&&typeof t=="object"&&(i=t),t=f.owner,e=f.service;}catch{throw this._alert("Service ID is invalid."),new a("Service ID is invalid.",{code:"INVALID_PARAMETER"})}if(!t||typeof t!="string")throw this._alert("Owner ID is invalid."),new a("Owner ID is invalid.",{code:"INVALID_PARAMETER"});if(e.toLowerCase()==="service_id")throw this._alert('Replace "service_id" with your actual Service ID.'),new a("Service ID is required.",{code:"INVALID_PARAMETER"});if(t!==this.host)try{g.UserId(t,'"owner"');}catch{throw this._alert("Owner ID is invalid."),new a("Owner ID is invalid.",{code:"INVALID_PARAMETER"})}this.service=e,this.owner=t;let l=true;if(i&&(typeof i.autoLogin=="boolean"&&(l=i.autoLogin),typeof i.requestBatchSize=="number")){if(i.requestBatchSize<1)throw new a('"requestBatchSize" must be greater than 0.',{code:"INVALID_PARAMETER"});this.requestBatchSize=i.requestBatchSize;}i?.eventListener&&typeof i.eventListener=="object"&&(i.eventListener?.onLogin&&typeof i.eventListener.onLogin=="function"&&(this.onLogin=i.eventListener.onLogin),i.eventListener?.onUserUpdate&&typeof i.eventListener.onUserUpdate=="function"&&(this.onUserUpdate=i.eventListener.onUserUpdate),i.eventListener?.onBatchProcess&&typeof i.eventListener.onBatchProcess=="function"&&(this.onBatchProcess=i.eventListener.onBatchProcess)),this.target_cdn=r?.target_cdn||this.target_cdn,this.hostDomain=r?.hostDomain||this.hostDomain,this.customApiDomain=r?.customApiDomain||this.customApiDomain,this.__network_logs=!!r?.network_logs;let d=`https://${this.target_cdn}.cloudfront.net`,h=e.substring(0,4);this.admin_endpoint=fetch(`${d}/${h}/admin-${this.__endpoint_version}.json`).then(f=>f.blob()).then(f=>new Promise((R,P)=>{let b=new FileReader;b.onloadend=()=>R(b.result),b.onerror=P,b.readAsDataURL(f);})).then(f=>{try{return typeof f=="string"?JSON.parse(atob(f.split(",")[1])):null}catch{throw new a("Service does not exist. Create your service from skapi.com",{code:"NOT_EXISTS"})}}),this.record_endpoint=fetch(`${d}/${h}/record-${this.__endpoint_version}.json`).then(f=>f.blob()).then(f=>new Promise((R,P)=>{let b=new FileReader;b.onloadend=()=>R(b.result),b.onerror=P,b.readAsDataURL(f);})).then(f=>{try{return typeof f=="string"?JSON.parse(atob(f.split(",")[1])):null}catch{throw new a("Service does not exist. Create your service from skapi.com",{code:"NOT_EXISTS"})}});let u=$();if(u&&!window.sessionStorage)throw this._alert("This browser is not supported."),new Error("This browser is not supported.");let p=u?JSON.parse(window.sessionStorage.getItem(`${e}#${t}`)||"null"):null;if(this.log("constructor:restore",p),p?.connection){for(let f in p)this[f]=p[f];p.__public_identifier||(this.__public_identifier=`${this.service}:${this.owner}:${oe(16)}`);}this.__authConnection=(async()=>{let f=await this.admin_endpoint,R={UserPoolId:f.userpool_id,ClientId:f.userpool_client};De()&&(R.Storage=window.localStorage),this.userPool=new CognitoUserPool(R);try{this.user||await F.bind(this)().getSession({skipUserUpdateEventTrigger:!0}),this.user&&(!p?.connection&&!l?G.bind(this)():(this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user)));}catch{}})();let A=u?window.sessionStorage.getItem(`${this.service}:uniqueids`):null;if(A)try{this.__my_unique_ids=JSON.parse(A);}catch{this.__my_unique_ids={};}this.__connection=(async()=>{let f=null;await this.record_endpoint,p?.connection||(f=this._updateConnection());let R=()=>{if(this.__class_properties_has_been_cached)return;let P=()=>{let b={},x=["__startKeyHistory","__disabledAccount","__cached_requests","__request_signup_confirmation","__public_identifier","connection"];if(this.connection){for(let k of x)b[k]=this[k];u&&window.sessionStorage.setItem(`${e}#${t}`,JSON.stringify(b)),this.__class_properties_has_been_cached=true;}};return f instanceof Promise?f.then(()=>P()):P()};return u&&(window.addEventListener("beforeunload",()=>{this.closeRealtime(),R();}),window.addEventListener("visibilitychange",()=>{R();})),await f,await this.__authConnection,this.connection})(),this.__connection.then(f=>{((f?.group||0)<3||this.__network_logs)&&this.version();});}get user(){return this.__user&&Object.keys(this.__user).length?JSON.parse(JSON.stringify(this.__user)):null}set user(e){}get onLogin(){return this._onLoginListeners}set onLogin(e){typeof e=="function"&&this._onLoginListeners.push(e);}get onUserUpdate(){return this._userProfileListeners}set onUserUpdate(e){typeof e=="function"&&this._userProfileListeners.push(e);}_runOnUserUpdateListeners(e){for(let t of this._userProfileListeners)typeof t=="function"&&t(e);}_runOnLoginListeners(e){for(let t of this._onLoginListeners)typeof t=="function"&&t(e);}get onBatchProcess(){return this._onBatchProcessListeners}set onBatchProcess(e){typeof e=="function"&&this._onBatchProcessListeners.push(e);}_alert(e){$()&&typeof window.alert=="function"&&window.alert(e);}async getConnectionInfo(){let e=await this.__connection,t=e?.user_agent||($()&&typeof window.navigator?.userAgent=="string"?window.navigator.userAgent:`skapi-node/${globalThis?.process?.versions?.node||"unknown"}`);return {user_ip:e.ip,user_agent:t,user_location:e.locale,service_name:e.service_name,version:this.__version}}async _updateConnection(){try{this.connection=await E.bind(this)("service",{service:this.service,owner:this.owner},{bypassAwaitConnection:!0,method:"get"});}catch(e){throw this.log("connection fail",e),this._alert("Service is not available: "+(e.message||e.toString())),this.connection=null,e}return this.connection}async version(){if(await this.__connection,$()){let t=`Built with:
218
218
  %c\r
219
219
  $$\\ $$\\ \r
220
220
  $$ | \\__|\r
@@ -229,6 +229,6 @@ $$$$$$$ |$$ | \\$$\\\\$$$$$$$ |$$$$$$$ |$$ |\r
229
229
  \\__| \r
230
230
  Version: ${this.__version}
231
231
 
232
- Full Documentation: https://docs.skapi.com/skapi.md`;console.log(t,"font-family: monospace; color:blue;"),this.connection.group===1&&console.log("%cSKAPI: THE SERVICE IS IN TRIAL MODE.","font-family: monospace; color:red;");}return this.__version}log(e,t){if(this.__network_logs){if(typeof t=="object")try{t=JSON.parse(JSON.stringify(t));}catch{t=String(t);}else typeof t=="string"&&t.length>100&&(t=t.substring(0,100)+"...");console.log(`%c${e}:`,"color: blue;",t);}}getFeed(e,t){return an.bind(this)(e,t)}closeRTC(e){return Q.bind(this)(e)}connectRTC(e,t){return Jt.bind(this)(e,t)}connectRealtime(e){return ke.bind(this)(e)}spellcast(e){return vn.bind(this)(e)}getspell(e){return Dn.bind(this)(e)}dopamine(e){return Un.bind(this)(e)}getUniqueId(e,t){return Vt.bind(this)(e,t)}resendInvitation(e){return Tn.bind(this)(e)}cancelInvitation(e){return In.bind(this)(e)}getInvitations(e,t){return An.bind(this)(e,t)}openIdLogin(e){return st.bind(this)(e)}loginWithToken(e){return ot.bind(this)(e)}clientSecretRequest(e){return nn.bind(this)(e)}consumeTicket(e){return Ye.bind(this)(e)}getConsumedTickets(e,t){return tt.bind(this)(e,t)}getTickets(e,t){return et.bind(this)(e,t)}closeRealtime(){return Zt.bind(this)()}getRealtimeUsers(e,t){return en.bind(this)(e,t)}sendInquiry(e){return rn.bind(this)(e)}blockAccount(e){return _n.bind(this)(e)}unblockAccount(e){return bn.bind(this)(e)}deleteAccount(e){return yn.bind(this)(e)}inviteUser(e,t){return wn.bind(this)(e,t)}createAccount(e){return En.bind(this)(e)}grantAccess(e){return Rn.bind(this)(e)}getRealtimeGroups(e,t){return tn.bind(this)(e,t)}postRealtime(e,t,i){return Yt.bind(this)(e,t,i)}joinRealtime(e){return Be.bind(this)(e)}getProfile(e){return it.bind(this)(e)}getFile(e,t){return Ie.bind(this)(e,t)}secureRequest(e,t){return sn.bind(this)(e,t)}getFormResponse(){return Pt.bind(this)()}getRecords(e,t){return Ut.bind(this)(e,t)}getTables(e,t){return Ot.bind(this)(e,t)}getIndexes(e,t){return Ft.bind(this)(e,t)}getTags(e,t){return Mt.bind(this)(e,t)}deleteRecords(e,t){return $t.bind(this)(e,t)}resendSignupConfirmation(){return at.bind(this)()}recoverAccount(e=false){return ct.bind(this)(e)}getUsers(e,t){return bt.bind(this)(e,t)}disableAccount(){return ut.bind(this)()}lastVerifiedEmail(e){return yt.bind(this)(e)}unsubscribeNewsletter(e){return pn.bind(this)(e)}subscribeNotification(e,t){return Pn.bind(this)({endpoint:e,keys:t})}unsubscribeNotification(e,t){return Sn.bind(this)({endpoint:e,keys:t})}vapidPublicKey(){return kn.bind(this)()}pushNotification(e,t){return xn.bind(this)(e,t)}getNewsletters(e,t){return mn.bind(this)(e,t)}getNewsletterSubscription(e,t){return fn.bind(this)(e,t)}requestUsernameChange(e){return wt.bind(this)(e)}grantPrivateRecordAccess(e){return qt.bind(this)(e)}removePrivateRecordAccess(e){return jt.bind(this)(e)}listPrivateRecordAccess(e){return Bt.bind(this)(e)}requestPrivateRecordAccessKey(e){return Kt.bind(this)(e)}deleteFiles(e){return vt.bind(this)(e)}uploadFiles(e,t){return we.bind(this)(e,t)}mock(e,t){return on.bind(this)(e,t)}login(e){return Ne.bind(this)(e)}logout(e){return ce.bind(this)(e)}signup(e,t){return lt.bind(this)(e,t)}resetPassword(e){return dt.bind(this)(e)}verifyEmail(e){return ht.bind(this)(e)}verifyPhoneNumber(e){return ft.bind(this)(e)}forgotPassword(e){return pt.bind(this)(e)}changePassword(e){return mt.bind(this)(e)}updateProfile(e){return _t.bind(this)(e)}postRecord(e,t,i){return Lt.bind(this)(e,t,i)}getSubscriptions(e,t){return cn.bind(this)(e,t)}subscribe(e){return ln.bind(this)(e)}unsubscribe(e){return un.bind(this)(e)}blockSubscriber(e){return dn.bind(this)(e)}unblockSubscriber(e){return gn.bind(this)(e)}subscribeNewsletter(e){return hn.bind(this)(e)}bulkPostRecords(e){return Ct.bind(this)(e)}};w([E()],b.prototype,"getFeed"),w([E()],b.prototype,"closeRTC"),w([E()],b.prototype,"connectRTC"),w([E()],b.prototype,"spellcast"),w([E()],b.prototype,"getspell"),w([E()],b.prototype,"dopamine"),w([E()],b.prototype,"getUniqueId"),w([E()],b.prototype,"resendInvitation"),w([E()],b.prototype,"cancelInvitation"),w([E()],b.prototype,"getInvitations"),w([E()],b.prototype,"openIdLogin"),w([E()],b.prototype,"loginWithToken"),w([E()],b.prototype,"clientSecretRequest"),w([E()],b.prototype,"consumeTicket"),w([E()],b.prototype,"getConsumedTickets"),w([E()],b.prototype,"getTickets"),w([E()],b.prototype,"getRealtimeUsers"),w([E()],b.prototype,"sendInquiry"),w([E()],b.prototype,"blockAccount"),w([E()],b.prototype,"unblockAccount"),w([E()],b.prototype,"deleteAccount"),w([E()],b.prototype,"inviteUser"),w([E()],b.prototype,"createAccount"),w([E()],b.prototype,"grantAccess"),w([E()],b.prototype,"getRealtimeGroups"),w([E()],b.prototype,"postRealtime"),w([E()],b.prototype,"joinRealtime"),w([E()],b.prototype,"getProfile"),w([E()],b.prototype,"getFile"),w([E()],b.prototype,"secureRequest"),w([E()],b.prototype,"getFormResponse"),w([E()],b.prototype,"getRecords"),w([E()],b.prototype,"getTables"),w([E()],b.prototype,"getIndexes"),w([E()],b.prototype,"getTags"),w([E()],b.prototype,"deleteRecords"),w([E()],b.prototype,"resendSignupConfirmation"),w([E()],b.prototype,"recoverAccount"),w([E()],b.prototype,"getUsers"),w([E()],b.prototype,"disableAccount"),w([E()],b.prototype,"lastVerifiedEmail"),w([E()],b.prototype,"unsubscribeNewsletter"),w([E()],b.prototype,"subscribeNotification"),w([E()],b.prototype,"unsubscribeNotification"),w([E()],b.prototype,"vapidPublicKey"),w([E()],b.prototype,"pushNotification"),w([E()],b.prototype,"getNewsletters"),w([E()],b.prototype,"getNewsletterSubscription"),w([E()],b.prototype,"requestUsernameChange"),w([E()],b.prototype,"grantPrivateRecordAccess"),w([E()],b.prototype,"removePrivateRecordAccess"),w([E()],b.prototype,"listPrivateRecordAccess"),w([E()],b.prototype,"requestPrivateRecordAccessKey"),w([E()],b.prototype,"deleteFiles"),w([E()],b.prototype,"uploadFiles"),w([E()],b.prototype,"mock"),w([E({preventMultipleCalls:true})],b.prototype,"login"),w([E()],b.prototype,"logout"),w([E({preventMultipleCalls:true})],b.prototype,"signup"),w([E({preventMultipleCalls:true})],b.prototype,"resetPassword"),w([E({preventMultipleCalls:true})],b.prototype,"verifyEmail"),w([E({preventMultipleCalls:true})],b.prototype,"verifyPhoneNumber"),w([E({preventMultipleCalls:true})],b.prototype,"forgotPassword"),w([E({preventMultipleCalls:true})],b.prototype,"changePassword"),w([E({preventMultipleCalls:true})],b.prototype,"updateProfile"),w([E()],b.prototype,"postRecord"),w([E()],b.prototype,"getSubscriptions"),w([E()],b.prototype,"subscribe"),w([E()],b.prototype,"unsubscribe"),w([E()],b.prototype,"blockSubscriber"),w([E()],b.prototype,"unblockSubscriber"),w([E()],b.prototype,"subscribeNewsletter");var Ur={};
233
- export{b as Skapi,a as SkapiError,Ur as Types};//# sourceMappingURL=skapi.mjs.map
232
+ Full Documentation: https://docs.skapi.com/skapi.md`;console.log(t,"font-family: monospace; color:blue;"),this.connection.group===1&&console.log("%cSKAPI: THE SERVICE IS IN TRIAL MODE.","font-family: monospace; color:red;");}return this.__version}log(e,t){if(this.__network_logs){if(t!==null&&typeof t=="object")try{$()?t=JSON.parse(JSON.stringify(t)):t=JSON.stringify(t,null,2);}catch{t=String(t);}else typeof t=="string"&&t.length>100&&(t=t.substring(0,100)+"...");console.log(`%c${e}:`,"color: blue;",t);}}getFeed(e,t){return cn.bind(this)(e,t)}closeRTC(e){return K.bind(this)(e)}connectRTC(e,t){return zt.bind(this)(e,t)}connectRealtime(e){return ke.bind(this)(e)}spellcast(e){return Dn.bind(this)(e)}getspell(e){return Un.bind(this)(e)}dopamine(e){return Nn.bind(this)(e)}getUniqueId(e,t){return $t.bind(this)(e,t)}resendInvitation(e){return Pn.bind(this)(e)}cancelInvitation(e){return Tn.bind(this)(e)}getInvitations(e,t){return In.bind(this)(e,t)}openIdLogin(e){return ot.bind(this)(e)}loginWithToken(e){return at.bind(this)(e)}clientSecretRequest(e){return rn.bind(this)(e)}consumeTicket(e){return et.bind(this)(e)}getConsumedTickets(e,t){return nt.bind(this)(e,t)}getTickets(e,t){return tt.bind(this)(e,t)}closeRealtime(){return Yt.bind(this)()}getRealtimeUsers(e,t){return tn.bind(this)(e,t)}sendInquiry(e){return sn.bind(this)(e)}blockAccount(e){return _n.bind(this)(e)}unblockAccount(e){return yn.bind(this)(e)}deleteAccount(e){return wn.bind(this)(e)}inviteUser(e,t){return En.bind(this)(e,t)}createAccount(e){return Rn.bind(this)(e)}grantAccess(e){return An.bind(this)(e)}getRealtimeGroups(e,t){return nn.bind(this)(e,t)}postRealtime(e,t,i){return en.bind(this)(e,t,i)}joinRealtime(e){return Ke.bind(this)(e)}getProfile(e){return st.bind(this)(e)}getFile(e,t){return Ie.bind(this)(e,t)}secureRequest(e,t){return on.bind(this)(e,t)}getFormResponse(){return St.bind(this)()}getRecords(e,t){return Nt.bind(this)(e,t)}getTables(e,t){return Ft.bind(this)(e,t)}getIndexes(e,t){return Mt.bind(this)(e,t)}getTags(e,t){return Vt.bind(this)(e,t)}deleteRecords(e,t){return qt.bind(this)(e,t)}resendSignupConfirmation(){return ct.bind(this)()}recoverAccount(e=false){return lt.bind(this)(e)}getUsers(e,t){return yt.bind(this)(e,t)}disableAccount(){return dt.bind(this)()}lastVerifiedEmail(e){return wt.bind(this)(e)}unsubscribeNewsletter(e){return mn.bind(this)(e)}subscribeNotification(e,t){return Sn.bind(this)({endpoint:e,keys:t})}unsubscribeNotification(e,t){return kn.bind(this)({endpoint:e,keys:t})}vapidPublicKey(){return xn.bind(this)()}pushNotification(e,t){return vn.bind(this)(e,t)}getNewsletters(e,t){return bn.bind(this)(e,t)}getNewsletterSubscription(e,t){return hn.bind(this)(e,t)}requestUsernameChange(e){return Et.bind(this)(e)}grantPrivateRecordAccess(e){return jt.bind(this)(e)}removePrivateRecordAccess(e){return Bt.bind(this)(e)}listPrivateRecordAccess(e){return Kt.bind(this)(e)}requestPrivateRecordAccessKey(e){return Qt.bind(this)(e)}deleteFiles(e){return Dt.bind(this)(e)}uploadFiles(e,t){return we.bind(this)(e,t)}mock(e,t){return an.bind(this)(e,t)}login(e){return Ce.bind(this)(e)}logout(e){return ce.bind(this)(e)}signup(e,t){return ut.bind(this)(e,t)}resetPassword(e){return gt.bind(this)(e)}verifyEmail(e){return pt.bind(this)(e)}verifyPhoneNumber(e){return ht.bind(this)(e)}forgotPassword(e){return mt.bind(this)(e)}changePassword(e){return bt.bind(this)(e)}updateProfile(e){return _t.bind(this)(e)}postRecord(e,t,i){return Ot.bind(this)(e,t,i)}getSubscriptions(e,t){return ln.bind(this)(e,t)}subscribe(e){return un.bind(this)(e)}unsubscribe(e){return dn.bind(this)(e)}blockSubscriber(e){return gn.bind(this)(e)}unblockSubscriber(e){return fn.bind(this)(e)}subscribeNewsletter(e){return pn.bind(this)(e)}bulkPostRecords(e){return Lt.bind(this)(e)}};y([w()],_.prototype,"getFeed"),y([w()],_.prototype,"closeRTC"),y([w()],_.prototype,"connectRTC"),y([w()],_.prototype,"spellcast"),y([w()],_.prototype,"getspell"),y([w()],_.prototype,"dopamine"),y([w()],_.prototype,"getUniqueId"),y([w()],_.prototype,"resendInvitation"),y([w()],_.prototype,"cancelInvitation"),y([w()],_.prototype,"getInvitations"),y([w()],_.prototype,"openIdLogin"),y([w()],_.prototype,"loginWithToken"),y([w()],_.prototype,"clientSecretRequest"),y([w()],_.prototype,"consumeTicket"),y([w()],_.prototype,"getConsumedTickets"),y([w()],_.prototype,"getTickets"),y([w()],_.prototype,"getRealtimeUsers"),y([w()],_.prototype,"sendInquiry"),y([w()],_.prototype,"blockAccount"),y([w()],_.prototype,"unblockAccount"),y([w()],_.prototype,"deleteAccount"),y([w()],_.prototype,"inviteUser"),y([w()],_.prototype,"createAccount"),y([w()],_.prototype,"grantAccess"),y([w()],_.prototype,"getRealtimeGroups"),y([w()],_.prototype,"postRealtime"),y([w()],_.prototype,"joinRealtime"),y([w()],_.prototype,"getProfile"),y([w()],_.prototype,"getFile"),y([w()],_.prototype,"secureRequest"),y([w()],_.prototype,"getFormResponse"),y([w()],_.prototype,"getRecords"),y([w()],_.prototype,"getTables"),y([w()],_.prototype,"getIndexes"),y([w()],_.prototype,"getTags"),y([w()],_.prototype,"deleteRecords"),y([w()],_.prototype,"resendSignupConfirmation"),y([w()],_.prototype,"recoverAccount"),y([w()],_.prototype,"getUsers"),y([w()],_.prototype,"disableAccount"),y([w()],_.prototype,"lastVerifiedEmail"),y([w()],_.prototype,"unsubscribeNewsletter"),y([w()],_.prototype,"subscribeNotification"),y([w()],_.prototype,"unsubscribeNotification"),y([w()],_.prototype,"vapidPublicKey"),y([w()],_.prototype,"pushNotification"),y([w()],_.prototype,"getNewsletters"),y([w()],_.prototype,"getNewsletterSubscription"),y([w()],_.prototype,"requestUsernameChange"),y([w()],_.prototype,"grantPrivateRecordAccess"),y([w()],_.prototype,"removePrivateRecordAccess"),y([w()],_.prototype,"listPrivateRecordAccess"),y([w()],_.prototype,"requestPrivateRecordAccessKey"),y([w()],_.prototype,"deleteFiles"),y([w()],_.prototype,"uploadFiles"),y([w()],_.prototype,"mock"),y([w({preventMultipleCalls:true})],_.prototype,"login"),y([w()],_.prototype,"logout"),y([w({preventMultipleCalls:true})],_.prototype,"signup"),y([w({preventMultipleCalls:true})],_.prototype,"resetPassword"),y([w({preventMultipleCalls:true})],_.prototype,"verifyEmail"),y([w({preventMultipleCalls:true})],_.prototype,"verifyPhoneNumber"),y([w({preventMultipleCalls:true})],_.prototype,"forgotPassword"),y([w({preventMultipleCalls:true})],_.prototype,"changePassword"),y([w({preventMultipleCalls:true})],_.prototype,"updateProfile"),y([w()],_.prototype,"postRecord"),y([w()],_.prototype,"getSubscriptions"),y([w()],_.prototype,"subscribe"),y([w()],_.prototype,"unsubscribe"),y([w()],_.prototype,"blockSubscriber"),y([w()],_.prototype,"unblockSubscriber"),y([w()],_.prototype,"subscribeNewsletter");var Cr={};
233
+ export{_ as Skapi,a as SkapiError,Cr as Types};//# sourceMappingURL=skapi.mjs.map
234
234
  //# sourceMappingURL=skapi.mjs.map