skapi-js 1.7.3-beta.1 → 1.7.7

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 lr from'cocochex';import an from'qpass';/**
1
+ import {CognitoUserPool,AuthenticationDetails,CognitoUserSession,CognitoRefreshToken,CognitoAccessToken,CognitoIdToken,CognitoUser,CognitoUserAttribute}from'amazon-cognito-identity-js';import fr from'cocochex';import ln 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 Qn=Object.defineProperty;var Kn=Object.getOwnPropertyDescriptor;var re=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var R=(t,e,n,r)=>{for(var s=Kn(e,n),i=t.length-1,o;i>=0;i--)(o=t[i])&&(s=(o(e,n,s))||s);return s&&Qn(e,n,s),s};var J=typeof globalThis<"u"?globalThis:void 0,me=J?.window;function Hn(t){if(Buffer)return Buffer.from(t).toString("base64");let e="",n=new Uint8Array(t),r=32768;for(let s=0;s<n.length;s+=r){let i=n.subarray(s,s+r);e+=String.fromCharCode.apply(null,Array.from(i));}if(typeof btoa=="function")return btoa(e);throw new Error("No base64 encoder available in this environment.")}if(me)me.global=me,me.global._runningInNodeJS=false;else if(J&&(J.global=J,typeof J.window>"u")){class t{constructor(){this.result=null;this.error=null;this.onload=null;this.onloadend=null;this.onerror=null;}readAsDataURL(r){r.arrayBuffer().then(s=>{let i=Hn(s),o=r.type||"application/octet-stream";this.result=`data:${o};base64,${i}`,this.onload&&this.onload({target:this}),this.onloadend&&this.onloadend({target:this});}).catch(s=>{this.error=s,this.onerror&&this.onerror({target:this});});}readAsArrayBuffer(r){r.arrayBuffer().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});});}readAsText(r,s="utf-8"){r.text().then(i=>{this.result=i,this.onload&&this.onload({target:this}),this.onloadend&&this.onloadend({target:this});}).catch(i=>{this.error=i,this.onerror&&this.onerror({target:this});});}}J.FileReader=t;class e{constructor(){this.status=0;this.statusText="";this.readyState=0;this.responseText="";this.response=null;this.responseType="";this.responseURL="";this.timeout=0;this.withCredentials=false;this.onload=null;this.onerror=null;this.onabort=null;this.ontimeout=null;this.onprogress=null;this.onreadystatechange=null;this.upload={onprogress:null};this._method="GET";this._url="";this._headers={};this._aborted=false;}open(r,s){this._method=r,this._url=s,this.readyState=1;}setRequestHeader(r,s){this._headers[r]=s;}getResponseHeader(r){return null}abort(){this._aborted=true,this.onabort&&this.onabort({});}send(r){if(this._aborted)return;let s={method:this._method,headers:this._headers};r&&this._method!=="GET"&&this._method!=="HEAD"&&(s.body=r),fetch(this._url,s).then(async i=>{if(!this._aborted){if(this.status=i.status,this.statusText=i.statusText,this.responseURL=i.url,this.readyState=4,this.responseType==="blob")this.response=await i.blob();else if(this.responseType==="json")try{this.response=await i.json();}catch{this.response=null;}else this.responseType==="arraybuffer"?this.response=await i.arrayBuffer():(this.responseText=await i.text(),this.response=this.responseText);this.onload&&this.onload({});}}).catch(i=>{this._aborted||this.onerror&&this.onerror(i);});}}J.XMLHttpRequest=e,J.window={_runningInNodeJS:true,alert:n=>console.error("[Alert]",n),sessionStorage:{getItem:n=>null,setItem:(n,r)=>{},removeItem:n=>{}},localStorage:{getItem:n=>{let r=re("fs"),s=re("path");try{let i=s.resolve(process.cwd(),"states","localStorage",`${n}.skapi`);return r.existsSync(i)?r.readFileSync(i,"utf8"):null}catch{return null}},setItem:(n,r)=>{let s=re("fs"),i=re("path");try{let o=i.resolve(process.cwd(),"states","localStorage");s.existsSync(o)||s.mkdirSync(o,{recursive:!0});let a=i.resolve(o,`${n}.skapi`);s.writeFileSync(a,r,"utf8");}catch{}},removeItem:n=>{let r=re("fs"),s=re("path");try{let i=s.resolve(process.cwd(),"states","localStorage",`${n}.skapi`);r.existsSync(i)&&r.unlinkSync(i);}catch{}}},location:{href:"",origin:"",hostname:"",protocol:"",replace:n=>{}},navigator:{userAgent:`nodejs/${J?.process?.versions?.node||"unknown"}`,mediaDevices:{getUserMedia:async n=>{throw new Error("getUserMedia is not supported in Node.js environment.")}}},addEventListener:()=>{},removeEventListener:()=>{}};}var c=class extends Error{constructor(e,n){if(Array.isArray(e)&&e.length<=2){let r=e[1];if(e.length>2)for(let s=2;s<e.length&&typeof e[s]=="string";s++)r+=e[s];super((r||"Something went wrong.").trim()),this.name=n?.name||"SKAPI",this.code=n?.code||e[0]||"ERROR",n?.cause&&(this.cause=n.cause);}else super((e?.message||(typeof e=="string"?e:"Something went wrong.")).trim()),typeof e=="string"?(this.name=n?.name||"SKAPI",this.code=n?.code||"ERROR",n?.cause&&(this.cause=n.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=n?.name||"SKAPI",this.code=n?.code||"ERROR",this.cause=e?.cause);}};var G="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Ue=BigInt(G.length),Wn=2*1024*1024,zn=["aud","cognito:username","event_id","exp","iat","iss","jti","origin_jti","secret_key","token_use"],ze={auth_time:"log",sub:"user_id"},Jn=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f","g","h","i","j","k","l"],Ye=["us31","us72","ap51","ap22","ap41","eu71","ap21","us32","us71","af51","ap31","ap43","ap23","ap42","ca01","eu01","eu72","eu51","eu73","eu11","me51","sa31"],Je=typeof TextEncoder<"u"?new TextEncoder:null;function Gn(){if(typeof globalThis<"u")return globalThis.Buffer}function Xn(t){if(Je)return Je.encode(t);let e=unescape(encodeURIComponent(t)),n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r);return n}function Zn(t){if(t instanceof Uint8Array)return t;if(typeof t=="string")return Xn(t);if(typeof ArrayBuffer<"u"&&t instanceof ArrayBuffer)return new Uint8Array(t);if(typeof ArrayBuffer<"u"&&ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);if(Array.isArray(t))return Uint8Array.from(t);let e=Gn();if(e)return new Uint8Array(e.from(t));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 n=m.sb(e),r=1732584193,s=-271733879,i=-1732584194,o=271733878,a,l,u,f;for(let d=0;d<n.length;d+=16)a=r,l=s,u=i,f=o,r=m.ff(r,s,i,o,n[d],7,-680876936),o=m.ff(o,r,s,i,n[d+1],12,-389564586),i=m.ff(i,o,r,s,n[d+2],17,606105819),s=m.ff(s,i,o,r,n[d+3],22,-1044525330),r=m.ff(r,s,i,o,n[d+4],7,-176418897),o=m.ff(o,r,s,i,n[d+5],12,1200080426),i=m.ff(i,o,r,s,n[d+6],17,-1473231341),s=m.ff(s,i,o,r,n[d+7],22,-45705983),r=m.ff(r,s,i,o,n[d+8],7,1770035416),o=m.ff(o,r,s,i,n[d+9],12,-1958414417),i=m.ff(i,o,r,s,n[d+10],17,-42063),s=m.ff(s,i,o,r,n[d+11],22,-1990404162),r=m.ff(r,s,i,o,n[d+12],7,1804603682),o=m.ff(o,r,s,i,n[d+13],12,-40341101),i=m.ff(i,o,r,s,n[d+14],17,-1502002290),s=m.ff(s,i,o,r,n[d+15],22,1236535329),r=m.gg(r,s,i,o,n[d+1],5,-165796510),o=m.gg(o,r,s,i,n[d+6],9,-1069501632),i=m.gg(i,o,r,s,n[d+11],14,643717713),s=m.gg(s,i,o,r,n[d],20,-373897302),r=m.gg(r,s,i,o,n[d+5],5,-701558691),o=m.gg(o,r,s,i,n[d+10],9,38016083),i=m.gg(i,o,r,s,n[d+15],14,-660478335),s=m.gg(s,i,o,r,n[d+4],20,-405537848),r=m.gg(r,s,i,o,n[d+9],5,568446438),o=m.gg(o,r,s,i,n[d+14],9,-1019803690),i=m.gg(i,o,r,s,n[d+3],14,-187363961),s=m.gg(s,i,o,r,n[d+8],20,1163531501),r=m.gg(r,s,i,o,n[d+13],5,-1444681467),o=m.gg(o,r,s,i,n[d+2],9,-51403784),i=m.gg(i,o,r,s,n[d+7],14,1735328473),s=m.gg(s,i,o,r,n[d+12],20,-1926607734),r=m.hh(r,s,i,o,n[d+5],4,-378558),o=m.hh(o,r,s,i,n[d+8],11,-2022574463),i=m.hh(i,o,r,s,n[d+11],16,1839030562),s=m.hh(s,i,o,r,n[d+14],23,-35309556),r=m.hh(r,s,i,o,n[d+1],4,-1530992060),o=m.hh(o,r,s,i,n[d+4],11,1272893353),i=m.hh(i,o,r,s,n[d+7],16,-155497632),s=m.hh(s,i,o,r,n[d+10],23,-1094730640),r=m.hh(r,s,i,o,n[d+13],4,681279174),o=m.hh(o,r,s,i,n[d],11,-358537222),i=m.hh(i,o,r,s,n[d+3],16,-722521979),s=m.hh(s,i,o,r,n[d+6],23,76029189),r=m.hh(r,s,i,o,n[d+9],4,-640364487),o=m.hh(o,r,s,i,n[d+12],11,-421815835),i=m.hh(i,o,r,s,n[d+15],16,530742520),s=m.hh(s,i,o,r,n[d+2],23,-995338651),r=m.ii(r,s,i,o,n[d],6,-198630844),o=m.ii(o,r,s,i,n[d+7],10,1126891415),i=m.ii(i,o,r,s,n[d+14],15,-1416354905),s=m.ii(s,i,o,r,n[d+5],21,-57434055),r=m.ii(r,s,i,o,n[d+12],6,1700485571),o=m.ii(o,r,s,i,n[d+3],10,-1894986606),i=m.ii(i,o,r,s,n[d+10],15,-1051523),s=m.ii(s,i,o,r,n[d+1],21,-2054922799),r=m.ii(r,s,i,o,n[d+8],6,1873313359),o=m.ii(o,r,s,i,n[d+15],10,-30611744),i=m.ii(i,o,r,s,n[d+6],15,-1560198380),s=m.ii(s,i,o,r,n[d+13],21,1309151649),r=m.ii(r,s,i,o,n[d+4],6,-145523070),o=m.ii(o,r,s,i,n[d+11],10,-1120210379),i=m.ii(i,o,r,s,n[d+2],15,718787259),s=m.ii(s,i,o,r,n[d+9],21,-343485551),r=m.ad(r,a),s=m.ad(s,l),i=m.ad(i,u),o=m.ad(o,f);return m.rh(r)+m.rh(s)+m.rh(i)+m.rh(o)}static rh(e){let n="";for(let r=0;r<=3;r++)n+=m.alphabet.charAt(e>>r*8+4&15)+m.alphabet.charAt(e>>r*8&15);return n}static ad(e,n){let r=(e&65535)+(n&65535);return (e>>16)+(n>>16)+(r>>16)<<16|r&65535}static rl(e,n){return e<<n|e>>>32-n}static cm(e,n,r,s,i,o){return m.ad(m.rl(m.ad(m.ad(n,e),m.ad(s,o)),i),r)}static ff(e,n,r,s,i,o,a){return m.cm(n&r|~n&s,e,n,i,o,a)}static gg(e,n,r,s,i,o,a){return m.cm(n&s|r&~s,e,n,i,o,a)}static hh(e,n,r,s,i,o,a){return m.cm(n^r^s,e,n,i,o,a)}static ii(e,n,r,s,i,o,a){return m.cm(r^(n|~s),e,n,i,o,a)}static sb(e){let n,r=(e.length+8>>6)+1,s=new Array(r*16);for(n=0;n<r*16;n++)s[n]=0;for(n=0;n<e.length;n++)s[n>>2]|=e.charCodeAt(n)<<n%4*8;return s[n>>2]|=128<<n%4*8,s[r*16-2]=e.length*8,s}};m.alphabet="0123456789abcdef";var M=m;function et(t){if(t===0)return G[0];let e="";for(;t>0;)e=G[t%62]+e,t=Math.floor(t/62);return e}function j(t){return t.split("").reverse().reduce((e,n,r)=>e+G.indexOf(n)*62**r,0)}function ne(t=6){let e="",n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",r=n.length,s=0;for(;s<t;)e+=n.charAt(Math.floor(Math.random()*r)),s+=1;return e}function Ne(){return typeof window>"u"||!!window?._runningInNodeJS}function V(){return !Ne()&&typeof document<"u"&&typeof document.createElement=="function"}function _e(t){let e;try{e=JSON.stringify(t);}catch{throw new c("Invalid data type.",{code:"INVALID_REQUEST"})}if(new Blob([e]).size>Wn)throw new c("Data should not exceed 2MB",{code:"INVALID_REQUEST"})}function Ge(t){return t===""||t==="on"||t==="true"}function Xe(t){return t==="false"}function Ze(t,e,n){e.name&&n(t,e.name,e.value);}var be=V(),Yn=typeof SubmitEvent<"u",er=typeof HTMLFormElement<"u";function N(t,e,n){let r={},s=[];function i(l,u,f){if(e?.ignoreEmpty&&f==="")return;if(e?.nullIfEmpty&&f===""&&(f=null),typeof n=="function"){let _=n(u,f);_!==void 0&&(f=_);}let d=u.split("[").map(_=>{let h=_.replace("]",""),w=Number(h);return !isNaN(w)&&!h.includes(".")?h=w:(h[0]==='"'&&h[h.length-1]==='"'||h[0]==="'"&&h[h.length-1]==="'")&&(h=h.replace(/"/g,"").replace(/'/g,"")),h}),p=l;if(typeof d[0]=="number")throw new c("Form key cannot start with an array index.",{code:"INVALID_REQUEST"});for(let _=0;_<d.length;_++){let h=d[_];_<d.length-1?(p[h]===void 0&&(typeof d[_+1]=="number"?p[h]=[]:p[h]={}),p=p[h]):p[h]===void 0?p[h]=f:Array.isArray(p[h])?p[h].push(f):p[h]=[p[h],f];}}function o(l,u,f){if(f instanceof File)l.push({name:u,file:f});else if(f instanceof FileList&&f&&f.length>0)for(let d=0;d<=f.length-1;d++){let p=f.item(d);p&&l.push({name:u,file:p});}}let a=l=>{l.name&&(l.type==="number"?l.value&&i(r,l.name,Number(l.value)):l.type==="checkbox"||l.type==="radio"?l.checked?l.type==="checkbox"&&l.value===""||Ge(l.value)?i(r,l.name,true):Xe(l.value)?i(r,l.name,false):l.value&&i(r,l.name,l.value):l.type==="checkbox"&&(Ge(l.value)?i(r,l.name,false):Xe(l.value)&&i(r,l.name,true)):l.type==="file"?l.files&&l.files.length>0&&o(s,l.name,l.files):i(r,l.name,l.value));};if(be&&(t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement))return a(t),_e(r),{data:r,files:s};if(be&&t instanceof FormData){for(let l of t.entries()){let u=l[0],f=l[1];if(f instanceof File||f instanceof FileList)o(s,u,f);else if(f instanceof Blob){let d=f;if(d.type==="application/json")try{let p=JSON.parse(d.text());i(r,u,p);}catch{i(r,u,d);}}else i(r,u,f);}return _e(r),{data:r,files:s}}if(be&&Yn&&t instanceof SubmitEvent&&(t=t.target),be&&er&&t instanceof HTMLFormElement){let l=t.querySelectorAll("input"),u=t.querySelectorAll("select"),f=t.querySelectorAll("textarea");for(let d=0;d<u.length;d++)Ze(r,u[d],i);for(let d=0;d<f.length;d++)Ze(r,f[d],i);for(let d=0;d<l.length;d++)a(l[d]);return _e(r),{data:r,files:s}}return _e(t),{data:t,files:s}}function le(t){let e={};for(let n in t){let r=t[n];if(!zn.includes(n))if(ze[n])e[ze[n]]=r;else if(n.includes("custom:"))e[n.replace("custom:","")]=r;else if(n==="address"){let s=r;if(s&&typeof s=="object"&&Object.keys(s).length){if(s?.formatted)try{e[n]=JSON.parse(s.formatted);}catch{e[n]=s.formatted;}}else e[n]=s;}else e[n]=r;}for(let n of ["address_public","birthdate_public","email_public","gender_public","phone_number_public","access_group"])n.includes("_public")?e.hasOwnProperty(n.split("_")[0])?e[n]=e.hasOwnProperty(n)?!!Number(e[n]):false:delete e[n]:e[n]=e.hasOwnProperty(n)?Number(e[n]):0;for(let n of ["email","phone_number"])e.hasOwnProperty(n)?e[n+"_verified"]=e[n+"_verified"]===true:delete e[n+"_verified"];return e}function Ce(t){if(t=cr(t),t.split("-").length===7){let e=t.split("-"),n,r;try{n=Ye[j(e[1][0])],r=e.slice(2).join("-");}catch{throw new Error("INVALID_PARAMETER: Service ID is invalid.")}if(!n)throw new Error("INVALID_PARAMETER: Service ID is invalid.");return {service:n+e[0]+e[1].slice(1),owner:r}}return {service:t,owner:""}}function tt(t,e){let n=Ye.indexOf(t.slice(0,4)),r=Jn[n],i=`${t.slice(4,-4)}-${r}${t.slice(-4)}-${e}`;return ar(i)}function tr(t){let e=0n;for(let n of t){let r=G.indexOf(n);if(r<0)throw new Error(`INVALID_PARAMETER: Invalid base62 character: ${n}`);e=e*Ue+BigInt(r);}return e}function nr(t,e=1){if(t<0n)throw new Error("INVALID_PARAMETER: Negative values are not supported.");if(t===0n)return "0".repeat(Math.max(1,e));let n="",r=t;for(;r>0n;){let s=Number(r%Ue);n=G[s]+n,r/=Ue;}return n.length<e&&(n="0".repeat(e-n.length)+n),n}function rr(t){if(t===0n)return Uint8Array.from([0]);let e=[],n=t;for(;n>0n;)e.push(Number(n&0xffn)),n>>=8n;return e.reverse(),Uint8Array.from(e)}function ir(t){let e=0n;for(let n of t)e=(e<<8n)+BigInt(n);return e}function sr(t){let e=String(t).replace(/-/g,"");if(!/^[0-9a-fA-F]{32}$/.test(e))throw new Error("INVALID_PARAMETER: Invalid UUID format.");let n=new Uint8Array(16);for(let r=0;r<16;r++)n[r]=parseInt(e.slice(r*2,r*2+2),16);return n}function or(t){let e=Array.from(Zn(t),n=>n.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 ar(t){let e=String(t);if(e.split("-").length===2)return e;let n=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(!n)throw new Error("INVALID_PARAMETER: Input must match <base62>-<base62>-<uuid>.");let[,r,s,i]=n;if(r.length<2)throw new Error("INVALID_PARAMETER: The first part must contain at least 2 characters.");if(s.length>=G.length)throw new Error("INVALID_PARAMETER: The middle section is too long to encode.");let o=r.slice(0,2),a=r.slice(2),l=s+o,u=G[s.length]+a+l,f=sr(i),d=nr(ir(f));return `${u}-${d}`}function cr(t){let e=String(t);if(e.split("-").length!==2)return e;let n=e.split("-");if(n.length!==2||!n[0]||!n[1])throw new Error("INVALID_PARAMETER: Corrupt compressed token.");let[r,s]=n,i=G.indexOf(r[0]);if(i<0)throw new Error("INVALID_PARAMETER: Corrupt compressed token.");let o=r.slice(1),a=i+2;if(o.length<a)throw new Error("INVALID_PARAMETER: Corrupt compressed token.");let l=o.slice(0,o.length-a),u=o.slice(o.length-a),f=u.slice(i),d=u.slice(0,i),p=f+l;if(!/^[0-9A-Za-z]+$/.test(p)||!/^[0-9A-Za-z]+$/.test(d))throw new Error("INVALID_PARAMETER: Corrupt compressed token.");let _=tr(s),h=rr(_);if(h.length>16)throw new Error("INVALID_PARAMETER: Corrupt compressed token.");let w=new Uint8Array(16);w.set(h,16-h.length);let P=or(w);return `${p}-${d}-${P}`}function ur(t,e="User ID"){let n=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;if(t){if(typeof t!="string")throw new c(`${e} should be type: string.`,{code:"INVALID_PARAMETER"});if(!t.match(n))throw new c(`${e} is invalid.`,{code:"INVALID_PARAMETER"})}else throw new c(`${e} is empty.`,{code:"INVALID_PARAMETER"});return t}function dr(t){if(t&&(typeof t!="string"||t.charAt(0)!=="+"||isNaN(Number(t.substring(1)))))throw new c('"phone_number" is invalid. The format should be "+00123456789". Type: string.',{code:"INVALID_PARAMETER"});return t||""}function gr(t){if(t){if(typeof t!="string")throw new c('"birthdate" is invalid. The format should be "yyyy-mm-dd". Type: string.',{code:"INVALID_PARAMETER"});{let e=new RegExp(/([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))/);if(t.length!==10||t.split("-").length!==3||!e.test(t))throw new c('"birthdate" is invalid. The format should be "yyyy-mm-dd". Type: string.',{code:"INVALID_PARAMETER"})}}return t||""}function fr(t){if(t){if(typeof t!="string")throw new c('"password" should be type: string.',{code:"INVALID_PARAMETER"});if(t.length<6)throw new c('"password" should be at least 6 characters.',{code:"INVALID_PARAMETER"});if(t.length>60)throw new c('"password" can be up to 60 characters max.',{code:"INVALID_PARAMETER"})}else throw new c('"password" is required.',{code:"INVALID_PARAMETER"});return t}function hr(t,e="email"){if(t){if(typeof t!="string")throw new c(`"${e}"should be type: string.`,{code:"INVALID_PARAMETER"});if(t.length<5)throw new c(`"${e}" should be at least 5 characters.`,{code:"INVALID_PARAMETER"});if(/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/.test(t)&&(t=t.trim(),t.split("@")[1].split(".").length>=2))return t.toLowerCase()}else throw new c(`"${e}" is required.`,{code:"INVALID_PARAMETER"});throw new c(`"${t}" is an invalid email.`,{code:"INVALID_PARAMETER"})}function pr(t){let e=typeof window<"u",n=(()=>{let s=e&&window.location.origin||null;return s&&s.slice(-1)==="/"&&(s=s.slice(0,-1)),s})(),r=s=>{if(typeof s=="string"){if(s==="*")return "*";{let i=s.trim();if(i[0]==="/"&&n){if(n.slice(0,5)==="file:")throw new c(`"${s}" is an invalid url. Relative URL does not work on local file system. Use full URL string.`,{code:"INVALID_PARAMETER"});i=n+i;}else if(i[0]==="."&&n){if(n.slice(0,5)==="file:")throw new c(`"${s}" is an invalid url. Relative URL does not work on local file system. Use full URL string.`,{code:"INVALID_PARAMETER"});let a=e?window.location.href.split("?")[0]:"";a.slice(-1)!=="/"&&(a+="/"),i=a+i.slice(1);}let o;try{o=new URL(i);}catch{throw new c(`"${s}" is an invalid url.`,{code:"INVALID_PARAMETER"})}if(o.protocol)return o.href}}throw new c(`"${s}" is an invalid url.`,{code:"INVALID_PARAMETER"})};return Array.isArray(t)?t.map(s=>r(s)):r(t)}function mr(t,e,n=[],r){let s=N(t,r),i=s.data;e.service="string",e.owner="string";let o={};for(let a in e)if(i&&typeof i=="object"&&!Array.isArray(i)&&i.hasOwnProperty(a))if(typeof i[a]=="function")o[a]=i[a];else try{o[a]=JSON.parse(JSON.stringify(i[a]));}catch{o[a]=i[a];}r?.precall&&r.precall({data:o,files:s?.files||[]});try{return lr(o,e,n)}catch(a){throw new c(a.message,{code:"INVALID_PARAMETER"})}}var g={UserId:ur,PhoneNumber:dr,Birthdate:gr,Password:fr,Email:hr,Url:pr,Params:mr};var C=null;function Le(t){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"},n={};for(let r in t)if(r==="tkid"){let s=t[r].split("#");if(s.length===1){n.ticket_id=s[0];continue}n.ticket_id=s[1],n.consume_id=s[2],n.user_id=s[3];let i=s[2].slice(-4);if(n.is_test=i===":CHK",!t.stmp){let o=s[2].slice(0,-4);/^[0-9]+$/.test(o)?n.timestamp=parseInt(o,10):n.timestamp=j(s[2].slice(0,-4));}}else e[r]?n[e[r]]=t[r]:n[r]=t[r];return n}async function rt(t){if(!t.ticket_id)throw new c("Ticket ID is required.",{code:"INVALID_PARAMETER"});if(!t.method)throw new c('Method is required. Should be either "GET" or "POST"',{code:"INVALID_PARAMETER"});let e=t.ticket_id;await this.__connection;let n=await E.bind(this)(`https://${this.service.slice(0,4)}.${this.customApiDomain}/auth/consume/${this.service}/${this.owner}/${e}`,t?.data||{},{method:t.method,auth:!!t?.auth});return Le(n)}async function it(t,e){await this.__connection;let n=await E.bind(this)("ticket",Object.assign({exec:"list"},t||{}),{auth:true,fetchOptions:e});return n.list=n.list.map(Le),n}async function st(t,e){await this.__connection;let n=await E.bind(this)("ticket",Object.assign({exec:"consumed"},t||{}),{auth:true,fetchOptions:e});return n.list=n.list.map(Le),n}async function ot(t){return E.bind(this)("register-ticket",Object.assign({exec:"reg"},t),{auth:true})}async function at(t){return E.bind(this)("register-ticket",Object.assign({exec:"unreg"},t),{auth:true})}async function se(){if(await this.__connection,this.session){let t=Math.floor(Date.now()/1e3),n=this.session.getIdToken().getExpiration();if(n<t){this.log("request:requesting new token",null);try{await q.bind(this)().getSession({refreshToken:!0}),this.log("request:received new tokens",{exp:this.session?.idToken?.payload?.exp,currentTime:t,expiresIn:n-t,token:this.session?.accessToken?.jwtToken,refreshToken:this.session?.refreshToken?.token});}catch(r){throw this.log("request:new token error",r),new c("User login is required.",{code:"INVALID_REQUEST"})}}else this.log("request:tokens",{exp:this.session.idToken.payload.exp,currentTime:t,expiresIn:n-t,token:this.session.accessToken.jwtToken,refreshToken:this.session.refreshToken.token});return this.session?.idToken?.jwtToken}else throw this.log("request:no session",null),X.bind(this)(),new c("User login is required.",{code:"INVALID_REQUEST"})}function nt(t,e){return new Promise((n,r)=>{e.refreshSession(t.getRefreshToken(),(s,i)=>{this.log("getSession:refreshSessionCallback",{refreshErr:s,refreshedSession:i}),s?(X.bind(this)(),r(s)):i.isValid()?n(i):(X.bind(this)(),r(new c("Invalid session.",{code:"INVALID_REQUEST"})));});})}function q(){if(!this.userPool)throw new c("User pool is missing",{code:"INVALID_REQUEST"});let t=()=>{let i=C.getSignInUserSession().getIdToken().payload||null,o=le(i);return this.log("normalized user attribute",o),this.__user=o,o},e=async i=>new Promise((o,a)=>{this.log("getSession:option",i);let{refreshToken:l=false,skipUserUpdateEventTrigger:u=false}=i||{};if(l&&u&&(u=false),C=this.userPool.getCurrentUser(),!C){this.log("getSession:cognitoUser",C),X.bind(this)(),a(null);return}let f=d=>{let p=d.getIdToken().payload;if(this.log("getSession:respond:sessionAttribute",p),p["custom:service"]!==this.service)throw this.log("getSession:respond","invalid service, signing out"),X.bind(this)(),new c("Invalid session.",{code:"INVALID_REQUEST"});return this.session=d,t(),u||this._runOnUserUpdateListeners(this.user),this.session};C.getSession((d,p)=>{if(this.log("getSession:getSessionCallback",{err:d,session:p}),!p){X.bind(this)(),a(new c("Current session does not exist.",{code:"INVALID_REQUEST"}));return}if(d){nt.bind(this)(p,C).then(b=>o(f(b))).catch(a);return}let _=Math.floor(Date.now()/1e3),h=p.getIdToken(),w=h.getExpiration(),P=w<_;if(this.log("getSession:currentTime",_),this.log("getSession:idTokenExp",w),this.log("getSession:isExpired",P),this.log("getSession:existingBearerToken",this.bearerToken),this.bearerToken=h.getJwtToken(),P||l||!p.isValid())nt.bind(this)(p,C).then(b=>o(f(b))).catch(a);else try{o(f(p));}catch(b){a(b);}});}),n=(i,o)=>{let a=o||i.includes(this.service+"-")?i:this.service+"-"+M.hash(i);return {cognitoUser:new CognitoUser({Username:a,Pool:this.userPool}),cognitoUsername:a}};return {getSession:e,authenticateUser:(i,o,a=false,l=false)=>new Promise((u,f)=>{this.__request_signup_confirmation=null,this.__disabledAccount=null;let d=n(i,a),p=d.cognitoUsername,_=new AuthenticationDetails({Username:p,Password:o});d.cognitoUser.authenticateUser(_,{newPasswordRequired:(h,w)=>{this.__disabledAccount=null,this.__request_signup_confirmation=p,h["custom:signup_ticket"]==="PASS"||h["custom:signup_ticket"]==="MEMBER"||h["custom:signup_ticket"]==="OIDPASS"?d.cognitoUser.completeNewPasswordChallenge(o,{},{onSuccess:P=>{C=d.cognitoUser,e().then(b=>u(this.user));},onFailure:P=>{f(new c(P.message||"Failed to authenticate user.",{code:P.code}));}}):f(new c("User's signup confirmation is required.",{code:"SIGNUP_CONFIRMATION_NEEDED"}));},onSuccess:h=>e({skipUserUpdateEventTrigger:true}).then(w=>{this.__disabledAccount=null,this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user),u(this.user);}),onFailure:h=>{let w=[],{parsed:P,code:b}=we(h),S=typeof h?.message=="string"?h.message:"";if(b==="NotAuthorizedException"?S.includes("User is disabled.")?(this.__disabledAccount=p,w=["This account is disabled.","USER_IS_DISABLED"]):l?w=["The account already exists.","ACCOUNT_EXISTS"]:w=["Incorrect username or password.","INCORRECT_USERNAME_OR_PASSWORD"]:b==="UserNotFoundException"?w=["Incorrect username or password.","INCORRECT_USERNAME_OR_PASSWORD"]:b==="UserNotConfirmedException"?(this.__request_signup_confirmation=p,w=["User's signup confirmation is required.","SIGNUP_CONFIRMATION_NEEDED"]):(b==="TooManyRequestsException"||b==="LimitExceededException")&&(w=["Too many attempts. Please try again later.","REQUEST_EXCEED"]),P.code==="SIGNUP_CONFIRMATION_NEEDED"&&(this.__request_signup_confirmation=p),w.length){let v=w[1],T=w[0];f(new c(T,{code:v,cause:h}));}else f(P);}});}),createCognitoUser:n,signup:(i,o,a)=>new Promise((l,u)=>{this.userPool.signUp(i,o,a,null,(f,d)=>{if(f){let{parsed:p,code:_}=we(f),h=[];_==="UsernameExistsException"?h=["The account already exists.","EXISTS"]:_==="InvalidPasswordException"?h=["Invalid password. Password must be at least 6 characters.","INVALID_PARAMETER"]:_==="InvalidParameterException"?h=[p.message||"Invalid parameter.","INVALID_PARAMETER"]:_==="TooManyRequestsException"||_==="LimitExceededException"?h=["Too many attempts. Please try again later.","REQUEST_EXCEED"]:_==="CodeDeliveryFailureException"?h=["Failed to deliver verification code.","CODE_DELIVERY_FAILURE"]:_==="UserLambdaValidationException"&&(h=[p.message||"Signup validation failed.","INVALID_REQUEST"]),h.length?u(new c(h[0],{code:h[1],cause:f})):u(p);return}l(d);});})}}function we(t){let e=typeof t?.code=="string"&&t.code.trim()?t.code.trim():"ERROR",r=((typeof t?.message=="string"?t.message:typeof t=="string"?t:"An error occurred.")||"An error occurred.").trim();r||(r="An error occurred.");let s=r.match(/#([A-Za-z0-9_]+)\s*:\s*([\s\S]+)/),i=s?.[1]?.trim()||e,o=s?.[2]?.trim()||r;return {parsed:new c(o,{code:i,cause:t}),code:e}}async function ct(t){await this.__authConnection;let e=t?.refreshToken||false;if(!e)return this.user;try{return await q.bind(this)().getSession(Object.assign({skipUserUpdateEventTrigger:!e,refreshToken:e},t)),this.user}catch{return null}}async function lt(t){await this.__connection,t=g.Params(t,{token:"string",id:"string",merge:o=>{if(o===void 0)return false;if(typeof o=="string")return [o];if(Array.isArray(o)){for(let a of o)if(typeof a!="string")throw new c('"merge" array items should be type: <string>.',{code:"INVALID_PARAMETER"})}if(typeof o!="boolean"&&!Array.isArray(o))throw new c('"merge" should be type: <boolean | string[]>.',{code:"INVALID_PARAMETER"});return o},template:o=>{if(typeof o!="object"||o===null)throw new c('"template" should be type: <object>.',{code:"INVALID_PARAMETER"});if(o.welcome!==void 0&&(typeof o.welcome!="string"||!o.welcome))throw new c('"template.welcome" should be a non-empty <string> (template message_id).',{code:"INVALID_PARAMETER"});return o}});let e={token:t.token,id:t.id,merge:t.merge};t.template?.welcome&&(e.template_welcome=t.template.welcome);let n=await E.bind(this)("openid-logger",e),r=n.logger.split("#"),s=this.service+"-"+r[0],i=r[1];return {userProfile:await q.bind(this)().authenticateUser(s,i,true,true),openid:n.openid}}function Rr(t){let e=typeof globalThis<"u"?globalThis:void 0;if(e?.Buffer)return e.Buffer.from(t,"base64").toString("utf8");if(typeof atob=="function"){let n=atob(t),r=new Uint8Array(n.length);for(let s=0;s<n.length;s++)r[s]=n.charCodeAt(s);return typeof TextDecoder<"u"?new TextDecoder().decode(r):n}throw new Error("No base64 decoder available in this environment")}function Ar(t){let e=t.split(".");if(e.length!==3)throw new Error("Invalid JWT format");let r=e[1].replace(/-/g,"+").replace(/_/g,"/"),s=Rr(r);return JSON.parse(s)}async function ut(t){await this.__authConnection,this.log("loginWithToken:params",t),t=g.Params(t,{idToken:"string",accessToken:"string",refreshToken:"string"},["idToken"]);let e=Ar(t.idToken);if(this.log("loginWithToken:idTokenPayload",e),e["custom:service"]!==this.service)throw new c("Token does not belong to this service.",{code:"INVALID_REQUEST"});let n=Math.floor(Date.now()/1e3);if(e.exp&&e.exp<n)throw new c("Token has expired.",{code:"INVALID_REQUEST"});if(this.__user=le(e),this.session=null,t.accessToken&&t.refreshToken)try{if(this.session=new CognitoUserSession({IdToken:new CognitoIdToken({IdToken:t.idToken}),AccessToken:new CognitoAccessToken({AccessToken:t.accessToken}),RefreshToken:new CognitoRefreshToken({RefreshToken:t.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 r={Username:e["cognito:username"],Pool:this.userPool};this.log("loginWithToken:cognitoUserParams",r),C=new CognitoUser(r),C.setSignInUserSession(this.session),this.log("loginWithToken:cognitoUserRestored",{cognitoUserType:typeof C,cognitoUserKeys:Object.keys(C||{}),cognitoUser:C});}}catch(r){this.log("loginWithToken:err",r);try{this.log("loginWithToken:err:stringified",JSON.stringify(r));}catch{this.log("loginWithToken:err:stringifyFail",String(r));}try{let s=Object.keys(r||{}),i=Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(r||{}):[],o=Object.getOwnPropertyDescriptors?Object.getOwnPropertyDescriptors(r||{}):{};this.log("loginWithToken:createSessionError:allKeys",{keys:s,symbols:i,descriptors:o});}catch(s){this.log("loginWithToken:createSessionError:allKeysFail",String(s));}}return this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user),this.user}async function F(){return await this.__connection,this.__user?.service===this.service?this.__user?.owner===this.host:(await ue.bind(this)(),false)}async function X(t=false){let e=null;C&&(t?e=new Promise((r,s)=>{C.globalSignOut({onSuccess:i=>{this.log("globalSignOut:success",i),r(i);},onFailure:i=>{this.log("globalSignOut:error",i),s(i);}});}):C.signOut());let n={session:null,__startKeyHistory:{},__cached_requests:{},__user:null};e&&(e=await e);for(let r in n)this[r]=n[r];return this._runOnUserUpdateListeners(null),this._runOnLoginListeners(null),e}async function ue(t){await this.__connection;let{data:e}=N(t);return await X.bind(this)(e?.global),"SUCCESS: The user has been logged out."}async function dt(){if(!this.__request_signup_confirmation)throw new c("Least one login attempt is required.",{code:"INVALID_REQUEST"});return await E.bind(this)("confirm-signup",{username:this.__request_signup_confirmation})}async function gt(t=false){if(typeof t=="string")t=g.Url(t);else if(typeof t!="boolean")throw new c("Argument should be type: <boolean | string>.",{code:"INVALID_REQUEST"});if(!this.__disabledAccount)throw new c("Least one signin attempt of disabled account is required.",{code:"INVALID_REQUEST"});return await E.bind(this)("recover-account",{username:this.__disabledAccount,redirect:t}),"SUCCESS: Recovery e-mail has been sent."}async function Oe(t){let e=g.Params(t,{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 c('Least one of "username" or "email" is required.',{code:"INVALID_PARAMETER"});return await q.bind(this)().authenticateUser(e.username||e.email,e.password)}async function ft(t,e){await this.__authConnection;let n={username:"string",password:u=>g.Password(u),email:u=>g.Email(u),name:"string",address:u=>{if(!u)return "";if(typeof u=="string")return u;if(typeof u=="object")return JSON.stringify(u)},gender:"string",birthdate:u=>u?g.Birthdate(u):"",phone_number:u=>u?g.PhoneNumber(u):"",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:u=>u?g.Url(u):"",profile:u=>u?g.Url(u):"",family_name:"string",given_name:"string",middle_name:"string",nickname:"string",website:u=>u?g.Url(u):""},r=g.Params(t||{},n,["email","password"]);await ue.bind(this)(),e=g.Params(e||{},{email_subscription:u=>{if(typeof u!="boolean")throw new c('"option.email_subscription" should be type: <boolean>.',{code:"INVALID_PARAMETER"});if(!e?.signup_confirmation)throw new c('"option.signup_confirmation" is required for email subscription.',{code:"INVALID_PARAMETER"});return u},signup_confirmation:u=>{let f=u;if(typeof u=="string")f=g.Url(u);else if(typeof u=="boolean")f=u;else throw new c('"option.signup_confirmation" should be type: <string | boolean>.',{code:"INVALID_PARAMETER"});if(f&&!r.email)throw new c('"email" is required for signup confirmation.',{code:"INVALID_PARAMETER"});return f},login:u=>{if(typeof u=="boolean"){if(e.signup_confirmation&&u)throw new c('"login" is not allowed when "option.signup_confirmation" is true.',{code:"INVALID_PARAMETER"});return u}throw new c('"option.login" should be type: boolean.',{code:"INVALID_PARAMETER"})},template:u=>{if(typeof u!="object"||u===null)throw new c('"option.template" should be type: <object>.',{code:"INVALID_PARAMETER"});if(u.signup_confirmation!==void 0){if(typeof u.signup_confirmation!="string"||!u.signup_confirmation)throw new c('"option.template.signup_confirmation" should be a non-empty <string> (template message_id).',{code:"INVALID_PARAMETER"});if(!e?.signup_confirmation)throw new c('"option.signup_confirmation" is required when "option.template.signup_confirmation" is set.',{code:"INVALID_PARAMETER"})}if(u.welcome!==void 0&&(typeof u.welcome!="string"||!u.welcome))throw new c('"option.template.welcome" should be a non-empty <string> (template message_id).',{code:"INVALID_PARAMETER"});return u}});let s=e?.login||false;if(r.signup_confirmation=e?.signup_confirmation||false,r.email_subscription=e?.email_subscription||false,r.email_public&&!r.signup_confirmation)throw new c('"option.signup_confirmation" should be true if "email_public" is set to true.',{code:"INVALID_PARAMETER"});r.service=this.service,r.owner=this.owner;let i=q.bind(this)().createCognitoUser(r.username||r.email);for(let u of ["email_public","address_public","gender_public","birthdate_public","phone_number_public"])r[u]=r[u]?"1":"0";r.access_group&&(r.access_group=r.access_group.toString());let o=(await E.bind(this)("signupkey",{username:i.cognitoUsername,signup_confirmation:typeof r.signup_confirmation=="boolean"?JSON.stringify(r.signup_confirmation):r.signup_confirmation,email_subscription:r.email_subscription,template_confirmation:e?.template?.signup_confirmation||"",template_welcome:e?.template?.welcome||""})).split(":"),a=o.slice(1).join(":"),l=[new CognitoUserAttribute({Name:"custom:signup",Value:o[0]}),new CognitoUserAttribute({Name:"locale",Value:a.split("#")[1]}),new CognitoUserAttribute({Name:"custom:signup_ticket",Value:a})];for(let u in n){let f=["email_public","address_public","gender_public","birthdate_public","phone_number_public","misc","service","owner"];r[u]!==""&&(u==="username"||u==="password"||u==="access_group"||(f.includes(u)?l.push(new CognitoUserAttribute({Name:"custom:"+u,Value:r[u]})):l.push(new CognitoUserAttribute({Name:u,Value:r[u]}))));}return await q.bind(this)().signup(i.cognitoUsername,r.password,l),r.signup_confirmation?(C=i.cognitoUser,this.__request_signup_confirmation=i.cognitoUsername,"SUCCESS: The account has been created. User's signup confirmation is required."):s?Oe.bind(this)({email:r.username||r.email,password:r.password}):"SUCCESS: The account has been created."}async function ht(){await this.__connection;let t=await E.bind(this)("remove-account",{disable:this.__user.user_id},{auth:true});return await ue.bind(this)(),t}async function pt(t){await this.__connection;let e=g.Params(t,{email:s=>g.Email(s),code:["number","string"],new_password:s=>g.Password(s)},["email","code","new_password"]),n=e.code,r=e.new_password;return typeof n=="number"&&(n=n.toString()),new Promise(async(s,i)=>{q.bind(this)().createCognitoUser(e.email).cognitoUser.confirmPassword(n,r,{onSuccess:a=>{s("SUCCESS: New password has been set.");},onFailure:a=>{i(new c(a?.message||"Failed to reset password.",{code:a?.code||"ERROR",cause:a}));}});})}async function mt(t,e,n){await this.__connection;let r;if(!C)throw new c("The user has to be logged in.",{code:"INVALID_REQUEST"});if(t==="email"||t==="phone_number"){if(!this.__user.hasOwnProperty(t))throw new c(`No ${t==="email"?"e-mail":"phone number"} to verify`,{code:"INVALID_REQUEST"});if(this.__user?.[`${t}_verified`])return `SUCCESS: "${t}" is verified.`;r=(e?g.Params(e,{code:"string"}):{}).code||"";}else return;let s,i=n?.template?.verification;if(i!==void 0){if(typeof i!="string"||!i)throw new c('"template.verification" should be a non-empty <string> (template message_id).',{code:"INVALID_PARAMETER"});s={template_verification:i};}return new Promise((o,a)=>{let l={onSuccess:u=>{r?q.bind(this)().getSession({refreshToken:true}).then(()=>{this.__user&&(this.__user[t+"_verified"]=true),o(`SUCCESS: "${t}" is verified.`);}).catch(f=>{a(f);}):o("SUCCESS: Verification code has been sent.");},onFailure:u=>{a(new c(u.message||"Failed to request verification code.",{code:u?.code}));}};r?C?.verifyAttribute(t,r,l):(l.inputVerificationCode=null,C?.getAttributeVerificationCode(t,l,s));})}function _t(t,e){return mt.bind(this)("phone_number",t,e)}function bt(t,e){return mt.bind(this)("email",t,e)}async function yt(t,e){await this.__connection;let n=g.Params(t,{email:i=>g.Email(i)},["email"]),r,s=e?.template?.verification;if(s!==void 0){if(typeof s!="string"||!s)throw new c('"template.verification" should be a non-empty <string> (template message_id).',{code:"INVALID_PARAMETER"});r={template_verification:s};}return new Promise(async(i,o)=>{q.bind(this)().createCognitoUser(n.email).cognitoUser.forgotPassword({onSuccess:l=>{i("SUCCESS: Verification code has been sent.");},onFailure:l=>{let{parsed:u,code:f}=we(l),d={UserNotFoundException:"NOT_EXISTS",InvalidParameterException:"INVALID_PARAMETER",NotAuthorizedException:"INVALID_REQUEST",LimitExceededException:"REQUEST_EXCEED",TooManyRequestsException:"REQUEST_EXCEED",CodeDeliveryFailureException:"CODE_DELIVERY_FAILURE"}[f]||u.code||f||"ERROR";o(new c(u.message,{code:d,cause:l}));}},r);})}async function wt(t){if(await this.__connection,!this.session)throw new c("User login is required.",{code:"INVALID_REQUEST"});let e=g.Params(t,{current_password:"string",new_password:"string"});if(!e?.current_password)throw new c('"current_password" is required to change password.',{code:"INVALID_PARAMETER"});if(!e?.new_password)throw new c('"new_password" is required to change password.',{code:"INVALID_PARAMETER"});return g.Password(e.current_password),g.Password(e.new_password),new Promise((n,r)=>{C.changePassword(e.current_password,e.new_password,(s,i)=>{if(s){if(s?.code==="InvalidParameterException")r(new c("Invalid password parameter.",{code:"INVALID_PARAMETER"}));else if(s?.code==="NotAuthorizedException")r(new c("Incorrect password.",{code:"INVALID_REQUEST"}));else if(s?.code==="TooManyRequestsException"||s?.code==="LimitExceededException")r(new c("Too many attempts. Please try again later.",{code:"REQUEST_EXCEED"}));else {let{parsed:o}=we(s);r(o);}return}n("SUCCESS: Password has been changed.");});})}async function Et(t){if(await this.__connection,!this.session)throw new c("User login is required.",{code:"INVALID_REQUEST"});let e=g.Params(t||{},{user_id:s=>g.UserId(s),email:s=>g.Email(s),address:s=>{if(!s)return "";if(typeof s=="string")return s;if(typeof s=="object")return JSON.stringify(s)},name:"string",gender:"string",birthdate:s=>s?g.Birthdate(s):"",phone_number:s=>s?g.PhoneNumber(s):"",email_public:"boolean",phone_number_public:"boolean",address_public:"boolean",gender_public:"boolean",birthdate_public:"boolean",misc:"string",picture:s=>s?g.Url(s):"",profile:s=>s?g.Url(s):"",family_name:"string",given_name:"string",middle_name:"string",nickname:"string",website:s=>s?g.Url(s):""});if(e&&typeof e=="object"&&!Object.keys(e).length)return this.user;e.email&&(e.preferred_username=this.service+"-"+M.hash(e.email));let n=[["email_public","email_verified","User's e-mail should be verified to set"],["phone_number_public","phone_number_verified","User's phone number should be verified to set"]];if(this.__user){for(let s of n)if(e[s[0]]&&!this.__user[s[1]])throw new c(`${s[2]} "${s[0]}" to true.`,{code:"INVALID_REQUEST"})}let r=[];for(let s in e){if(e[s]===this.user[s]){r.push(s);continue}if(["email_public","phone_number_public","address_public","gender_public","birthdate_public","misc"].includes(s)){let o=e[s];typeof o=="boolean"&&(o=o?"1":"0"),e["custom:"+s]=o,r.push(s);}}for(let s of r)delete e[s];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 s=[];for(let i in e)s.push(new CognitoUserAttribute({Name:i,Value:e[i]}));return await new Promise((i,o)=>{C?.updateAttributes(s,(a,l)=>{a&&o([a?.code||a?.name,a?.message||"Failed to update user settings."]),i(l);});}),await q.bind(this)().getSession({refreshToken:true}),this.user}return this.user}async function Rt(t,e){t=N(t).data,t||(t={searchFor:"timestamp",condition:">",value:0},e||(e={}),e.ascending=false),await this.__connection;let n={user_id:s=>Array.isArray(s)?s.map(i=>g.UserId(i)):g.UserId(s),email:"string",phone_number:"string",locale:s=>{if(typeof s!="string"||typeof s=="string"&&s.length>5)throw new c('Value of "locale" should be a country code.',{code:"INVALID_PARAMETER"});return s},name:"string",address:"string",gender:"string",birthdate:s=>g.Birthdate(s),subscribers:"number",timestamp:"number",access_group:"number",approved:"string"},r=["searchFor","value"];if(t=g.Params(t,{searchFor:["user_id","name","email","phone_number","address","gender","birthdate","locale","subscribers","timestamp","access_group","approved"],condition:[">",">=","=","<","<=","gt","gte","eq","lt","lte",()=>"="],value:s=>{let i=n[t.searchFor];if(typeof i=="function")return i(s);if(typeof s!==i)throw new c(`Value does not match the type of "${t.searchFor}" index.`,{code:"INVALID_PARAMETER"});return s},range:s=>{let i=n[t.searchFor];if(typeof i=="function")return i(s);if(typeof s!==i)throw new c(`Range does not match the type of "${t.searchFor}" index.`,{code:"INVALID_PARAMETER"});return s}},r),t?.condition&&t?.condition!=="="&&t.hasOwnProperty("range"))throw new c("Conditions does not apply on range search.",{code:"INVALID_PARAMETER"});if(t.searchFor==="user_id"&&(t.condition!=="="||t.range))throw new c(`Conditions are not allowed on "${t.searchFor}"`,{code:"INVALID_PARAMETER"});if(typeof t?.value=="string"&&!t?.value)throw new c("Value should not be an empty string.",{code:"INVALID_PARAMETER"});if(typeof t?.searchFor=="string"&&!t?.searchFor)throw new c('"searchFor" should not be an empty string.',{code:"INVALID_PARAMETER"});return E.bind(this)("get-users",t,{auth:true,fetchOptions:e})}async function At(t){await this.__connection;let e=await E.bind(this)("last-verified-email",t,{auth:true});return e.includes("SUCCESS")?(await q.bind(this)().getSession({refreshToken:true}),this.user):e}async function It(t){return await this.__connection,t=g.Params(t,{username:g.Email,redirect:g.Url},["username"]),await E.bind(this)("request-username-change",t,{auth:true})}var oe=null,Pt=typeof SubmitEvent<"u",Tr=typeof HTMLFormElement<"u",ge=V(),Me=0;function St(t){if(!t)return null;let e=Number(t);if(Number.isFinite(e))return Math.max(0,e*1e3);let n=Date.parse(t);return Number.isNaN(n)?null:Math.max(0,n-Date.now())}function Fe(t,e){return e>0?t/e*100:0}var Tt=t=>{let{auth:e,type:n,endpoints:r}=t,s=r[0],i=r[1];if(Me++,n==="admin"){let o=Object.entries(s).filter(([a,l])=>a.includes(e?"_private":"_public")&&a!=="get_users_private"&&a!=="service_public"&&typeof l=="string").map(([,a])=>a);if(!o.length)throw new c("No available admin gateways.",{code:"INVALID_REQUEST"});return o[Me%o.length]}if(n==="record"){let o=Object.entries(i).filter(([a,l])=>a.includes(e?"record_private":"record_public")&&typeof l=="string").map(([,a])=>a);if(!o.length)throw new c("No available record gateways.",{code:"INVALID_REQUEST"});return o[Me%o.length]}throw new c("Invalid gateway type.",{code:"INVALID_REQUEST"})};async function Pr(t,e){let n=await Promise.all([this.admin_endpoint,this.record_endpoint]),r=n[0],s=n[1],i=t.split("?"),o=i.length>1?"?"+i[1]:"";switch(t=i[0],t){case "get-users":return r.get_users_private+t+o;case "service":return r.service_public+t+o;case "get-newsletters":case "get-public-newsletters":case "subscribe-newsletter":case "subscribe-public-newsletter":case "signupkey":case "admin-newsletter-request":case "admin-signup":case "confirm-signup":case "openid-logger":case "block-account":case "admin-edit-profile":case "remove-account":case "post-secure":case "recover-account":case "mock":case "grant-access":case "last-verified-email":case "ticket":case "register-ticket":case "get-newsletter-subscription":case "request-username-change":case "send-inquiry":case "register-newsletter-group":case "newsletter-group-endpoint":case "invitation-list":case "csr":case "csr-poll":case "csr-cancel":return Tt.bind(this)({auth:e,type:"admin",endpoints:n})+t+o;case "post-record":return (e?s.post_private:s.post_public)+t+o;case "get-records":return (e?s.get_private:s.get_public)+t+o;case "del-files":case "del-records":return s.del_private+t+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 "extract-file-text":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 Tt.bind(this)({auth:e,type:"record",endpoints:n})+t+o;default:return g.Url(t)+o}}var de={};function kt(){oe&&(oe.terminate(),oe=null);}async function E(t,e=null,n,r){this.log("request",{url:t,data:e,options:n,_etc:r||{}}),n=n||{};let{auth:s=false,method:i="post",bypassAwaitConnection:o=false}=n;i=i.toUpperCase();let a=null,l=e?.service||this.service,u=e?.owner||this.owner,f=null,d=await Pr.bind(this)(t,!!s);if(!o&&(a=await this.__connection,!a))throw new c("Invalid connection. The service could have been disabled, or has a restricted CORS.",{code:"INVALID_REQUEST"});let p=n?.tokenHeaders?.idToken===true;(s||p)&&(f=await se.bind(this)());let _={},{fetchMore:h=false,progress:w}=n?.fetchOptions||{};if(n?.fetchOptions&&Object.keys(n.fetchOptions).length){for(let k of ["limit","startKey","ascending"])if(n.fetchOptions.hasOwnProperty(k)){if(k==="startKey"&&n.fetchOptions[k]===null)continue;_[k]=n.fetchOptions[k];}_=g.Params(_,{limit:k=>{if(typeof k!="number")throw new c("Fetch limit should be a number.",{code:"INVALID_REQUEST"});if(k>1e3)throw new c("Fetch limit should be below 1000.",{code:"INVALID_REQUEST"});return k},startKey:k=>k,ascending:"boolean"});}let P=r?.ignoreService?{}:{service:l,owner:u};Object.assign(P,_),e=N(e).data,e?e&&typeof e=="object"&&(e=Object.assign(P,e)):e=P;let b=`${i}:${s?"auth":"public"}:${t}`,S=(()=>{if(e&&typeof e=="object"&&Object.keys(e).length&&!(ge&&e instanceof FormData)){let k=function(D){return typeof D=="object"&&D!==null?Object.keys(D).sort().reduce((U,L)=>(typeof D[L]=="object"&&D[L]!==null?U[L]=k(D[L]):U[L]=D[L],U),{}):D};return M.hash(b+"/"+JSON.stringify(k(e)))}return M.hash(b+"/"+l)})(),{requestKey:v,requestKeyWithStartKey:T}=Sr.bind(this)({params:e,url:t,fetchMore:h,hashedParams:S});if(!v||v&&typeof v=="object")return v;if(this.log("requestKey",T),typeof T=="string"&&de[T]instanceof Promise)return this.log("request:returning pending",T),de[T];let x={Accept:"*/*"};if(Object.prototype.hasOwnProperty.call(n,"contentType")&&n.contentType!==void 0){let k=n.contentType===null?"application/x-www-form-urlencoded":n.contentType;k&&(x["Content-Type"]=k);}else x["Content-Type"]="application/json";if(f&&(x.Authorization=f),n?.tokenHeaders){let k=(L,Bn)=>typeof L=="string"?L:L===true?Bn:null,D=k(n.tokenHeaders.accessToken,this.session?.accessToken?.jwtToken||null),U=k(n.tokenHeaders.idToken,this.bearerToken||this.session?.idToken?.jwtToken||f||null);D&&(x["X-Access-Token"]=D),U&&(x["X-Id-Token"]=U);}let De={public_identifier:this.__public_identifier,service:l,owner:u};x["Content-Meta"]=JSON.stringify(De);let $={headers:x};if(n?.responseType&&($.responseType=n.responseType),i==="GET"){if(e){let k=[];if(ge&&e instanceof FormData?k=Array.from(e.entries()).map(([D,U])=>{let L=typeof U=="string"?U:U.name;return encodeURIComponent(D)+"="+encodeURIComponent(L)}):k=Object.keys(e).map(D=>{let U=e[D];return typeof U!="string"&&(U=JSON.stringify(U)),encodeURIComponent(D)+"="+encodeURIComponent(U)}),k.length){let D=d.includes("?")?d.endsWith("?")||d.endsWith("&")?"":"&":"?";d+=D+k.join("&");}}$.body=null;}else if(ge&&e instanceof FormData)$.body=e;else if(x["Content-Type"]==="application/x-www-form-urlencoded"&&e&&typeof e=="object"){let k=new URLSearchParams;for(let D of Object.keys(e)){let U=e[D];k.append(D,typeof U=="string"?U:JSON.stringify(U));}$.body=k.toString();}else typeof e=="string"?$.body=e:$.body=e?JSON.stringify(e):null;if($.method=i,oe===null){let k={batchSize:this.requestBatchSize,breakWhenError:false,onProgress:D=>{this.onBatchProcess.forEach(U=>U(D));}};oe=new an(k);}return this.log("request-opt",$),new Promise((k,D)=>{oe.add([async()=>{let U=vt.bind(this)(d,$,w);de[T]=U;try{let L=kr.bind(this)({hashedParam:v,requestKeyWithStartKey:T,url:t,fetched:await U});return delete de[T],this.log("request:end",L),k(L),L}catch(L){throw delete de[T],this.log("request:err",L),D(L),L}}]);})}function Sr(t){let{params:e={},url:n,fetchMore:r=false,hashedParams:s}=t||{};if(e.startKey){if(!(typeof e.startKey=="object"&&Object.keys(e.startKey).length)&&e.startKey!=="start"&&e.startKey!=="end")throw new c(`"${e.startKey}" is invalid startKey key.`,{code:"INVALID_PARAMETER"});e.startKey==="start"&&(r=false,delete e.startKey);}if(!r){if(this.__cached_requests?.[n]?.[s]&&delete this.__cached_requests[n][s],this.__startKeyHistory?.[n]?.[s]){if(Array.isArray(this.__startKeyHistory[n][s])&&this.__startKeyHistory[n][s].length)for(let l of this.__startKeyHistory[n][s]){let u=s+M.hash(l);this.__cached_requests?.[n]&&this.__cached_requests?.[n]?.[u]&&delete this.__cached_requests[n][u];}delete this.__startKeyHistory[n][s];}return {requestKeyWithStartKey:s,requestKey:s}}if(!Array.isArray(this.__startKeyHistory?.[n]?.[s]))return {requestKeyWithStartKey:s,requestKey:s};let i=this.__startKeyHistory[n][s],o=i[i.length-1],a=s;if(o){if(o==="end")return {requestKey:{list:[],startKey:"end",endOfList:true,startKeyHistory:i},requestKeyWithStartKey:a};a+=M.hash(o),e.startKey=JSON.parse(o);}return this.__cached_requests?.[n]?.[a]?{requestKey:this.__cached_requests[n][a],requestKeyWithStartKey:a}:{requestKeyWithStartKey:a,requestKey:s}}function vt(t,e,n){return new Promise((r,s)=>{let i=new XMLHttpRequest;i.open(e.method||"GET",t);for(var o in e.headers||{})i.setRequestHeader(o,e.headers[o]);e.responseType&&(i.responseType=e.responseType),i.onload=()=>{if(i.status<400)if(e.responseType=="json"||e.responseType=="blob")r(i.response);else {let a=i.responseText;try{a=JSON.parse(a);}catch{}r(a);}else if(i.status===429){let a=i.getResponseHeader("Retry-After"),l=St(a);l!==null?setTimeout(()=>{vt(t,e,n).then(r,s);},l):s("Too many requests");}else {let a=i.status,l=["INVALID_CORS","INVALID_REQUEST","SERVICE_DISABLED","INVALID_PARAMETER","ERROR","EXISTS","NOT_EXISTS"],u=e.responseType=="blob"?i.response:i.responseText;try{u=JSON.parse(u);}catch{}if(typeof u=="string"){let f=u.split(":"),d=f.splice(0,1)[0].trim(),p=f.join(":").trim();s(new c(p||u,{code:l.includes(d)?d:"ERROR"}));}else if(typeof u=="object"&&u?.message){let f=u?.code||(a?a.toString():null)||"ERROR",d=u.message,p=u?.cause;typeof d=="string"&&(d=d.trim()),s(new c(d,{cause:p,code:f}));}else s(u);}},i.onerror=()=>s("Network error"),i.onabort=()=>s("Aborted"),i.ontimeout=()=>s("Timeout"),typeof n=="function"&&(i.onprogress=a=>{n({status:"download",progress:Fe(a.loaded,a.total),loaded:a.loaded,total:a.total,abort:()=>i.abort()});},i.upload&&(i.upload.onprogress=a=>{n({status:"upload",progress:Fe(a.loaded,a.total),loaded:a.loaded,total:a.total,abort:()=>i.abort()});})),i.send(e.body);})}function kr(t){let{hashedParam:e,requestKeyWithStartKey:n,url:r,fetched:s}=t;if(!s?.startKey)return s;this.__startKeyHistory.hasOwnProperty(r)||(this.__startKeyHistory[r]={}),this.__startKeyHistory[r].hasOwnProperty(e)||(this.__startKeyHistory[r][e]=[]);let i=s.startKey==="end"?"end":JSON.stringify(s.startKey);return this.__startKeyHistory[r][e].includes(i)||this.__startKeyHistory[r][e].push(i),this.__cached_requests?.[r]||(this.__cached_requests[r]={}),this.__cached_requests[r][n]=s,Object.assign({startKeyHistory:this.__startKeyHistory[r][e]},s)}async function Re(t,e){await this.__connection;let{record_id:n,service:r=this.service,progress:s}=e;if(!n)throw new c('"record_id" is required.',{code:"INVALID_PARAMETER"});if(Pt&&t instanceof SubmitEvent&&(t=t.target),Tr&&t instanceof HTMLFormElement&&(t=new FormData(t)),!ge||!(t instanceof FormData))throw new c('"fileList" should be a FormData or HTMLFormElement.',{code:"INVALID_PARAMETER"});let o={reserved_key:ne(),service:r,request:"post"};e?.record_id&&(o.id=e.record_id);let a,l=(_,h,w)=>new Promise((P,b)=>{a=new XMLHttpRequest,a.open("POST",_),a.onload=()=>{let S=a.responseText;try{S=JSON.parse(S);}catch{}if(a.status>=200&&a.status<300)P(S);else if(a.status===429){let v=a.getResponseHeader("Retry-After"),T=St(v);T!==null?setTimeout(()=>{l(_,h,w).then(P,b);},T):b("Too many requests");}else b(S);},a.onerror=()=>b("Network error"),a.onabort=()=>b("Aborted"),a.ontimeout=()=>b("Timeout"),a.upload&&typeof w=="function"&&(a.upload.onprogress=w),a.send(h);});function u(_){let h="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";if(_===0)return h[0];let w="";for(;_>0;)w=h[_%62]+w,_=Math.floor(_/62);return w}let f=[],d=[],p=[];for(let[_,h]of t.entries()){if(!(h instanceof File))continue;let w=Object.assign({key:_+"/"+h.name,sizeKey:u(h.size),contentType:h.type||null},o),{fields:P=null,url:b,cdn:S}=await E.bind(this)("get-signed-url",w,{auth:!!this.__user});p.push(S);let v=new FormData;for(let T in P)v.append(T,P[T]);v.append("file",h);try{await l(b,v,typeof s=="function"?T=>s({status:"upload",progress:Fe(T.loaded,T.total),currentFile:h,completed:f,failed:d,loaded:T.loaded,total:T.total,abort:()=>a.abort()}):null),f.push(h);}catch{d.push(h);}}return {completed:f,failed:d,bin_endpoints:p}}var Ee={};function A(t){let{preventMultipleCalls:e=false}=t||{};return function(n,r,s){let i=s.value;s.value=function(...o){let a=o[0],l=true,u=null,f="",d={},p=false;if(Pt&&a instanceof SubmitEvent){a.preventDefault();let b=window.location.href;u=a.target;let S=new URL(u.action);f=S.href;let v=f?f.match(/(?<=\{).*?(?=\})/g):"";if(v)for(let T of v){if(!T)continue;let x=u.querySelector(`[name="${T}"]`);if(x)if(x.type==="file")for(let H=0;H<=x.files.length-1;H++)x.files[H]&&(d[T]||(d[T]=[]),d[T].push(new Promise((De,$)=>{let k=new FileReader;k.onload=function(){De(k.result);},k.readAsDataURL(x.files[H]),k.onerror=$;})));else f=f.replace(`{${T}}`,x.value);}u.getAttribute("action")===null?l=false:p=S.href===b;}let _=async b=>{if(f)for(let S in d)d[S].length&&(f=f.replace(`{${S}}`,(await Promise.all(d[S])).join(",")));return u&&l&&(window.sessionStorage.setItem(`${this.service}:${M.hash(f)}`,JSON.stringify(b)),p?window.location.replace(f):window.location.href=f),b},h,w=b=>{throw b instanceof c?b.name=r+"()":b=b instanceof Error?b:new c(b,{name:r+"()"}),b},P=async()=>{try{if(h=i.bind(this)(...o),h instanceof Promise){let b=await h;return _(b)}return _(h)}catch(b){throw w(b)}};if(e){let b=`${r}:${this?.__public_identifier||""}:${this?.service||""}:${this?.owner||""}`;return Ee?.[b]||(Ee[b]=P().finally(()=>{delete Ee[b];})),Ee[b]}return P()};}}async function xt(){await this.__connection;let t=`${this.service}:${M.hash(window.location.href.split("?")[0])}`,e=window.sessionStorage.getItem(t);if(window.sessionStorage.removeItem(t),e!==null){try{e=JSON.parse(e);}catch{}return e}return null}var vr=128,xr=64,Dr=128,Ur=256,Nr="\u{10FFFF}",Cr=/[\u0000-\u001F\u007F]|\u{10FFFF}/u,Lr=/[\/!*#]/,Or={"/":"%2F","!":"%21","*":"%2A","#":"%23"},Mr={"%2F":"/","%21":"!","%2A":"*","%23":"#"};function Fr(t){return t.replace(/%/g,"%25").replace(/[\/!*#]/g,n=>Or[n]||n)}function B(t){return typeof t!="string"?t:t.replace(/%(2F|21|2A|23)/gi,n=>{let r=n.toUpperCase();return Mr[r]||n}).replace(/%25/gi,"%")}function Z(t,e,n={}){let{allowEmpty:r=false,maxLength:s,blockKeyDelimiters:i=false,disallowLeadingDollar:o=false,onlyAlphanumeric:a=false}=n;if(typeof t!="string")throw new c(`"${e}" should be type: <string>.`,{code:"INVALID_PARAMETER"});if(a&&/[^a-zA-Z0-9]/.test(t))throw new c(`"${e}" should only contain alphanumeric characters.`,{code:"INVALID_PARAMETER"});if(!r&&t.length===0)throw new c(`"${e}" is required.`,{code:"INVALID_PARAMETER"});if(s&&t.length>s)throw new c(`"${e}" should be <= ${s} characters.`,{code:"INVALID_PARAMETER"});if(Cr.test(t)||t.includes(Nr))throw new c(`"${e}" cannot include control characters or unsupported sentinel characters.`,{code:"INVALID_PARAMETER"});if(i&&Lr.test(t)&&(t=Fr(t)),o&&t.startsWith("$"))throw new c(`"${e}" cannot start with "$".`,{code:"INVALID_PARAMETER"});return t}function qe(t,e="table.name"){return Z(t,e,{allowEmpty:false,maxLength:vr,blockKeyDelimiters:true})}function Ve(t,e="tag"){return Z(t,e,{allowEmpty:false,maxLength:xr,blockKeyDelimiters:true})}function fe(t,e="index.name"){return Z(t,e,{allowEmpty:false,maxLength:Dr,blockKeyDelimiters:true,disallowLeadingDollar:true})}function Dt(t,e="index.value"){return Z(t,e,{allowEmpty:true,maxLength:Ur})}function Ut(t){if(!t.record_id&&!t.unique_id)return null;let e={};return t?.service&&(e.service=t.service),t?.owner&&(e.owner=t.owner),t?.record_id?e.record_id=Z(t.record_id,"record_id",{allowEmpty:false,onlyAlphanumeric:true}):t?.unique_id&&(e.unique_id=t.unique_id),e}function $e(t){if(t===void 0)return 0;if(typeof t=="number"){if(t>99||t<0)throw new c('"table.access_group" value should be within a range of 0 ~ 99.',{code:"INVALID_REQUEST"})}else if(typeof t=="string"){if(t={private:"private",public:0,authorized:1,admin:99}[t],t===void 0)throw new c('"table.access_group" is invalid.',{code:"INVALID_PARAMETER"})}else throw new c('"table.access_group" should be type: <number | string>.',{code:"INVALID_PARAMETER"});if(!this.__user&&t)throw new c("Unsigned users have no access to records with access group.",{code:"INVALID_REQUEST"});return t}var Ae=4503599627370496;function Ie(t){if(typeof t=="number"){if(t>Ae||t<-Ae)throw new c(`Number value should be within range -${Ae} ~ +${Ae}`,{code:"INVALID_PARAMETER"});return t}if(typeof t=="boolean")return t;if(typeof t=="string")return Dt(t,"index.value");throw new c('"index.value" should be type: <number | boolean | string>.',{code:"INVALID_PARAMETER"})}function Nt(t,e){if(!e.index||!("value"in e.index))throw new c('"index.value" is required.',{code:"INVALID_PARAMETER"});if(e.index.name==="$record_id")throw new c(`Cannot do "index.range" on ${e.index.name}`,{code:"INVALID_PARAMETER"});if(typeof e.index.value!=typeof t)throw new c('"index.range" type should match the type of "index.value".',{code:"INVALID_PARAMETER"});return typeof t=="string"?Dt(t,"index.range"):t}var Te={};async function ae(t,e){let n={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:{}},r=false;function s(o){let a=o=="**"?"private":parseInt(o);return a=a==0?"public":a==1?"authorized":a==99?"admin":a,a}let i={ip:o=>{let a=o.split("#"),l=a[0];a.length>1&&(n.unique_id=a[1]),l.slice(-1)==="R"?(n.readonly=true,l=l.slice(0,-1)):n.readonly=false,/^\d{1,3}-\d{1,3}-\d{1,3}-\d{1,3}$/.test(l)&&(l=l.split("-").join("."),r=true),n.ip=l;},rec:o=>{if(!o)return;n.record_id=o;let a=o.substring(0,o.length-9),l=j(a);n.uploaded=l;},usr:o=>{n.user_id=o;},tbl:o=>{if(o&&!n.table.name){let a=o.split("/");n.table.name=B(a[0]),n.table.access_group=s(a[2]),a?.[3]&&(n.table.subscription.is_subscription_record=true);}},usr_tbl:o=>{let a=o.split("/");n.user_id||(n.user_id=a[0]),n.table.name||(n.table.name=B(a[1]),n.table.access_group=s(a[3]),a?.[4]&&(n.table.subscription.is_subscription_record=true));},idx:o=>{if(!o)return;let a=o.split("!"),l=B(a.splice(0,1)[0]),u=qr("!"+a.join("!"));typeof u=="string"&&(u=B(u)),n.index={name:l,value:u};},ref:o=>{o&&(n.reference=o.split("/")[0]);},tags:o=>{n.tags=Array.isArray(o)?o.map(a=>B(a)):o;},upd:o=>{n.updated=o;},acpt_mrf:o=>{n.source.prevent_multiple_referencing=!o;},ref_limt:o=>{n.source.referencing_limit=o;},rfd:o=>{n.referenced_count=o;},bin:async o=>{let a={},l=n?.reference||null;if(Array.isArray(o)){let u=await Promise.all(o.map(async f=>{try{let d=f.split("/").slice(3).join("/"),p=d.split("/");if(p.length<12)return null;let _=decodeURIComponent(p[p.length-1]),h=decodeURIComponent(p[10]),w=p[9],P=p[8],b=s(p[6]),S=f;if(b!=="public")try{S=await Pe.bind(this)(f,{dataType:"endpoint",_ref:l});}catch(T){console.error("Error getting signed url for private file:",T),S=f;}let v={access_group:b,filename:_,url:S,path:d,size:j(w),uploaded:j(P),getFile:(T,x)=>{let H={dataType:T||"download",progress:x,_ref:l,_update:v};return Pe.bind(this)(S,H)}};return {pathKey:h,obj:v}}catch{return null}}));for(let f of u)if(f){if(a[f.pathKey]){a[f.pathKey].push(f.obj);continue}a[f.pathKey]=[f.obj];}}n.bin=a;},prv_acs:o=>{for(let a in o)["notify_subscribers","upload_to_feed","feed_referencing_records","notify_referencing_records"].includes(a)?n.table.subscription[a]=o[a]:n.source[a]=o[a];},data:o=>{let a=o;o==="!D%{}"?a={}:o==="!L%[]"&&(a=[]),n.data=a;}};if(t.record_id)return t;for(let o in i)if(t.hasOwnProperty(o)){let a=i[o](t[o]);a instanceof Promise&&await a;}return r&&(n.user_id="anonymous:"+n.user_id),n}function qr(t){let e=t.substring(3);switch(t.substring(0,3)){case "!S%":return e;case "!N%":let r=e.split("."),s=Number(r[0])-4503599627370496;return r.length===1?s:parseFloat(s.toString()+"."+r[1]);case "!B%":return e==="1";case "!L%":case "!D%":try{return JSON.parse(e)}catch{throw new c("Value parse error.",{code:"PARSE_ERROR"})}default:return t}}async function Ct(t){let{endpoints:e}=t;if(typeof e=="string"&&(e=[e]),!Array.isArray(e))throw new c('"endpoints" should be type: array | string.',{code:"INVALID_PARAMETER"});let n=await E.bind(this)("del-files",{endpoints:e,storage:"records"},{auth:true,method:"post"}),r=[];for(let s in n)r.push(ae.bind(this)(n[s]));return Promise.all(r)}async function Pe(t,e){if(typeof t!="string")throw new c('"url" should be type: string.',{code:"INVALID_PARAMETER"});let n=t.split("?"),r=n.shift()||"",s=n.length?"?"+n.join("?"):"",i=g.Url(r);t=i+s;let o=false,a=i.split("/"),u=a[2].split("."),f=null;u.length===3&&u[1]==="skapi"&&(f=u[0],o=true);let d=a.slice(3),p=false;if(!o&&(d[0]==="auth"||d[0]==="publ"))try{g.UserId(d[2]),g.UserId(d[3]),p=d[0]=="auth",o=!0;}catch{throw new c("Invalid file url.",{code:"INVALID_PARAMETER"})}let _=f?null:d[1];if(e=g.Params(e,{expires:["number",()=>0],dataType:["base64","blob","endpoint","text","info",()=>"download"],progress:["function","undefined",null],_ref:[null,"string"],_update:b=>b}),e?.dataType==="info")return {url:t,filename:d[d.length-1],fileKey:d[d.length-2],access_group:d[6]==="**"?"private":d[6]==="01"?"authorized":d[6]==="00"?"public":parseInt(d[6]),uploader:d[3],record_id:d[4]==="records"?d[5]:"N/A",filesize:j(d[9]),uploaded:j(d[8])};let h=t.split("/").slice(-1)[0],w=e.expires;if(w){if(!o)throw new c("Expires option can only be used on skapi cdn endpoints.",{code:"INVALID_PARAMETER"});if(w<0)throw new c('"config.expires" should be > 0. (seconds)',{code:"INVALID_PARAMETER"});let b={request:f?"get-host":"get",id:f||d[5],key:t,expires:w};_&&(b.service=_),t=(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 q.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(x){throw this.log("getFile:new token error",x),new c("User login is required.",{code:"INVALID_REQUEST"})}}let S=this.bearerToken||this.session?.idToken?.jwtToken;if(!S||!this.user?.user_id)throw new c("User login is required.",{code:"INVALID_REQUEST"});t+=`${t.includes("?")?"&":"?"}t=${encodeURIComponent(S)}`;let v=d[6]==="**"?"**":parseInt(d[6]),T=this.user?.access_group??-1;if(this.user.user_id!==d[3]&&(v==="**"||T<v)){let x=d[5];if(this.__private_access_key[x]&&typeof this.__private_access_key[x]=="string")t+=`&p=${encodeURIComponent(this.__private_access_key[x])}`;else if(this.owner!==this.host)try{let H=await this.requestPrivateRecordAccessKey({record_id:x,reference_id:e?._ref});t+=`&p=${encodeURIComponent(H)}`;}catch{}}}if(e?.dataType==="endpoint")return e._update&&(e._update.url=t),t;if(e?.dataType==="download"){let b=document.createElement("a");return b.href=t,document.body.appendChild(b),b.setAttribute("download",h),b.target="_blank",b.click(),document.body.removeChild(b),null}return new Promise(async(b,S)=>{try{let v=await E.bind(this)(t,null,{method:"get",contentType:null,responseType:e?.dataType==="text"?"text":"blob",fetchOptions:{progress:e?.progress}},{ignoreService:!0});if(e?.dataType==="base64"){let T=new FileReader;T.onloadend=()=>b(T.result),T.readAsDataURL(v);}else b(v);}catch(v){S(v);}})}async function Lt(t,e=false){t=N(t,{ignoreEmpty:true}).data||{};let n="",r=Ut(t);if(r)t=r,n=t.record_id||t.unique_id,typeof n=="string"&&(typeof this.__private_access_key?.[n]=="string"&&(t.private_key=this.__private_access_key?.[n]||void 0),this.__my_unique_ids[n]&&(e?delete this.__my_unique_ids[n]:t.record_id=this.__my_unique_ids[n]));else {let s=await F.bind(this)(),i=t?.reference,o=false;typeof i=="object"&&Object.keys(i).length&&(i?.record_id||i?.unique_id?(n=i.record_id||i.unique_id,n&&typeof this.__private_access_key?.[n]=="string"&&(t.private_key=this.__private_access_key?.[n]||void 0),t.reference=n):i?.user_id&&(o=i.user_id===this.user?.user_id,t.reference=i.user_id)),typeof t?.table=="string"&&(t.table={name:t.table,access_group:0}),t.index&&t.index.hasOwnProperty("range")&&t.index.hasOwnProperty("condition")&&delete t.index.range;let a=l=>({table:{name:u=>qe(u,"table.name"),access_group:$e.bind(this),subscription:u=>g.UserId(u,'User ID in "subscription"')},reference:"string",index:{name:["$updated","$uploaded","$referenced_count","$user_id",u=>fe(u,"index.name")],value:u=>{let f={$updated:"number",$uploaded:"number",$referenced_count:"number",$user_id:g.UserId};if(f.hasOwnProperty(l.index.name)){let d=f[l.index.name];if(typeof d=="function")return d(u);if(d!==typeof u)throw new c(`"index.value" should be type: ${d}.`,{code:"INVALID_PARAMETER"});return u}return typeof u=="string"&&!u?"":Ie(u)},condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq"],range:u=>Nt(u,l)},tag:u=>{if(u==null)return u;if(typeof u=="string")return Ve(u,"tag");throw new c('"tag" should be type: string.',{code:"INVALID_PARAMETER"})},private_key:"string"});t=g.Params(t||{},a(t),o||s?[]:["table"],{ignoreEmpty:true});}return {query:t,is_reference_fetch:n}}async function Ot(t,e){await this.__connection;let n=await Lt.bind(this)(t),r=n.is_reference_fetch,s=await E.bind(this)("get-records",n.query,{fetchOptions:e,auth:!!this.__user,method:this.__user?"post":"get"});r&&s?.reference_private_key&&typeof s.reference_private_key=="string"&&(this.__private_access_key[r]=s.reference_private_key);let i=[];for(let o in s.list)i.push(ae.bind(this)(s.list[o]));return s.list=await Promise.all(i),s}function Mt(t){let e="",n=[],r=g.Params(t||{},{record_id:i=>typeof i=="string"&&this.__my_unique_ids[i]?this.__my_unique_ids[i]:Z(i,"record_id",{allowEmpty:false}),unique_id:["string",null],readonly:"boolean",table:{name:i=>qe(i,"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:$e.bind(this)},source:{referencing_limit:i=>{if(i===null)return null;if(typeof i=="number"){if(0>i)throw new c('"reference_limit" should be >= 0',{code:"INVALID_PARAMETER"});if(i>4503599627370546)throw new c('"reference_limit" should be <= 4503599627370546',{code:"INVALID_PARAMETER"});return i}throw new c('"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:i=>{if(i===void 0)return;if(!i||Array.isArray(i)&&!i.length)return null;let o={name:l=>fe(l,'"name" in "index_restrictions"'),value:l=>Ie(l),condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne",()=>null],range:l=>{if(l!==null&&typeof i.value!=typeof l)throw new c('Index restriction "range" type should match the type of "value".',{code:"INVALID_PARAMETER"});if(!i.hasOwnProperty("value"))throw new c('Index restriction "value" is required.',{code:"INVALID_PARAMETER"});return l}};Array.isArray(i)||(i=[i]);let a=i.map(l=>g.Params(l,o,["name"]));if(a.length)for(let l of a)l.condition&&l.hasOwnProperty("range")&&delete l.range;return a}},reference:i=>{if(i===null)return {record_id:null};if(i){if(typeof i=="string")return e=i,this.__my_unique_ids[i]?this.__my_unique_ids[i]:i;if(typeof i!="object")throw new c('"reference" should be type: <string | object>.',{code:"INVALID_PARAMETER"});return g.Params(i,{unique_id:"string",record_id:o=>o==null?o:(e=o,typeof this.__private_access_key?.[o]=="string"&&(t.reference_private_key=this.__private_access_key[o]||void 0),Z(o,"reference.record_id",{allowEmpty:false,onlyAlphanumeric:true}))})}},index:[null,{name:i=>fe(i,"index.name"),value:i=>Ie(i)}],tags:i=>{if(i==null)return i;if(typeof i=="string"&&(i=i.split(",").map(o=>o.trim())),!Array.isArray(i))throw new c('"tag" should be type: <string | string[]>.',{code:"INVALID_PARAMETER"});return i.map(o=>Ve(o,"tag"))},remove_bin:i=>{if(!i)return null;let o=[];if(Array.isArray(i))for(let a of i)if(typeof a=="string")o.push(decodeURIComponent(a.split("?")[0]));else if(a.url&&a.size&&a.filename){let u=a.url.split("/").slice(0,3).join("/")+"/"+a.path;o.push(u);}else throw new c('"remove_bin" should be type: <string[] | BinaryFile[] | null>',{code:"INVALID_PARAMETER"});else throw new c('"remove_bin" should be type: <string[] | BinaryFile[] | null>',{code:"INVALID_PARAMETER"});return o},progress:"function",data:i=>i},[],{precall:i=>{let o=i?.data||{};if(!o?.record_id&&!o.table)throw new c('"table.name" is required.',{code:"INVALID_PARAMETER"});typeof o.table=="string"&&(o.table={name:o.table,access_group:0}),i.files&&(n=i.files);}}),s=t.progress||null;if(delete r.progress,!this.__user){let i=!!(r.table?.subscription?.is_subscription_record||r.table?.subscription?.upload_to_feed||r.table?.subscription?.notify_subscribers||r.table?.subscription?.feed_referencing_records||r.table?.subscription?.notify_referencing_records);if(r.record_id)throw new c("Public users cannot update existing records.",{code:"INVALID_REQUEST"});if(r.table.access_group!=="public"&&r.table.access_group!==0)throw new c("Public users can only post records to public tables.",{code:"INVALID_REQUEST"});if(i)throw new c("Public users cannot post subscription records.",{code:"INVALID_REQUEST"});if(r.remove_bin)throw new c("Public users cannot remove files from records.",{code:"INVALID_REQUEST"});if(r.unique_id)throw new c("Public users cannot set unique_id for records.",{code:"INVALID_REQUEST"})}return {config:r,progress:s,is_reference_post:e,files:n}}async function Ft(t){if(await this.__connection,!Array.isArray(t)||!t.length)throw new c('"params" should be a non-empty array.',{code:"INVALID_PARAMETER"});let e=[],n,r,s=null,o={_is_bulk_:t.map((d,p)=>{if(!d||typeof d!="object"||Array.isArray(d))throw new c(`"params[${p}]" should be type: <object>.`,{code:"INVALID_PARAMETER"});let _=Mt.bind(this)(d),h=_.config;if(_.is_reference_post&&e.push(_.is_reference_post),typeof h.progress=="function"&&s===null&&(s=h.progress),h.service!==void 0){if(n===void 0)n=h.service;else if(n!==h.service)throw new c('All bulk params should share the same "service" value.',{code:"INVALID_PARAMETER"})}if(h.owner!==void 0){if(r===void 0)r=h.owner;else if(r!==h.owner)throw new c('All bulk params should share the same "owner" value.',{code:"INVALID_PARAMETER"})}return delete h.progress,delete h.service,delete h.owner,h}),service:"",owner:""};n!==void 0&&(o.service=n),r!==void 0&&(o.owner=r);let a={auth:!!this.__user,method:"post"},l={};Object.keys(l).length&&Object.assign(a,{fetchOptions:l});let u=await E.bind(this)("post-record",o,a),f=await Promise.all(u.map(d=>ae.bind(this)(d,"called from postRecord")));for(let d=0;d<u.length;d++){let p=u[d],_=f[d];if(typeof p?.reference_private_key=="string")for(let h of e)this.__private_access_key[h]=p.reference_private_key;_?.unique_id&&(this.__my_unique_ids[_.unique_id]=_.record_id);}return f}async function qt(t,e,n){if(await this.__connection,!e)throw new c('"config" argument is required.',{code:"INVALID_PARAMETER"});let r=Mt.bind(this)(e),s=r.config,i=r.progress,o=r.is_reference_post,a={auth:!!this.__user,method:"post"},l=[],u=N(t);n&&Array.isArray(n)&&n.length&&(l=l.concat(n)),u.files&&Array.isArray(u.files)&&u.files.length&&(l=l.concat(u.files));let f=null;f=Object.assign({data:u.data},s);let d={};typeof i=="function"&&(d.progress=i),Object.keys(d).length&&Object.assign(a,{fetchOptions:d});let p=await E.bind(this)("post-record",f,a);if(V()&&l.length){let h=new FormData;for(let b of l)h.append(b.name,b.file,b.file.name);let w={record_id:p.rec,progress:i};s.hasOwnProperty("service")&&(w.service=s.service);let{bin_endpoints:P}=await Re.bind(this)(h,w);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 _=await ae.bind(this)(p,"called from postRecord");return _.unique_id&&(this.__my_unique_ids[_.unique_id]=_.record_id,V()&&(this.__uniqueIdsPersistTimer!==null&&clearTimeout(this.__uniqueIdsPersistTimer),this.__uniqueIdsPersistTimer=setTimeout(()=>{this.__uniqueIdsPersistTimer=null;try{window.sessionStorage.setItem(`${this.service}:uniqueids`,JSON.stringify(this.__my_unique_ids));}catch{}},500))),_}async function Vt(t,e){let n=await E.bind(this)("get-table",g.Params(t||{},{table:"string",condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}),Object.assign({auth:!!this.__user},{fetchOptions:e})),r={cnt_rec:"number_of_records",tbl:"table",srvc:"service",grp_:"number_of_records_in_access_group_"};if(Array.isArray(n?.list))for(let s of n.list){for(let i in r){if(i==="grp_"){for(let o in s)if(o.startsWith("grp_")){let a=o.substring(4);a==="pv"?a="private":a==="00"?a="public":a==="01"?a="authorized":a==="99"&&(a="admin"),s[`number_of_records_in_access_group_${a}`]=s[o],delete s[o];}}s.hasOwnProperty(i)&&(s[r[i]]=s[i],delete s[i]);}typeof s.table=="string"&&(s.table=B(s.table));}return n}async function $t(t,e){if(!t?.table)throw new c('"table" is required.',{code:"INVALID_PARAMETER"});let n=g.Params(t||{},{table:"string",index:i=>fe(i,"index.name"),order:{by:["average_number","total_number","number_count","average_bool","total_bool","bool_count","string_count","index_name","number_of_records"],value:["string","number","boolean"],condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}},["table"]);if(n.hasOwnProperty("order")){if(!n.order?.by)throw new c('"order.by" is required.',{code:"INVALID_PARAMETER"});if(n.order.hasOwnProperty("condition")&&!n.order.hasOwnProperty("value"))throw new c('"value" is required for "condition".',{code:"INVALID_PARAMETER"});if(n.hasOwnProperty("index")&&n.index.substring(n.index.length-1)!==".")throw new c('"index" should be a parent index name of the compound index when using "order.by"',{code:"INVALID_PARAMETER"})}let r=await E.bind(this)("get-index",n,Object.assign({auth:!!this.__user},{fetchOptions:e})),s={cnt_bool:"boolean_count",cnt_numb:"number_count",totl_numb:"total_number",totl_bool:"total_bool",avrg_numb:"average_number",avrg_bool:"average_bool",cnt_str:"string_count"};return Array.isArray(r?.list)&&(r.list=r.list.map(i=>{let o=i.idx.split("/"),a={table:B(o[1]),index:B(o[2]),number_of_records:i.cnt_rec};for(let l in s)Object.prototype.hasOwnProperty.call(i,l)&&(a[s[l]]=i[l]);return a})),r}async function jt(t,e){let n=await E.bind(this)("get-tag",g.Params(t||{},{table:"string",tag:"string",condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}),Object.assign({auth:!!this.__user},{fetchOptions:e}));return Array.isArray(n?.list)&&(n.list=n.list.map(r=>{let s=r.tag.split("/");return {table:B(s[1]),tag:B(s[0]),number_of_records:r.cnt_rec}})),n}async function Bt(t,e){let n=await E.bind(this)("get-uniqueid",g.Params(t||{},{unique_id:"string",condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}),Object.assign({auth:!!this.__user},{fetchOptions:e}));if(Array.isArray(n?.list))for(let r in n.list){let s=n.list[r];n.list[r]={unique_id:s.unq,record_id:s.rec};}return n}async function Qt(t,e){await this.__connection;let n=await Lt.bind(this)(t,true),r=n.is_reference_fetch,s=await E.bind(this)("del-records",n.query,{auth:true,fetchOptions:e});return r&&typeof s?.reference_private_key=="string"&&(this.__private_access_key[r]=s.reference_private_key),s?.message||s}function Kt(t){return Jt.bind(this)({record_id:t.record_id,user_id:t.user_id,execute:"add"})}function Ht(t){return Jt.bind(this)({record_id:t.record_id,user_id:t.user_id||null,execute:"remove"})}async function Wt(t,e){let n={record_id:t.record_id||void 0,user_id:t.user_id||void 0,execute:"list"};if(!n.record_id&&!n.user_id)throw new c("Either record_id or user_id must be provided.",{code:"INVALID_PARAMETER"});if(n.user_id)if(typeof n.user_id=="string")g.UserId(n.user_id),n.user_id=[n.user_id];else if(Array.isArray(n.user_id))for(let i of n.user_id)g.UserId(i);else throw new c("user_id should be type: <string | string[]>",{code:"INVALID_PARAMETER"});let r=i=>(i.rec_usr?(i.record_id=i.rec_usr.split("/")[0],i.user_id=i.rec_usr.split("/")[1]):i.usr_rec&&(i.user_id=i.usr_rec.split("/")[0],i.record_id=i.usr_rec.split("/")[1]),i),s=await E.bind(this)("grant-private-access",n,{auth:true,fetchOptions:e});return s.list=s.list.map(r),s}function zt(t){let e=t.record_id,n=t.reference_id||void 0;if(!e)throw new c("Record ID is required.",{code:"INVALID_PARAMETER"});if(typeof e!="string")throw new c("Record ID should be type: <string | string[]>",{code:"INVALID_PARAMETER"});if(n&&typeof n!="string")throw new c("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(Te[e])return Te[e];let r=E.bind(this)("request-private-access-key",{record_id:e,reference_id:n},{auth:true}).then(s=>{let i=typeof s=="string"?s:s?.private_key;if(typeof i!="string")throw new c("Invalid private access key response.",{code:"ERROR"});return this.__private_access_key[e]=i,i}).finally(()=>{delete Te[e];});return Te[e]=r,r}function Jt(t){t.execute;let n=g.Params(t,{record_id:"string",user_id:r=>{if(!r)throw new c("User ID is required.",{code:"INVALID_PARAMETER"});let s=r;if(typeof s=="string"&&(s=[s]),s.length>100)throw new c("Cannot process more than 100 users at once.",{code:"INVALID_REQUEST"});for(let i of s)g.UserId(i,'User ID in "user_id"');return s},execute:["add","remove"]},["execute","record_id","user_id"]);return n.user_id||(n.user_id=null),E.bind(this)("grant-private-access",n,{auth:true})}var I={},O={},Q={},z={},W={},Se={},ke={};function Gt(t,e,n){t[e]||(t[e]=[]),t[e].push(n);}async function ve(t,e,n){let r=[];if(t[e]){for(let s of t[e])if(s){let i=n(s);i instanceof Promise&&(i=await i),r.push(i);}delete t[e];}return r}async function Be(t,e){if(!this?.session?.accessToken?.jwtToken)throw new c("Access token is required.",{code:"INVALID_PARAMETER"});let n=await this.__socket;async function r(s,i,o){this.log("answerSdpOffer from",i),await I[i].setRemoteDescription(new RTCSessionDescription(s));let a=await I[i].createAnswer();await I[i].setLocalDescription(a),o.send(JSON.stringify({action:"rtc",uid:i,content:{sdpanswer:a},token:this.session.accessToken.jwtToken}));}I?.[e]?t?(await ve(ke,e,s=>r.bind(this)(s,e,n)),await r.bind(this)(t,e,n)):await ve(ke,e,s=>r.bind(this)(s,e,n)):t&&Gt(ke,e,t);}async function Qe(t,e){if(this.log("receiveIceCandidate",t),I?.[e]&&I[e]?.remoteDescription&&I[e]?.remoteDescription?.type){if(!t)return ve(Se,e,n=>I[e].addIceCandidate(n));await ve(Se,e,n=>I[e].addIceCandidate(n)),await I[e].addIceCandidate(t);}else Gt(Se,e,t);}async function K(t){if(typeof window>"u"||window._runningInNodeJS)throw new c("WebRTC is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});g.Params(t,{cid:i=>{if(typeof i!="string")throw new c('"cid" should be type: <string>.',{code:"INVALID_PARAMETER"});if(i&&i.slice(0,4)!=="cid:")throw new c('"cid" should be a valid connection id.',{code:"INVALID_PARAMETER"});return i},close:"boolean"});let e=await this.__socket,{cid:n,close_all:r=false}=t||{};if(!r&&!n)throw new c('"cid" is required.',{code:"INVALID_PARAMETER"});let s=i=>{if(!i)throw new c('"cid" is required.',{code:"INVALID_PARAMETER"});if(delete ke[i],delete Se[i],O[i]&&Object.values(O[i]).forEach(o=>{o.readyState!=="closed"&&o.close();}),delete O[i],I?.[i]){I[i].connectionState!=="closed"&&(I[i].close(),e.send(JSON.stringify({action:"rtc",uid:i,content:{hungup:this.user.user_id},token:this.session.accessToken.jwtToken})));let o={type:"connectionstatechange",target:I[i],timestamp:new Date().toISOString(),state:I[i].connectionState,iceState:I[i].iceConnectionState,signalingState:I[i].signalingState};W[i]&&W[i](o),this.log("closeRTC",o);}delete W[i],delete z[i],delete Q[i],delete I[i];};if(r)for(let i in I)s(i);else s(n);this.log("Cleaning up media stream..."),this.__mediaStream&&(this.__mediaStream.getTracks().forEach(i=>{i.stop();}),this.__mediaStream=null);}async function Xt(t){if(t instanceof MediaStream)return t;if(!t.video&&!t.audio){let e=new MediaStream,n=document.createElement("canvas");n.width=1,n.height=1;let s=n.captureStream().getVideoTracks()[0];return e.addTrack(s),e}return window.navigator.mediaDevices.getUserMedia(t)}async function Zt(t,e){if(typeof window>"u"||window._runningInNodeJS)throw new c("WebRTC is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(typeof e!="function")throw new c("Callback is required.",{code:"INVALID_PARAMETER"});if(!this?.session?.accessToken?.jwtToken)throw new c("Access token is required.",{code:"INVALID_PARAMETER"});t=g.Params(t,{cid:o=>{if(typeof o!="string")throw new c('"cid" should be type: <string>.',{code:"INVALID_PARAMETER"});if(o&&o.slice(0,4)!=="cid:")throw new c('"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:n,ice:r}=t;if(!(t?.media instanceof MediaStream)&&(t?.media?.video||t?.media?.audio)&&window.location.hostname!=="localhost"&&window.location.protocol!=="https:")throw new c("Media stream is only supported on either localhost or https.",{code:"INVALID_REQUEST"});let s=this.__socket?await this.__socket:this.__socket;if(!s)throw new c("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});if(s.readyState!==1)throw new c("Realtime connection is not ready.",{code:"INVALID_REQUEST"});let i={iceServers:[{urls:r}]};I?.[n]||(I[n]=new RTCPeerConnection(i)),t?.media&&(this.__mediaStream=await Xt(t.media),this.__mediaStream.getTracks().forEach(o=>{I[n].addTrack(o,this.__mediaStream);})),W[n]=e,O[n]||(O[n]={});for(let o=0;o<t.channels.length;o++){let a=t.channels[o];if(typeof a=="string")switch(a){case "text-chat":a={ordered:true,maxRetransmits:10,protocol:"text-chat"};break;case "file-transfer":a={ordered:false,maxPacketLifeTime:3e3,protocol:"file-transfer"};break;case "video-chat":a={ordered:true,maxRetransmits:10,protocol:"video-chat"};break;case "voice-chat":a={ordered:true,maxRetransmits:10,protocol:"voice-chat"};break;case "gaming":a={ordered:false,maxPacketLifeTime:100,protocol:"gaming"};break;default:a={ordered:true,maxRetransmits:10,protocol:"default"};break}let l=a.protocol||"default";if(Object.keys(O[n]).includes(l))throw new c(`Data channel with the protocol "${l}" already exists.`,{code:"INVALID_REQUEST"});let u=I[n].createDataChannel(l,a);O[n][l]=u;}for(let o in O[n]){let a=O[n][o];tn.bind(this)(n,a);}return en.bind(this)(n,["onnegotiationneeded"]),await je.bind(this)(n),{hangup:()=>Q[n]&&Q[n](false),connection:new Promise(o=>{Q[n]=(a=>{if(this.log("receiver picked up the call",n),!a)return K.bind(this)({cid:n}),null;I[n].onnegotiationneeded=()=>{this.log("onnegotiationneeded",`sending offer to "${n}".`),je.bind(this)(n),W[n]&&W[n]({type:"negotiationneeded",target:I[n],timestamp:new Date().toISOString(),signalingState:I[n].signalingState,connectionState:I[n].iceConnectionState,gatheringState:I[n].iceGatheringState});},o({target:I[n],channels:O[n],hangup:()=>K.bind(this)({cid:n}),media:this.__mediaStream});}).bind(this);})}}function Yt(t){return async(e,n)=>{e=e||{},e=N(e).data;let r=t.sender_cid,s=await this.__socket;if(!z[r])return null;if(typeof n!="function")throw new c("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 c("Media stream is only supported on either localhost or https.",{code:"INVALID_REQUEST"});let{ice:i="stun:stun.skapi.com:3468"}=e;return I?.[r]||(I[r]=new RTCPeerConnection({iceServers:[{urls:i}]})),e?.media&&(this.__mediaStream=await Xt(e.media),this.__mediaStream.getTracks().forEach(o=>{I[r].addTrack(o,this.__mediaStream);})),delete z[r],W[r]=n,O[r]||(O[r]={}),I[r].ondatachannel=o=>{this.log("ondatachannel",`received data channel "${o.channel.label}".`);let a=o.channel;O[r][a.label]=a,tn.bind(this)(r,a);},en.bind(this)(r,["onnegotiationneeded"]),await Be.bind(this)(null,r),await Qe.bind(this)(null,r),s.send(JSON.stringify({action:"rtc",uid:r,content:{pickup:this.user.user_id},token:this.session.accessToken.jwtToken})),{target:I[r],channels:O[r],hangup:()=>K.bind(this)({cid:r}),media:this.__mediaStream}}}async function je(t){if(!this?.session?.accessToken?.jwtToken)throw new c("Access token is required.",{code:"INVALID_PARAMETER"});this.log("sendOffer",t);let e=await this.__socket,n=await I[t].createOffer();await I[t].setLocalDescription(n);let r=I[t].localDescription;this.log("rtcSdpOffer to",r),e.send(JSON.stringify({action:"rtc",uid:t,content:{sdpoffer:r},token:this.session.accessToken.jwtToken}));}async function Vr(t,e){if(!this?.session?.accessToken?.jwtToken)throw new c("Access token is required.",{code:"INVALID_PARAMETER"});this.log("sendIceCandidate to",e);let n=await this.__socket;if(!t.candidate){this.log("candidate-end","all ice candidates have been sent");return}let r=W[e]||(()=>{}),s=t.candidate;this.log("ice gathering state set to",I[e].iceGatheringState),r({type:"icecandidate",target:I[e],timestamp:new Date().toISOString(),candidate:t.candidate.candidate,sdpMid:t.candidate.sdpMid,sdpMLineIndex:t.candidate.sdpMLineIndex,usernameFragment:t.candidate.usernameFragment,protocol:t.candidate.protocol,gatheringState:I[e].iceGatheringState,connectionState:I[e].iceConnectionState}),n.send(JSON.stringify({action:"rtc",uid:e,content:{candidate:s},token:this.session.accessToken.jwtToken}));}function en(t,e){let n=new Set(e),r=W[t]||(o=>{}),s=I[t],i={ontrack:o=>{r({type:"track",target:s,timeStamp:o.timeStamp,streams:o.streams,track:o.track});},onicecandidate:o=>{Vr.bind(this)(o,t),o.candidate?r({type:"icecandidate",target:s,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:s.iceGatheringState,connectionState:s.iceConnectionState}):r({type:"icecandidateend",target:s,timestamp:new Date().toISOString()});},onicecandidateerror:o=>{r({type:"icecandidateerror",target:s,timestamp:new Date().toISOString(),errorCode:o.errorCode,errorText:o.errorText,url:o.url,hostCandidate:o.hostCandidate,gatheringState:s.iceGatheringState,connectionState:s.iceConnectionState});},oniceconnectionstatechange:()=>{r({type:"iceconnectionstatechange",target:s,timestamp:new Date().toISOString(),state:s.iceConnectionState,gatheringState:s.iceGatheringState,signalingState:s.signalingState});},onicegatheringstatechange:()=>{r({type:"icegatheringstatechange",target:s,timestamp:new Date().toISOString(),state:s.iceGatheringState,connectionState:s.iceConnectionState,signalingState:s.signalingState});},onsignalingstatechange:()=>{r({type:"signalingstatechange",target:s,timestamp:new Date().toISOString(),state:s.signalingState,connectionState:s.iceConnectionState,gatheringState:s.iceGatheringState});},onnegotiationneeded:()=>{je.bind(this)(t),r({type:"negotiationneeded",target:s,timestamp:new Date().toISOString(),signalingState:s.signalingState,connectionState:s.iceConnectionState,gatheringState:s.iceGatheringState});},onconnectionstatechange:()=>{r({type:"connectionstatechange",target:s,timestamp:new Date().toISOString(),state:s.connectionState,iceState:s.iceConnectionState,signalingState:s.signalingState});let o=s.connectionState;(o==="disconnected"||o==="failed"||o==="closed")&&K.bind(this)({cid:t});}};for(let[o,a]of Object.entries(i))n.has(o)||(s[o]=a);}function tn(t,e,n){let r=new Set(n),s=W[t]||(o=>{}),i={onmessage:o=>{let a={type:o.type,target:e,timeStamp:o.timeStamp,data:o.data,lastEventId:o.lastEventId,origin:o.origin,readyState:e.readyState,bufferedAmount:e.bufferedAmount};this.log(`${e.label}: message`,o.data),s(a);},onerror:o=>{let a={type:o.type,target:e,timeStamp:o.timeStamp,error:o.error.message,errorCode:o.error.errorDetail,readyState:e.readyState,label:e.label};this.log(`${e.label}: error`,o.error.message),s(a);},onclose:o=>{let a={type:o.type,target:e,timeStamp:o.timeStamp,readyState:e.readyState,label:e.label,id:e.id};this.log(`${e.label}: closed`,null),s(a),O[t]&&(delete O[t][e.label],Object.keys(O[t]).length===0&&K.bind(this)({cid:t}));},onbufferedamountlow:o=>{let a={target:e,bufferedAmount:e.bufferedAmount,bufferedAmountLowThreshold:e.bufferedAmountLowThreshold,type:o.type,timeStamp:o.timeStamp};this.log(`${e.label}: bufferedamountlow`,e.bufferedAmount),s(a);},onopen:o=>{this.log("dataChannel",`data channel: "${e.label}" is open and ready to send messages.`);let a={type:o.type,target:e,timeStamp:o.timeStamp,readyState:e.readyState,label:e.label,id:e.id,ordered:e.ordered,maxRetransmits:e.maxRetransmits,protocol:e.protocol};s(a);}};for(let[o,a]of Object.entries(i))r.has(o)||(e[o]=a);}var ee,Y=null,he=true,ce=0;async function $r(){if(typeof window>"u"||window._runningInNodeJS)throw new c("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.getProfile(),!this.session)throw new c("No access.",{code:"INVALID_REQUEST"});let t=await this.record_endpoint;return new WebSocket(t.websocket_private+"?token="+this.session.accessToken.jwtToken)}var Ke=null;async function nn(){if(typeof window>"u"||window._runningInNodeJS)throw new c("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});he=true;let t=this.__socket?await this.__socket:this.__socket;K.bind(this)({close_all:true}),ee&&He.bind(this)({group:null}),ce=0,Y&&(Y.terminate(),Y=null);try{t&&t.close();}catch{}return window.removeEventListener("visibilitychange",Ke),this.__socket=null,null}async function xe(t,e=50,n){if(typeof window>"u"||window._runningInNodeJS)throw new c("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(typeof t!="function")throw new c("Callback must be a function.",{code:"INVALID_REQUEST"});if(n==="reconnect"){if(this.__socket instanceof Promise){let r=await this.__socket;if(r.readyState!==WebSocket.CLOSED&&r.readyState!==WebSocket.CLOSING)return this.__socket}}else if(he&&(Ke=()=>{!document.hidden&&!he&&xe.bind(this)(t,0,"reconnect");},this.__socket instanceof Promise))return this.__socket;Y&&(Y.terminate(),Y=null),this.__socket=new Promise(async r=>{await se.bind(this)(),setTimeout(async()=>{let s=await $r.bind(this)();s.onopen=()=>{he=false,ce=0,n!=="reconnect"&&window.addEventListener("visibilitychange",Ke),this.log("realtime onopen","Connected to WebSocket server."),t({type:"success",message:"Connected to WebSocket server."}),ee&&s.send(JSON.stringify({action:"joinRoom",rid:ee,token:this.session.accessToken.jwtToken}));let i=`
206
+ var zn=Object.defineProperty;var Jn=Object.getOwnPropertyDescriptor;var ie=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var R=(t,e,n,r)=>{for(var s=Jn(e,n),i=t.length-1,o;i>=0;i--)(o=t[i])&&(s=(o(e,n,s))||s);return s&&zn(e,n,s),s};var X=typeof globalThis<"u"?globalThis:void 0,be=X?.window;function Gn(t){if(Buffer)return Buffer.from(t).toString("base64");let e="",n=new Uint8Array(t),r=32768;for(let s=0;s<n.length;s+=r){let i=n.subarray(s,s+r);e+=String.fromCharCode.apply(null,Array.from(i));}if(typeof btoa=="function")return btoa(e);throw new Error("No base64 encoder available in this environment.")}if(be)be.global=be,be.global._runningInNodeJS=false;else if(X&&(X.global=X,typeof X.window>"u")){class t{constructor(){this.result=null;this.error=null;this.onload=null;this.onloadend=null;this.onerror=null;}readAsDataURL(r){r.arrayBuffer().then(s=>{let i=Gn(s),o=r.type||"application/octet-stream";this.result=`data:${o};base64,${i}`,this.onload&&this.onload({target:this}),this.onloadend&&this.onloadend({target:this});}).catch(s=>{this.error=s,this.onerror&&this.onerror({target:this});});}readAsArrayBuffer(r){r.arrayBuffer().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});});}readAsText(r,s="utf-8"){r.text().then(i=>{this.result=i,this.onload&&this.onload({target:this}),this.onloadend&&this.onloadend({target:this});}).catch(i=>{this.error=i,this.onerror&&this.onerror({target:this});});}}X.FileReader=t;class e{constructor(){this.status=0;this.statusText="";this.readyState=0;this.responseText="";this.response=null;this.responseType="";this.responseURL="";this.timeout=0;this.withCredentials=false;this.onload=null;this.onerror=null;this.onabort=null;this.ontimeout=null;this.onprogress=null;this.onreadystatechange=null;this.upload={onprogress:null};this._method="GET";this._url="";this._headers={};this._aborted=false;}open(r,s){this._method=r,this._url=s,this.readyState=1;}setRequestHeader(r,s){this._headers[r]=s;}getResponseHeader(r){return null}abort(){this._aborted=true,this.onabort&&this.onabort({});}send(r){if(this._aborted)return;let s={method:this._method,headers:this._headers};r&&this._method!=="GET"&&this._method!=="HEAD"&&(s.body=r),fetch(this._url,s).then(async i=>{if(!this._aborted){if(this.status=i.status,this.statusText=i.statusText,this.responseURL=i.url,this.readyState=4,this.responseType==="blob")this.response=await i.blob();else if(this.responseType==="json")try{this.response=await i.json();}catch{this.response=null;}else this.responseType==="arraybuffer"?this.response=await i.arrayBuffer():(this.responseText=await i.text(),this.response=this.responseText);this.onload&&this.onload({});}}).catch(i=>{this._aborted||this.onerror&&this.onerror(i);});}}X.XMLHttpRequest=e,X.window={_runningInNodeJS:true,alert:n=>console.error("[Alert]",n),sessionStorage:{getItem:n=>null,setItem:(n,r)=>{},removeItem:n=>{}},localStorage:{getItem:n=>{let r=ie("fs"),s=ie("path");try{let i=s.resolve(process.cwd(),"states","localStorage",`${n}.skapi`);return r.existsSync(i)?r.readFileSync(i,"utf8"):null}catch{return null}},setItem:(n,r)=>{let s=ie("fs"),i=ie("path");try{let o=i.resolve(process.cwd(),"states","localStorage");s.existsSync(o)||s.mkdirSync(o,{recursive:!0});let a=i.resolve(o,`${n}.skapi`);s.writeFileSync(a,r,"utf8");}catch{}},removeItem:n=>{let r=ie("fs"),s=ie("path");try{let i=s.resolve(process.cwd(),"states","localStorage",`${n}.skapi`);r.existsSync(i)&&r.unlinkSync(i);}catch{}}},location:{href:"",origin:"",hostname:"",protocol:"",replace:n=>{}},navigator:{userAgent:`nodejs/${X?.process?.versions?.node||"unknown"}`,mediaDevices:{getUserMedia:async n=>{throw new Error("getUserMedia is not supported in Node.js environment.")}}},addEventListener:()=>{},removeEventListener:()=>{}};}var c=class extends Error{constructor(e,n){if(Array.isArray(e)&&e.length<=2){let r=e[1];if(e.length>2)for(let s=2;s<e.length&&typeof e[s]=="string";s++)r+=e[s];super((r||"Something went wrong.").trim()),this.name=n?.name||"SKAPI",this.code=n?.code||e[0]||"ERROR",n?.cause&&(this.cause=n.cause);}else super((e?.message||(typeof e=="string"?e:"Something went wrong.")).trim()),typeof e=="string"?(this.name=n?.name||"SKAPI",this.code=n?.code||"ERROR",n?.cause&&(this.cause=n.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=n?.name||"SKAPI",this.code=n?.code||"ERROR",this.cause=e?.cause);}};var Z="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Ce=BigInt(Z.length),Xn=2*1024*1024,Zn=["aud","cognito:username","event_id","exp","iat","iss","jti","origin_jti","secret_key","token_use"],Ge={auth_time:"log",sub:"user_id"},Yn=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f","g","h","i","j","k","l"],tt=["us31","us72","ap51","ap22","ap41","eu71","ap21","us32","us71","af51","ap31","ap43","ap23","ap42","ca01","eu01","eu72","eu51","eu73","eu11","me51","sa31"],Xe=typeof TextEncoder<"u"?new TextEncoder:null;function er(){if(typeof globalThis<"u")return globalThis.Buffer}function tr(t){if(Xe)return Xe.encode(t);let e=unescape(encodeURIComponent(t)),n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r);return n}function nr(t){if(t instanceof Uint8Array)return t;if(typeof t=="string")return tr(t);if(typeof ArrayBuffer<"u"&&t instanceof ArrayBuffer)return new Uint8Array(t);if(typeof ArrayBuffer<"u"&&ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);if(Array.isArray(t))return Uint8Array.from(t);let e=er();if(e)return new Uint8Array(e.from(t));throw new Error("No byte conversion available in this environment.")}var b=class b{static hash(e){typeof e!="string"&&(console.warn("coercing non-string value to empty string"),e="");let n=b.sb(e),r=1732584193,s=-271733879,i=-1732584194,o=271733878,a,l,u,f;for(let d=0;d<n.length;d+=16)a=r,l=s,u=i,f=o,r=b.ff(r,s,i,o,n[d],7,-680876936),o=b.ff(o,r,s,i,n[d+1],12,-389564586),i=b.ff(i,o,r,s,n[d+2],17,606105819),s=b.ff(s,i,o,r,n[d+3],22,-1044525330),r=b.ff(r,s,i,o,n[d+4],7,-176418897),o=b.ff(o,r,s,i,n[d+5],12,1200080426),i=b.ff(i,o,r,s,n[d+6],17,-1473231341),s=b.ff(s,i,o,r,n[d+7],22,-45705983),r=b.ff(r,s,i,o,n[d+8],7,1770035416),o=b.ff(o,r,s,i,n[d+9],12,-1958414417),i=b.ff(i,o,r,s,n[d+10],17,-42063),s=b.ff(s,i,o,r,n[d+11],22,-1990404162),r=b.ff(r,s,i,o,n[d+12],7,1804603682),o=b.ff(o,r,s,i,n[d+13],12,-40341101),i=b.ff(i,o,r,s,n[d+14],17,-1502002290),s=b.ff(s,i,o,r,n[d+15],22,1236535329),r=b.gg(r,s,i,o,n[d+1],5,-165796510),o=b.gg(o,r,s,i,n[d+6],9,-1069501632),i=b.gg(i,o,r,s,n[d+11],14,643717713),s=b.gg(s,i,o,r,n[d],20,-373897302),r=b.gg(r,s,i,o,n[d+5],5,-701558691),o=b.gg(o,r,s,i,n[d+10],9,38016083),i=b.gg(i,o,r,s,n[d+15],14,-660478335),s=b.gg(s,i,o,r,n[d+4],20,-405537848),r=b.gg(r,s,i,o,n[d+9],5,568446438),o=b.gg(o,r,s,i,n[d+14],9,-1019803690),i=b.gg(i,o,r,s,n[d+3],14,-187363961),s=b.gg(s,i,o,r,n[d+8],20,1163531501),r=b.gg(r,s,i,o,n[d+13],5,-1444681467),o=b.gg(o,r,s,i,n[d+2],9,-51403784),i=b.gg(i,o,r,s,n[d+7],14,1735328473),s=b.gg(s,i,o,r,n[d+12],20,-1926607734),r=b.hh(r,s,i,o,n[d+5],4,-378558),o=b.hh(o,r,s,i,n[d+8],11,-2022574463),i=b.hh(i,o,r,s,n[d+11],16,1839030562),s=b.hh(s,i,o,r,n[d+14],23,-35309556),r=b.hh(r,s,i,o,n[d+1],4,-1530992060),o=b.hh(o,r,s,i,n[d+4],11,1272893353),i=b.hh(i,o,r,s,n[d+7],16,-155497632),s=b.hh(s,i,o,r,n[d+10],23,-1094730640),r=b.hh(r,s,i,o,n[d+13],4,681279174),o=b.hh(o,r,s,i,n[d],11,-358537222),i=b.hh(i,o,r,s,n[d+3],16,-722521979),s=b.hh(s,i,o,r,n[d+6],23,76029189),r=b.hh(r,s,i,o,n[d+9],4,-640364487),o=b.hh(o,r,s,i,n[d+12],11,-421815835),i=b.hh(i,o,r,s,n[d+15],16,530742520),s=b.hh(s,i,o,r,n[d+2],23,-995338651),r=b.ii(r,s,i,o,n[d],6,-198630844),o=b.ii(o,r,s,i,n[d+7],10,1126891415),i=b.ii(i,o,r,s,n[d+14],15,-1416354905),s=b.ii(s,i,o,r,n[d+5],21,-57434055),r=b.ii(r,s,i,o,n[d+12],6,1700485571),o=b.ii(o,r,s,i,n[d+3],10,-1894986606),i=b.ii(i,o,r,s,n[d+10],15,-1051523),s=b.ii(s,i,o,r,n[d+1],21,-2054922799),r=b.ii(r,s,i,o,n[d+8],6,1873313359),o=b.ii(o,r,s,i,n[d+15],10,-30611744),i=b.ii(i,o,r,s,n[d+6],15,-1560198380),s=b.ii(s,i,o,r,n[d+13],21,1309151649),r=b.ii(r,s,i,o,n[d+4],6,-145523070),o=b.ii(o,r,s,i,n[d+11],10,-1120210379),i=b.ii(i,o,r,s,n[d+2],15,718787259),s=b.ii(s,i,o,r,n[d+9],21,-343485551),r=b.ad(r,a),s=b.ad(s,l),i=b.ad(i,u),o=b.ad(o,f);return b.rh(r)+b.rh(s)+b.rh(i)+b.rh(o)}static rh(e){let n="";for(let r=0;r<=3;r++)n+=b.alphabet.charAt(e>>r*8+4&15)+b.alphabet.charAt(e>>r*8&15);return n}static ad(e,n){let r=(e&65535)+(n&65535);return (e>>16)+(n>>16)+(r>>16)<<16|r&65535}static rl(e,n){return e<<n|e>>>32-n}static cm(e,n,r,s,i,o){return b.ad(b.rl(b.ad(b.ad(n,e),b.ad(s,o)),i),r)}static ff(e,n,r,s,i,o,a){return b.cm(n&r|~n&s,e,n,i,o,a)}static gg(e,n,r,s,i,o,a){return b.cm(n&s|r&~s,e,n,i,o,a)}static hh(e,n,r,s,i,o,a){return b.cm(n^r^s,e,n,i,o,a)}static ii(e,n,r,s,i,o,a){return b.cm(r^(n|~s),e,n,i,o,a)}static sb(e){let n,r=(e.length+8>>6)+1,s=new Array(r*16);for(n=0;n<r*16;n++)s[n]=0;for(n=0;n<e.length;n++)s[n>>2]|=e.charCodeAt(n)<<n%4*8;return s[n>>2]|=128<<n%4*8,s[r*16-2]=e.length*8,s}};b.alphabet="0123456789abcdef";var M=b;function nt(t){if(t===0)return Z[0];let e="";for(;t>0;)e=Z[t%62]+e,t=Math.floor(t/62);return e}function j(t){return t.split("").reverse().reduce((e,n,r)=>e+Z.indexOf(n)*62**r,0)}function re(t=6){let e="",n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",r=n.length,s=0;for(;s<t;)e+=n.charAt(Math.floor(Math.random()*r)),s+=1;return e}function Le(){return typeof window>"u"||!!window?._runningInNodeJS}function V(){return !Le()&&typeof document<"u"&&typeof document.createElement=="function"}function ye(t){let e;try{e=JSON.stringify(t);}catch{throw new c("Invalid data type.",{code:"INVALID_REQUEST"})}if(new Blob([e]).size>Xn)throw new c("Data should not exceed 2MB",{code:"INVALID_REQUEST"})}function Ze(t){return t===""||t==="on"||t==="true"}function Ye(t){return t==="false"}function et(t,e,n){e.name&&n(t,e.name,e.value);}var we=V(),rr=typeof SubmitEvent<"u",ir=typeof HTMLFormElement<"u";function N(t,e,n){let r={},s=[];function i(l,u,f){if(e?.ignoreEmpty&&f==="")return;if(e?.nullIfEmpty&&f===""&&(f=null),typeof n=="function"){let w=n(u,f);w!==void 0&&(f=w);}let d=u.split("[").map(w=>{let h=w.replace("]",""),m=Number(h);return !isNaN(m)&&!h.includes(".")?h=m:(h[0]==='"'&&h[h.length-1]==='"'||h[0]==="'"&&h[h.length-1]==="'")&&(h=h.replace(/"/g,"").replace(/'/g,"")),h}),p=l;if(typeof d[0]=="number")throw new c("Form key cannot start with an array index.",{code:"INVALID_REQUEST"});for(let w=0;w<d.length;w++){let h=d[w];w<d.length-1?(p[h]===void 0&&(typeof d[w+1]=="number"?p[h]=[]:p[h]={}),p=p[h]):p[h]===void 0?p[h]=f:Array.isArray(p[h])?p[h].push(f):p[h]=[p[h],f];}}function o(l,u,f){if(f instanceof File)l.push({name:u,file:f});else if(f instanceof FileList&&f&&f.length>0)for(let d=0;d<=f.length-1;d++){let p=f.item(d);p&&l.push({name:u,file:p});}}let a=l=>{l.name&&(l.type==="number"?l.value&&i(r,l.name,Number(l.value)):l.type==="checkbox"||l.type==="radio"?l.checked?l.type==="checkbox"&&l.value===""||Ze(l.value)?i(r,l.name,true):Ye(l.value)?i(r,l.name,false):l.value&&i(r,l.name,l.value):l.type==="checkbox"&&(Ze(l.value)?i(r,l.name,false):Ye(l.value)&&i(r,l.name,true)):l.type==="file"?l.files&&l.files.length>0&&o(s,l.name,l.files):i(r,l.name,l.value));};if(we&&(t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement))return a(t),ye(r),{data:r,files:s};if(we&&t instanceof FormData){for(let l of t.entries()){let u=l[0],f=l[1];if(f instanceof File||f instanceof FileList)o(s,u,f);else if(f instanceof Blob){let d=f;if(d.type==="application/json")try{let p=JSON.parse(d.text());i(r,u,p);}catch{i(r,u,d);}}else i(r,u,f);}return ye(r),{data:r,files:s}}if(we&&rr&&t instanceof SubmitEvent&&(t=t.target),we&&ir&&t instanceof HTMLFormElement){let l=t.querySelectorAll("input"),u=t.querySelectorAll("select"),f=t.querySelectorAll("textarea");for(let d=0;d<u.length;d++)et(r,u[d],i);for(let d=0;d<f.length;d++)et(r,f[d],i);for(let d=0;d<l.length;d++)a(l[d]);return ye(r),{data:r,files:s}}return ye(t),{data:t,files:s}}function ue(t){let e={};for(let n in t){let r=t[n];if(!Zn.includes(n))if(Ge[n])e[Ge[n]]=r;else if(n.includes("custom:"))e[n.replace("custom:","")]=r;else if(n==="address"){let s=r;if(s&&typeof s=="object"&&Object.keys(s).length){if(s?.formatted)try{e[n]=JSON.parse(s.formatted);}catch{e[n]=s.formatted;}}else e[n]=s;}else e[n]=r;}for(let n of ["address_public","birthdate_public","email_public","gender_public","phone_number_public","access_group"])n.includes("_public")?e.hasOwnProperty(n.split("_")[0])?e[n]=e.hasOwnProperty(n)?!!Number(e[n]):false:delete e[n]:e[n]=e.hasOwnProperty(n)?Number(e[n]):0;for(let n of ["email","phone_number"])e.hasOwnProperty(n)?e[n+"_verified"]=e[n+"_verified"]===true:delete e[n+"_verified"];return e}function Oe(t){if(t=gr(t),t.split("-").length===7){let e=t.split("-"),n,r;try{n=tt[j(e[1][0])],r=e.slice(2).join("-");}catch{throw new Error("INVALID_PARAMETER: Service ID is invalid.")}if(!n)throw new Error("INVALID_PARAMETER: Service ID is invalid.");return {service:n+e[0]+e[1].slice(1),owner:r}}return {service:t,owner:""}}function rt(t,e){let n=tt.indexOf(t.slice(0,4)),r=Yn[n],i=`${t.slice(4,-4)}-${r}${t.slice(-4)}-${e}`;return dr(i)}function sr(t){let e=0n;for(let n of t){let r=Z.indexOf(n);if(r<0)throw new Error(`INVALID_PARAMETER: Invalid base62 character: ${n}`);e=e*Ce+BigInt(r);}return e}function or(t,e=1){if(t<0n)throw new Error("INVALID_PARAMETER: Negative values are not supported.");if(t===0n)return "0".repeat(Math.max(1,e));let n="",r=t;for(;r>0n;){let s=Number(r%Ce);n=Z[s]+n,r/=Ce;}return n.length<e&&(n="0".repeat(e-n.length)+n),n}function ar(t){if(t===0n)return Uint8Array.from([0]);let e=[],n=t;for(;n>0n;)e.push(Number(n&0xffn)),n>>=8n;return e.reverse(),Uint8Array.from(e)}function cr(t){let e=0n;for(let n of t)e=(e<<8n)+BigInt(n);return e}function lr(t){let e=String(t).replace(/-/g,"");if(!/^[0-9a-fA-F]{32}$/.test(e))throw new Error("INVALID_PARAMETER: Invalid UUID format.");let n=new Uint8Array(16);for(let r=0;r<16;r++)n[r]=parseInt(e.slice(r*2,r*2+2),16);return n}function ur(t){let e=Array.from(nr(t),n=>n.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 dr(t){let e=String(t);if(e.split("-").length===2)return e;let n=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(!n)throw new Error("INVALID_PARAMETER: Input must match <base62>-<base62>-<uuid>.");let[,r,s,i]=n;if(r.length<2)throw new Error("INVALID_PARAMETER: The first part must contain at least 2 characters.");if(s.length>=Z.length)throw new Error("INVALID_PARAMETER: The middle section is too long to encode.");let o=r.slice(0,2),a=r.slice(2),l=s+o,u=Z[s.length]+a+l,f=lr(i),d=or(cr(f));return `${u}-${d}`}function gr(t){let e=String(t);if(e.split("-").length!==2)return e;let n=e.split("-");if(n.length!==2||!n[0]||!n[1])throw new Error("INVALID_PARAMETER: Corrupt compressed token.");let[r,s]=n,i=Z.indexOf(r[0]);if(i<0)throw new Error("INVALID_PARAMETER: Corrupt compressed token.");let o=r.slice(1),a=i+2;if(o.length<a)throw new Error("INVALID_PARAMETER: Corrupt compressed token.");let l=o.slice(0,o.length-a),u=o.slice(o.length-a),f=u.slice(i),d=u.slice(0,i),p=f+l;if(!/^[0-9A-Za-z]+$/.test(p)||!/^[0-9A-Za-z]+$/.test(d))throw new Error("INVALID_PARAMETER: Corrupt compressed token.");let w=sr(s),h=ar(w);if(h.length>16)throw new Error("INVALID_PARAMETER: Corrupt compressed token.");let m=new Uint8Array(16);m.set(h,16-h.length);let I=ur(m);return `${p}-${d}-${I}`}function hr(t,e="User ID"){let n=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;if(t){if(typeof t!="string")throw new c(`${e} should be type: string.`,{code:"INVALID_PARAMETER"});if(!t.match(n))throw new c(`${e} is invalid.`,{code:"INVALID_PARAMETER"})}else throw new c(`${e} is empty.`,{code:"INVALID_PARAMETER"});return t}function pr(t){if(t&&(typeof t!="string"||t.charAt(0)!=="+"||isNaN(Number(t.substring(1)))))throw new c('"phone_number" is invalid. The format should be "+00123456789". Type: string.',{code:"INVALID_PARAMETER"});return t||""}function mr(t){if(t){if(typeof t!="string")throw new c('"birthdate" is invalid. The format should be "yyyy-mm-dd". Type: string.',{code:"INVALID_PARAMETER"});{let e=new RegExp(/([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))/);if(t.length!==10||t.split("-").length!==3||!e.test(t))throw new c('"birthdate" is invalid. The format should be "yyyy-mm-dd". Type: string.',{code:"INVALID_PARAMETER"})}}return t||""}function _r(t){if(t){if(typeof t!="string")throw new c('"password" should be type: string.',{code:"INVALID_PARAMETER"});if(t.length<6)throw new c('"password" should be at least 6 characters.',{code:"INVALID_PARAMETER"});if(t.length>60)throw new c('"password" can be up to 60 characters max.',{code:"INVALID_PARAMETER"})}else throw new c('"password" is required.',{code:"INVALID_PARAMETER"});return t}function br(t,e="email"){if(t){if(typeof t!="string")throw new c(`"${e}"should be type: string.`,{code:"INVALID_PARAMETER"});if(t.length<5)throw new c(`"${e}" should be at least 5 characters.`,{code:"INVALID_PARAMETER"});if(/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/.test(t)&&(t=t.trim(),t.split("@")[1].split(".").length>=2))return t.toLowerCase()}else throw new c(`"${e}" is required.`,{code:"INVALID_PARAMETER"});throw new c(`"${t}" is an invalid email.`,{code:"INVALID_PARAMETER"})}function yr(t){let e=typeof window<"u",n=(()=>{let s=e&&window.location.origin||null;return s&&s.slice(-1)==="/"&&(s=s.slice(0,-1)),s})(),r=s=>{if(typeof s=="string"){if(s==="*")return "*";{let i=s.trim();if(i[0]==="/"&&n){if(n.slice(0,5)==="file:")throw new c(`"${s}" is an invalid url. Relative URL does not work on local file system. Use full URL string.`,{code:"INVALID_PARAMETER"});i=n+i;}else if(i[0]==="."&&n){if(n.slice(0,5)==="file:")throw new c(`"${s}" is an invalid url. Relative URL does not work on local file system. Use full URL string.`,{code:"INVALID_PARAMETER"});let a=e?window.location.href.split("?")[0]:"";a.slice(-1)!=="/"&&(a+="/"),i=a+i.slice(1);}let o;try{o=new URL(i);}catch{throw new c(`"${s}" is an invalid url.`,{code:"INVALID_PARAMETER"})}if(o.protocol)return o.href}}throw new c(`"${s}" is an invalid url.`,{code:"INVALID_PARAMETER"})};return Array.isArray(t)?t.map(s=>r(s)):r(t)}function wr(t,e,n=[],r){let s=N(t,r),i=s.data;e.service="string",e.owner="string";let o={};for(let a in e)if(i&&typeof i=="object"&&!Array.isArray(i)&&i.hasOwnProperty(a))if(typeof i[a]=="function")o[a]=i[a];else try{o[a]=JSON.parse(JSON.stringify(i[a]));}catch{o[a]=i[a];}r?.precall&&r.precall({data:o,files:s?.files||[]});try{return fr(o,e,n)}catch(a){throw new c(a.message,{code:"INVALID_PARAMETER"})}}var g={UserId:hr,PhoneNumber:pr,Birthdate:mr,Password:_r,Email:br,Url:yr,Params:wr};var C=null;function Me(t){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"},n={};for(let r in t)if(r==="tkid"){let s=t[r].split("#");if(s.length===1){n.ticket_id=s[0];continue}n.ticket_id=s[1],n.consume_id=s[2],n.user_id=s[3];let i=s[2].slice(-4);if(n.is_test=i===":CHK",!t.stmp){let o=s[2].slice(0,-4);/^[0-9]+$/.test(o)?n.timestamp=parseInt(o,10):n.timestamp=j(s[2].slice(0,-4));}}else e[r]?n[e[r]]=t[r]:n[r]=t[r];return n}async function st(t){if(!t.ticket_id)throw new c("Ticket ID is required.",{code:"INVALID_PARAMETER"});if(!t.method)throw new c('Method is required. Should be either "GET" or "POST"',{code:"INVALID_PARAMETER"});let e=t.ticket_id;await this.__connection;let n=await E.bind(this)(`https://${this.service.slice(0,4)}.${this.customApiDomain}/auth/consume/${this.service}/${this.owner}/${e}`,t?.data||{},{method:t.method,auth:!!t?.auth});return Me(n)}async function ot(t,e){await this.__connection;let n=await E.bind(this)("ticket",Object.assign({exec:"list"},t||{}),{auth:true,fetchOptions:e});return n.list=n.list.map(Me),n}async function at(t,e){await this.__connection;let n=await E.bind(this)("ticket",Object.assign({exec:"consumed"},t||{}),{auth:true,fetchOptions:e});return n.list=n.list.map(Me),n}async function ct(t){return E.bind(this)("register-ticket",Object.assign({exec:"reg"},t),{auth:true})}async function lt(t){return E.bind(this)("register-ticket",Object.assign({exec:"unreg"},t),{auth:true})}async function oe(){if(await this.__connection,this.session){let t=Math.floor(Date.now()/1e3),n=this.session.getIdToken().getExpiration();if(n<t){this.log("request:requesting new token",null);try{await q.bind(this)().getSession({refreshToken:!0}),this.log("request:received new tokens",{exp:this.session?.idToken?.payload?.exp,currentTime:t,expiresIn:n-t,token:this.session?.accessToken?.jwtToken,refreshToken:this.session?.refreshToken?.token});}catch(r){throw this.log("request:new token error",r),new c("User login is required.",{code:"INVALID_REQUEST"})}}else this.log("request:tokens",{exp:this.session.idToken.payload.exp,currentTime:t,expiresIn:n-t,token:this.session.accessToken.jwtToken,refreshToken:this.session.refreshToken.token});return this.session?.idToken?.jwtToken}else throw this.log("request:no session",null),Y.bind(this)(),new c("User login is required.",{code:"INVALID_REQUEST"})}function it(t,e){return new Promise((n,r)=>{e.refreshSession(t.getRefreshToken(),(s,i)=>{this.log("getSession:refreshSessionCallback",{refreshErr:s,refreshedSession:i}),s?(Y.bind(this)(),r(s)):i.isValid()?n(i):(Y.bind(this)(),r(new c("Invalid session.",{code:"INVALID_REQUEST"})));});})}function q(){if(!this.userPool)throw new c("User pool is missing",{code:"INVALID_REQUEST"});let t=()=>{let i=C.getSignInUserSession().getIdToken().payload||null,o=ue(i);return this.log("normalized user attribute",o),this.__user=o,o},e=async i=>new Promise((o,a)=>{this.log("getSession:option",i);let{refreshToken:l=false,skipUserUpdateEventTrigger:u=false}=i||{};if(l&&u&&(u=false),C=this.userPool.getCurrentUser(),!C){this.log("getSession:cognitoUser",C),Y.bind(this)(),a(null);return}let f=d=>{let p=d.getIdToken().payload;if(this.log("getSession:respond:sessionAttribute",p),p["custom:service"]!==this.service)throw this.log("getSession:respond","invalid service, signing out"),Y.bind(this)(),new c("Invalid session.",{code:"INVALID_REQUEST"});return this.session=d,t(),u||this._runOnUserUpdateListeners(this.user),this.session};C.getSession((d,p)=>{if(this.log("getSession:getSessionCallback",{err:d,session:p}),!p){Y.bind(this)(),a(new c("Current session does not exist.",{code:"INVALID_REQUEST"}));return}if(d){it.bind(this)(p,C).then(_=>o(f(_))).catch(a);return}let w=Math.floor(Date.now()/1e3),h=p.getIdToken(),m=h.getExpiration(),I=m<w;if(this.log("getSession:currentTime",w),this.log("getSession:idTokenExp",m),this.log("getSession:isExpired",I),this.log("getSession:existingBearerToken",this.bearerToken),this.bearerToken=h.getJwtToken(),I||l||!p.isValid())it.bind(this)(p,C).then(_=>o(f(_))).catch(a);else try{o(f(p));}catch(_){a(_);}});}),n=(i,o)=>{let a=o||i.includes(this.service+"-")?i:this.service+"-"+M.hash(i);return {cognitoUser:new CognitoUser({Username:a,Pool:this.userPool}),cognitoUsername:a}};return {getSession:e,authenticateUser:(i,o,a=false,l=false)=>new Promise((u,f)=>{this.__request_signup_confirmation=null,this.__disabledAccount=null;let d=n(i,a),p=d.cognitoUsername,w=new AuthenticationDetails({Username:p,Password:o});d.cognitoUser.authenticateUser(w,{newPasswordRequired:(h,m)=>{this.__disabledAccount=null,this.__request_signup_confirmation=p,h["custom:signup_ticket"]==="PASS"||h["custom:signup_ticket"]==="MEMBER"||h["custom:signup_ticket"]==="OIDPASS"?d.cognitoUser.completeNewPasswordChallenge(o,{},{onSuccess:I=>{C=d.cognitoUser,e().then(_=>u(this.user));},onFailure:I=>{f(new c(I.message||"Failed to authenticate user.",{code:I.code}));}}):f(new c("User's signup confirmation is required.",{code:"SIGNUP_CONFIRMATION_NEEDED"}));},onSuccess:h=>e({skipUserUpdateEventTrigger:true}).then(m=>{this.__disabledAccount=null,this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user),u(this.user);}),onFailure:h=>{let m=[],{parsed:I,code:_}=Re(h),S=typeof h?.message=="string"?h.message:"";if(_==="NotAuthorizedException"?S.includes("User is disabled.")?(this.__disabledAccount=p,m=["This account is disabled.","USER_IS_DISABLED"]):l?m=["The account already exists.","ACCOUNT_EXISTS"]:m=["Incorrect username or password.","INCORRECT_USERNAME_OR_PASSWORD"]:_==="UserNotFoundException"?m=["Incorrect username or password.","INCORRECT_USERNAME_OR_PASSWORD"]:_==="UserNotConfirmedException"?(this.__request_signup_confirmation=p,m=["User's signup confirmation is required.","SIGNUP_CONFIRMATION_NEEDED"]):(_==="TooManyRequestsException"||_==="LimitExceededException")&&(m=["Too many attempts. Please try again later.","REQUEST_EXCEED"]),I.code==="SIGNUP_CONFIRMATION_NEEDED"&&(this.__request_signup_confirmation=p),m.length){let v=m[1],P=m[0];f(new c(P,{code:v,cause:h}));}else f(I);}});}),createCognitoUser:n,signup:(i,o,a)=>new Promise((l,u)=>{this.userPool.signUp(i,o,a,null,(f,d)=>{if(f){let{parsed:p,code:w}=Re(f),h=[];w==="UsernameExistsException"?h=["The account already exists.","EXISTS"]:w==="InvalidPasswordException"?h=["Invalid password. Password must be at least 6 characters.","INVALID_PARAMETER"]:w==="InvalidParameterException"?h=[p.message||"Invalid parameter.","INVALID_PARAMETER"]:w==="TooManyRequestsException"||w==="LimitExceededException"?h=["Too many attempts. Please try again later.","REQUEST_EXCEED"]:w==="CodeDeliveryFailureException"?h=["Failed to deliver verification code.","CODE_DELIVERY_FAILURE"]:w==="UserLambdaValidationException"&&(h=[p.message||"Signup validation failed.","INVALID_REQUEST"]),h.length?u(new c(h[0],{code:h[1],cause:f})):u(p);return}l(d);});})}}function Re(t){let e=typeof t?.code=="string"&&t.code.trim()?t.code.trim():"ERROR",r=((typeof t?.message=="string"?t.message:typeof t=="string"?t:"An error occurred.")||"An error occurred.").trim();r||(r="An error occurred.");let s=r.match(/#([A-Za-z0-9_]+)\s*:\s*([\s\S]+)/),i=s?.[1]?.trim()||e,o=s?.[2]?.trim()||r;return {parsed:new c(o,{code:i,cause:t}),code:e}}async function ut(t){await this.__authConnection;let e=t?.refreshToken||false;if(!e)return this.user;try{return await q.bind(this)().getSession(Object.assign({skipUserUpdateEventTrigger:!e,refreshToken:e},t)),this.user}catch{return null}}async function dt(t){await this.__connection,t=g.Params(t,{token:"string",id:"string",merge:o=>{if(o===void 0)return false;if(typeof o=="string")return [o];if(Array.isArray(o)){for(let a of o)if(typeof a!="string")throw new c('"merge" array items should be type: <string>.',{code:"INVALID_PARAMETER"})}if(typeof o!="boolean"&&!Array.isArray(o))throw new c('"merge" should be type: <boolean | string[]>.',{code:"INVALID_PARAMETER"});return o},template:o=>{if(typeof o!="object"||o===null)throw new c('"template" should be type: <object>.',{code:"INVALID_PARAMETER"});if(o.welcome!==void 0&&(typeof o.welcome!="string"||!o.welcome))throw new c('"template.welcome" should be a non-empty <string> (template message_id).',{code:"INVALID_PARAMETER"});return o}});let e={token:t.token,id:t.id,merge:t.merge};t.template?.welcome&&(e.template_welcome=t.template.welcome);let n=await E.bind(this)("openid-logger",e),r=n.logger.split("#"),s=this.service+"-"+r[0],i=r[1];return {userProfile:await q.bind(this)().authenticateUser(s,i,true,true),openid:n.openid}}function Pr(t){let e=typeof globalThis<"u"?globalThis:void 0;if(e?.Buffer)return e.Buffer.from(t,"base64").toString("utf8");if(typeof atob=="function"){let n=atob(t),r=new Uint8Array(n.length);for(let s=0;s<n.length;s++)r[s]=n.charCodeAt(s);return typeof TextDecoder<"u"?new TextDecoder().decode(r):n}throw new Error("No base64 decoder available in this environment")}function Sr(t){let e=t.split(".");if(e.length!==3)throw new Error("Invalid JWT format");let r=e[1].replace(/-/g,"+").replace(/_/g,"/"),s=Pr(r);return JSON.parse(s)}async function gt(t){await this.__authConnection,this.log("loginWithToken:params",t),t=g.Params(t,{idToken:"string",accessToken:"string",refreshToken:"string"},["idToken"]);let e=Sr(t.idToken);if(this.log("loginWithToken:idTokenPayload",e),e["custom:service"]!==this.service)throw new c("Token does not belong to this service.",{code:"INVALID_REQUEST"});let n=Math.floor(Date.now()/1e3);if(e.exp&&e.exp<n)throw new c("Token has expired.",{code:"INVALID_REQUEST"});if(this.__user=ue(e),this.session=null,t.accessToken&&t.refreshToken)try{if(this.session=new CognitoUserSession({IdToken:new CognitoIdToken({IdToken:t.idToken}),AccessToken:new CognitoAccessToken({AccessToken:t.accessToken}),RefreshToken:new CognitoRefreshToken({RefreshToken:t.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 r={Username:e["cognito:username"],Pool:this.userPool};this.log("loginWithToken:cognitoUserParams",r),C=new CognitoUser(r),C.setSignInUserSession(this.session),this.log("loginWithToken:cognitoUserRestored",{cognitoUserType:typeof C,cognitoUserKeys:Object.keys(C||{}),cognitoUser:C});}}catch(r){this.log("loginWithToken:err",r);try{this.log("loginWithToken:err:stringified",JSON.stringify(r));}catch{this.log("loginWithToken:err:stringifyFail",String(r));}try{let s=Object.keys(r||{}),i=Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(r||{}):[],o=Object.getOwnPropertyDescriptors?Object.getOwnPropertyDescriptors(r||{}):{};this.log("loginWithToken:createSessionError:allKeys",{keys:s,symbols:i,descriptors:o});}catch(s){this.log("loginWithToken:createSessionError:allKeysFail",String(s));}}return this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user),this.user}async function F(){return await this.__connection,this.__user?.service===this.service?this.__user?.owner===this.host:(await de.bind(this)(),false)}async function Y(t=false){let e=null;C&&(t?e=new Promise((r,s)=>{C.globalSignOut({onSuccess:i=>{this.log("globalSignOut:success",i),r(i);},onFailure:i=>{this.log("globalSignOut:error",i),s(i);}});}):C.signOut());let n={session:null,__startKeyHistory:{},__cached_requests:{},__user:null};e&&(e=await e);for(let r in n)this[r]=n[r];return this._runOnUserUpdateListeners(null),this._runOnLoginListeners(null),e}async function de(t){await this.__connection;let{data:e}=N(t);return await Y.bind(this)(e?.global),"SUCCESS: The user has been logged out."}async function ft(){if(!this.__request_signup_confirmation)throw new c("Least one login attempt is required.",{code:"INVALID_REQUEST"});return await E.bind(this)("confirm-signup",{username:this.__request_signup_confirmation})}async function ht(t=false){if(typeof t=="string")t=g.Url(t);else if(typeof t!="boolean")throw new c("Argument should be type: <boolean | string>.",{code:"INVALID_REQUEST"});if(!this.__disabledAccount)throw new c("Least one signin attempt of disabled account is required.",{code:"INVALID_REQUEST"});return await E.bind(this)("recover-account",{username:this.__disabledAccount,redirect:t}),"SUCCESS: Recovery e-mail has been sent."}async function Fe(t){let e=g.Params(t,{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 c('Least one of "username" or "email" is required.',{code:"INVALID_PARAMETER"});return await q.bind(this)().authenticateUser(e.username||e.email,e.password)}async function pt(t,e){await this.__authConnection;let n={username:"string",password:u=>g.Password(u),email:u=>g.Email(u),name:"string",address:u=>{if(!u)return "";if(typeof u=="string")return u;if(typeof u=="object")return JSON.stringify(u)},gender:"string",birthdate:u=>u?g.Birthdate(u):"",phone_number:u=>u?g.PhoneNumber(u):"",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:u=>u?g.Url(u):"",profile:u=>u?g.Url(u):"",family_name:"string",given_name:"string",middle_name:"string",nickname:"string",website:u=>u?g.Url(u):""},r=g.Params(t||{},n,["email","password"]);await de.bind(this)(),e=g.Params(e||{},{email_subscription:u=>{if(typeof u!="boolean")throw new c('"option.email_subscription" should be type: <boolean>.',{code:"INVALID_PARAMETER"});if(!e?.signup_confirmation)throw new c('"option.signup_confirmation" is required for email subscription.',{code:"INVALID_PARAMETER"});return u},signup_confirmation:u=>{let f=u;if(typeof u=="string")f=g.Url(u);else if(typeof u=="boolean")f=u;else throw new c('"option.signup_confirmation" should be type: <string | boolean>.',{code:"INVALID_PARAMETER"});if(f&&!r.email)throw new c('"email" is required for signup confirmation.',{code:"INVALID_PARAMETER"});return f},login:u=>{if(typeof u=="boolean"){if(e.signup_confirmation&&u)throw new c('"login" is not allowed when "option.signup_confirmation" is true.',{code:"INVALID_PARAMETER"});return u}throw new c('"option.login" should be type: boolean.',{code:"INVALID_PARAMETER"})},template:u=>{if(typeof u!="object"||u===null)throw new c('"option.template" should be type: <object>.',{code:"INVALID_PARAMETER"});if(u.signup_confirmation!==void 0){if(typeof u.signup_confirmation!="string"||!u.signup_confirmation)throw new c('"option.template.signup_confirmation" should be a non-empty <string> (template message_id).',{code:"INVALID_PARAMETER"});if(!e?.signup_confirmation)throw new c('"option.signup_confirmation" is required when "option.template.signup_confirmation" is set.',{code:"INVALID_PARAMETER"})}if(u.welcome!==void 0&&(typeof u.welcome!="string"||!u.welcome))throw new c('"option.template.welcome" should be a non-empty <string> (template message_id).',{code:"INVALID_PARAMETER"});return u}});let s=e?.login||false;if(r.signup_confirmation=e?.signup_confirmation||false,r.email_subscription=e?.email_subscription||false,r.email_public&&!r.signup_confirmation)throw new c('"option.signup_confirmation" should be true if "email_public" is set to true.',{code:"INVALID_PARAMETER"});r.service=this.service,r.owner=this.owner;let i=q.bind(this)().createCognitoUser(r.username||r.email);for(let u of ["email_public","address_public","gender_public","birthdate_public","phone_number_public"])r[u]=r[u]?"1":"0";r.access_group&&(r.access_group=r.access_group.toString());let o=(await E.bind(this)("signupkey",{username:i.cognitoUsername,signup_confirmation:typeof r.signup_confirmation=="boolean"?JSON.stringify(r.signup_confirmation):r.signup_confirmation,email_subscription:r.email_subscription,template_confirmation:e?.template?.signup_confirmation||"",template_welcome:e?.template?.welcome||""})).split(":"),a=o.slice(1).join(":"),l=[new CognitoUserAttribute({Name:"custom:signup",Value:o[0]}),new CognitoUserAttribute({Name:"locale",Value:a.split("#")[1]}),new CognitoUserAttribute({Name:"custom:signup_ticket",Value:a})];for(let u in n){let f=["email_public","address_public","gender_public","birthdate_public","phone_number_public","misc","service","owner"];r[u]!==""&&(u==="username"||u==="password"||u==="access_group"||(f.includes(u)?l.push(new CognitoUserAttribute({Name:"custom:"+u,Value:r[u]})):l.push(new CognitoUserAttribute({Name:u,Value:r[u]}))));}return await q.bind(this)().signup(i.cognitoUsername,r.password,l),r.signup_confirmation?(C=i.cognitoUser,this.__request_signup_confirmation=i.cognitoUsername,"SUCCESS: The account has been created. User's signup confirmation is required."):s?Fe.bind(this)({email:r.username||r.email,password:r.password}):"SUCCESS: The account has been created."}async function mt(){await this.__connection;let t=await E.bind(this)("remove-account",{disable:this.__user.user_id},{auth:true});return await de.bind(this)(),t}async function _t(t){await this.__connection;let e=g.Params(t,{email:s=>g.Email(s),code:["number","string"],new_password:s=>g.Password(s)},["email","code","new_password"]),n=e.code,r=e.new_password;return typeof n=="number"&&(n=n.toString()),new Promise(async(s,i)=>{q.bind(this)().createCognitoUser(e.email).cognitoUser.confirmPassword(n,r,{onSuccess:a=>{s("SUCCESS: New password has been set.");},onFailure:a=>{i(new c(a?.message||"Failed to reset password.",{code:a?.code||"ERROR",cause:a}));}});})}async function bt(t,e,n){await this.__connection;let r;if(!C)throw new c("The user has to be logged in.",{code:"INVALID_REQUEST"});if(t==="email"||t==="phone_number"){if(!this.__user.hasOwnProperty(t))throw new c(`No ${t==="email"?"e-mail":"phone number"} to verify`,{code:"INVALID_REQUEST"});if(this.__user?.[`${t}_verified`])return `SUCCESS: "${t}" is verified.`;r=(e?g.Params(e,{code:"string"}):{}).code||"";}else return;let s,i=n?.template?.verification;if(i!==void 0){if(typeof i!="string"||!i)throw new c('"template.verification" should be a non-empty <string> (template message_id).',{code:"INVALID_PARAMETER"});s={template_verification:i};}return new Promise((o,a)=>{let l={onSuccess:u=>{r?q.bind(this)().getSession({refreshToken:true}).then(()=>{this.__user&&(this.__user[t+"_verified"]=true),o(`SUCCESS: "${t}" is verified.`);}).catch(f=>{a(f);}):o("SUCCESS: Verification code has been sent.");},onFailure:u=>{a(new c(u.message||"Failed to request verification code.",{code:u?.code}));}};r?C?.verifyAttribute(t,r,l):(l.inputVerificationCode=null,C?.getAttributeVerificationCode(t,l,s));})}function yt(t,e){return bt.bind(this)("phone_number",t,e)}function wt(t,e){return bt.bind(this)("email",t,e)}async function Et(t,e){await this.__connection;let n=g.Params(t,{email:i=>g.Email(i)},["email"]),r,s=e?.template?.verification;if(s!==void 0){if(typeof s!="string"||!s)throw new c('"template.verification" should be a non-empty <string> (template message_id).',{code:"INVALID_PARAMETER"});r={template_verification:s};}return new Promise(async(i,o)=>{q.bind(this)().createCognitoUser(n.email).cognitoUser.forgotPassword({onSuccess:l=>{i("SUCCESS: Verification code has been sent.");},onFailure:l=>{let{parsed:u,code:f}=Re(l),d={UserNotFoundException:"NOT_EXISTS",InvalidParameterException:"INVALID_PARAMETER",NotAuthorizedException:"INVALID_REQUEST",LimitExceededException:"REQUEST_EXCEED",TooManyRequestsException:"REQUEST_EXCEED",CodeDeliveryFailureException:"CODE_DELIVERY_FAILURE"}[f]||u.code||f||"ERROR";o(new c(u.message,{code:d,cause:l}));}},r);})}async function Rt(t){if(await this.__connection,!this.session)throw new c("User login is required.",{code:"INVALID_REQUEST"});let e=g.Params(t,{current_password:"string",new_password:"string"});if(!e?.current_password)throw new c('"current_password" is required to change password.',{code:"INVALID_PARAMETER"});if(!e?.new_password)throw new c('"new_password" is required to change password.',{code:"INVALID_PARAMETER"});return g.Password(e.current_password),g.Password(e.new_password),new Promise((n,r)=>{C.changePassword(e.current_password,e.new_password,(s,i)=>{if(s){if(s?.code==="InvalidParameterException")r(new c("Invalid password parameter.",{code:"INVALID_PARAMETER"}));else if(s?.code==="NotAuthorizedException")r(new c("Incorrect password.",{code:"INVALID_REQUEST"}));else if(s?.code==="TooManyRequestsException"||s?.code==="LimitExceededException")r(new c("Too many attempts. Please try again later.",{code:"REQUEST_EXCEED"}));else {let{parsed:o}=Re(s);r(o);}return}n("SUCCESS: Password has been changed.");});})}async function At(t){if(await this.__connection,!this.session)throw new c("User login is required.",{code:"INVALID_REQUEST"});let e=g.Params(t||{},{user_id:s=>g.UserId(s),email:s=>g.Email(s),address:s=>{if(!s)return "";if(typeof s=="string")return s;if(typeof s=="object")return JSON.stringify(s)},name:"string",gender:"string",birthdate:s=>s?g.Birthdate(s):"",phone_number:s=>s?g.PhoneNumber(s):"",email_public:"boolean",phone_number_public:"boolean",address_public:"boolean",gender_public:"boolean",birthdate_public:"boolean",misc:"string",picture:s=>s?g.Url(s):"",profile:s=>s?g.Url(s):"",family_name:"string",given_name:"string",middle_name:"string",nickname:"string",website:s=>s?g.Url(s):""});if(e&&typeof e=="object"&&!Object.keys(e).length)return this.user;e.email&&(e.preferred_username=this.service+"-"+M.hash(e.email));let n=[["email_public","email_verified","User's e-mail should be verified to set"],["phone_number_public","phone_number_verified","User's phone number should be verified to set"]];if(this.__user){for(let s of n)if(e[s[0]]&&!this.__user[s[1]])throw new c(`${s[2]} "${s[0]}" to true.`,{code:"INVALID_REQUEST"})}let r=[];for(let s in e){if(e[s]===this.user[s]){r.push(s);continue}if(["email_public","phone_number_public","address_public","gender_public","birthdate_public","misc"].includes(s)){let o=e[s];typeof o=="boolean"&&(o=o?"1":"0"),e["custom:"+s]=o,r.push(s);}}for(let s of r)delete e[s];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 s=[];for(let i in e)s.push(new CognitoUserAttribute({Name:i,Value:e[i]}));return await new Promise((i,o)=>{C?.updateAttributes(s,(a,l)=>{a&&o([a?.code||a?.name,a?.message||"Failed to update user settings."]),i(l);});}),await q.bind(this)().getSession({refreshToken:true}),this.user}return this.user}async function It(t,e){t=N(t).data,t||(t={searchFor:"timestamp",condition:">",value:0},e||(e={}),e.ascending=false),await this.__connection;let n={user_id:s=>Array.isArray(s)?s.map(i=>g.UserId(i)):g.UserId(s),email:"string",phone_number:"string",locale:s=>{if(typeof s!="string"||typeof s=="string"&&s.length>5)throw new c('Value of "locale" should be a country code.',{code:"INVALID_PARAMETER"});return s},name:"string",address:"string",gender:"string",birthdate:s=>g.Birthdate(s),subscribers:"number",timestamp:"number",access_group:"number",approved:"string"},r=["searchFor","value"];if(t=g.Params(t,{searchFor:["user_id","name","email","phone_number","address","gender","birthdate","locale","subscribers","timestamp","access_group","approved"],condition:[">",">=","=","<","<=","gt","gte","eq","lt","lte",()=>"="],value:s=>{let i=n[t.searchFor];if(typeof i=="function")return i(s);if(typeof s!==i)throw new c(`Value does not match the type of "${t.searchFor}" index.`,{code:"INVALID_PARAMETER"});return s},range:s=>{let i=n[t.searchFor];if(typeof i=="function")return i(s);if(typeof s!==i)throw new c(`Range does not match the type of "${t.searchFor}" index.`,{code:"INVALID_PARAMETER"});return s}},r),t?.condition&&t?.condition!=="="&&t.hasOwnProperty("range"))throw new c("Conditions does not apply on range search.",{code:"INVALID_PARAMETER"});if(t.searchFor==="user_id"&&(t.condition!=="="||t.range))throw new c(`Conditions are not allowed on "${t.searchFor}"`,{code:"INVALID_PARAMETER"});if(typeof t?.value=="string"&&!t?.value)throw new c("Value should not be an empty string.",{code:"INVALID_PARAMETER"});if(typeof t?.searchFor=="string"&&!t?.searchFor)throw new c('"searchFor" should not be an empty string.',{code:"INVALID_PARAMETER"});return E.bind(this)("get-users",t,{auth:true,fetchOptions:e})}async function Tt(t){await this.__connection;let e=await E.bind(this)("last-verified-email",t,{auth:true});return e.includes("SUCCESS")?(await q.bind(this)().getSession({refreshToken:true}),this.user):e}async function Pt(t){return await this.__connection,t=g.Params(t,{username:g.Email,redirect:g.Url},["username"]),await E.bind(this)("request-username-change",t,{auth:true})}var ae=null,kt=typeof SubmitEvent<"u",vr=typeof HTMLFormElement<"u",fe=V(),qe=0;function vt(t){if(!t)return null;let e=Number(t);if(Number.isFinite(e))return Math.max(0,e*1e3);let n=Date.parse(t);return Number.isNaN(n)?null:Math.max(0,n-Date.now())}function Ve(t,e){return e>0?t/e*100:0}var St=t=>{let{auth:e,type:n,endpoints:r}=t,s=r[0],i=r[1];if(qe++,n==="admin"){let o=Object.entries(s).filter(([a,l])=>a.includes(e?"_private":"_public")&&a!=="get_users_private"&&a!=="service_public"&&typeof l=="string").map(([,a])=>a);if(!o.length)throw new c("No available admin gateways.",{code:"INVALID_REQUEST"});return o[qe%o.length]}if(n==="record"){let o=Object.entries(i).filter(([a,l])=>a.includes(e?"record_private":"record_public")&&typeof l=="string").map(([,a])=>a);if(!o.length)throw new c("No available record gateways.",{code:"INVALID_REQUEST"});return o[qe%o.length]}throw new c("Invalid gateway type.",{code:"INVALID_REQUEST"})};async function xr(t,e){let n=await Promise.all([this.admin_endpoint,this.record_endpoint]),r=n[0],s=n[1],i=t.split("?"),o=i.length>1?"?"+i[1]:"";switch(t=i[0],t){case "get-users":return r.get_users_private+t+o;case "service":return r.service_public+t+o;case "get-newsletters":case "get-public-newsletters":case "subscribe-newsletter":case "subscribe-public-newsletter":case "signupkey":case "admin-newsletter-request":case "admin-signup":case "confirm-signup":case "openid-logger":case "block-account":case "admin-edit-profile":case "remove-account":case "post-secure":case "recover-account":case "mock":case "grant-access":case "last-verified-email":case "ticket":case "register-ticket":case "get-newsletter-subscription":case "request-username-change":case "send-inquiry":case "register-newsletter-group":case "newsletter-group-endpoint":case "invitation-list":case "csr":case "csr-poll":case "csr-cancel":return St.bind(this)({auth:e,type:"admin",endpoints:n})+t+o;case "post-record":return (e?s.post_private:s.post_public)+t+o;case "get-records":return (e?s.get_private:s.get_public)+t+o;case "del-files":case "del-records":return s.del_private+t+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 "extract-file-text":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 St.bind(this)({auth:e,type:"record",endpoints:n})+t+o;default:return g.Url(t)+o}}var ge={};function xt(){ae&&(ae.terminate(),ae=null);}async function E(t,e=null,n,r){this.log("request",{url:t,data:e,options:n,_etc:r||{}}),n=n||{};let{auth:s=false,method:i="post",bypassAwaitConnection:o=false}=n;i=i.toUpperCase();let a=null,l=e?.service||this.service,u=e?.owner||this.owner,f=null,d=await xr.bind(this)(t,!!s);if(!o&&(a=await this.__connection,!a))throw new c("Invalid connection. The service could have been disabled, or has a restricted CORS.",{code:"INVALID_REQUEST"});let p=n?.tokenHeaders?.idToken===true;(s||p)&&(f=await oe.bind(this)());let w={},{fetchMore:h=false,progress:m}=n?.fetchOptions||{};if(n?.fetchOptions&&Object.keys(n.fetchOptions).length){for(let k of ["limit","startKey","ascending"])if(n.fetchOptions.hasOwnProperty(k)){if(k==="startKey"&&n.fetchOptions[k]===null)continue;w[k]=n.fetchOptions[k];}w=g.Params(w,{limit:k=>{if(typeof k!="number")throw new c("Fetch limit should be a number.",{code:"INVALID_REQUEST"});if(k>1e3)throw new c("Fetch limit should be below 1000.",{code:"INVALID_REQUEST"});return k},startKey:k=>k,ascending:"boolean"});}let I=r?.ignoreService?{}:{service:l,owner:u};Object.assign(I,w),e=N(e).data,e?e&&typeof e=="object"&&(e=Object.assign(I,e)):e=I;let _=`${i}:${s?"auth":"public"}:${t}`,S=(()=>{if(e&&typeof e=="object"&&Object.keys(e).length&&!(fe&&e instanceof FormData)){let k=function(D){return typeof D=="object"&&D!==null?Object.keys(D).sort().reduce((U,L)=>(typeof D[L]=="object"&&D[L]!==null?U[L]=k(D[L]):U[L]=D[L],U),{}):D};return M.hash(_+"/"+JSON.stringify(k(e)))}return M.hash(_+"/"+l)})(),{requestKey:v,requestKeyWithStartKey:P}=Dr.bind(this)({params:e,url:t,fetchMore:h,hashedParams:S});if(!v||v&&typeof v=="object")return v;if(this.log("requestKey",P),typeof P=="string"&&ge[P]instanceof Promise)return this.log("request:returning pending",P),ge[P];let x={Accept:"*/*"};if(Object.prototype.hasOwnProperty.call(n,"contentType")&&n.contentType!==void 0){let k=n.contentType===null?"application/x-www-form-urlencoded":n.contentType;k&&(x["Content-Type"]=k);}else x["Content-Type"]="application/json";if(f&&(x.Authorization=f),n?.tokenHeaders){let k=(L,Wn)=>typeof L=="string"?L:L===true?Wn:null,D=k(n.tokenHeaders.accessToken,this.session?.accessToken?.jwtToken||null),U=k(n.tokenHeaders.idToken,this.bearerToken||this.session?.idToken?.jwtToken||f||null);D&&(x["X-Access-Token"]=D),U&&(x["X-Id-Token"]=U);}let Ne={public_identifier:this.__public_identifier,service:l,owner:u};x["Content-Meta"]=JSON.stringify(Ne);let $={headers:x};if(n?.responseType&&($.responseType=n.responseType),i==="GET"){if(e){let k=[];if(fe&&e instanceof FormData?k=Array.from(e.entries()).map(([D,U])=>{let L=typeof U=="string"?U:U.name;return encodeURIComponent(D)+"="+encodeURIComponent(L)}):k=Object.keys(e).map(D=>{let U=e[D];return typeof U!="string"&&(U=JSON.stringify(U)),encodeURIComponent(D)+"="+encodeURIComponent(U)}),k.length){let D=d.includes("?")?d.endsWith("?")||d.endsWith("&")?"":"&":"?";d+=D+k.join("&");}}$.body=null;}else if(fe&&e instanceof FormData)$.body=e;else if(x["Content-Type"]==="application/x-www-form-urlencoded"&&e&&typeof e=="object"){let k=new URLSearchParams;for(let D of Object.keys(e)){let U=e[D];k.append(D,typeof U=="string"?U:JSON.stringify(U));}$.body=k.toString();}else typeof e=="string"?$.body=e:$.body=e?JSON.stringify(e):null;if($.method=i,ae===null){let k={batchSize:this.requestBatchSize,breakWhenError:false,onProgress:D=>{this.onBatchProcess.forEach(U=>U(D));}};ae=new ln(k);}return this.log("request-opt",$),new Promise((k,D)=>{ae.add([async()=>{let U=Dt.bind(this)(d,$,m);ge[P]=U;try{let L=Ur.bind(this)({hashedParam:v,requestKeyWithStartKey:P,url:t,fetched:await U});return delete ge[P],this.log("request:end",L),k(L),L}catch(L){throw delete ge[P],this.log("request:err",L),D(L),L}}]);})}function Dr(t){let{params:e={},url:n,fetchMore:r=false,hashedParams:s}=t||{};if(e.startKey){if(!(typeof e.startKey=="object"&&Object.keys(e.startKey).length)&&e.startKey!=="start"&&e.startKey!=="end")throw new c(`"${e.startKey}" is invalid startKey key.`,{code:"INVALID_PARAMETER"});e.startKey==="start"&&(r=false,delete e.startKey);}if(!r){if(this.__cached_requests?.[n]?.[s]&&delete this.__cached_requests[n][s],this.__startKeyHistory?.[n]?.[s]){if(Array.isArray(this.__startKeyHistory[n][s])&&this.__startKeyHistory[n][s].length)for(let l of this.__startKeyHistory[n][s]){let u=s+M.hash(l);this.__cached_requests?.[n]&&this.__cached_requests?.[n]?.[u]&&delete this.__cached_requests[n][u];}delete this.__startKeyHistory[n][s];}return {requestKeyWithStartKey:s,requestKey:s}}if(!Array.isArray(this.__startKeyHistory?.[n]?.[s]))return {requestKeyWithStartKey:s,requestKey:s};let i=this.__startKeyHistory[n][s],o=i[i.length-1],a=s;if(o){if(o==="end")return {requestKey:{list:[],startKey:"end",endOfList:true,startKeyHistory:i},requestKeyWithStartKey:a};a+=M.hash(o),e.startKey=JSON.parse(o);}return this.__cached_requests?.[n]?.[a]?{requestKey:this.__cached_requests[n][a],requestKeyWithStartKey:a}:{requestKeyWithStartKey:a,requestKey:s}}function Dt(t,e,n){return new Promise((r,s)=>{let i=new XMLHttpRequest;i.open(e.method||"GET",t);for(var o in e.headers||{})i.setRequestHeader(o,e.headers[o]);e.responseType&&(i.responseType=e.responseType),i.onload=()=>{if(i.status<400)if(e.responseType=="json"||e.responseType=="blob")r(i.response);else {let a=i.responseText;try{a=JSON.parse(a);}catch{}r(a);}else if(i.status===429){let a=i.getResponseHeader("Retry-After"),l=vt(a);l!==null?setTimeout(()=>{Dt(t,e,n).then(r,s);},l):s("Too many requests");}else {let a=i.status,l=["INVALID_CORS","INVALID_REQUEST","SERVICE_DISABLED","INVALID_PARAMETER","ERROR","EXISTS","NOT_EXISTS"],u=e.responseType=="blob"?i.response:i.responseText;try{u=JSON.parse(u);}catch{}if(typeof u=="string"){let f=u.split(":"),d=f.splice(0,1)[0].trim(),p=f.join(":").trim();s(new c(p||u,{code:l.includes(d)?d:"ERROR"}));}else if(typeof u=="object"&&u?.message){let f=u?.code||(a?a.toString():null)||"ERROR",d=u.message,p=u?.cause;typeof d=="string"&&(d=d.trim()),s(new c(d,{cause:p,code:f}));}else s(u);}},i.onerror=()=>s("Network error"),i.onabort=()=>s("Aborted"),i.ontimeout=()=>s("Timeout"),typeof n=="function"&&(i.onprogress=a=>{n({status:"download",progress:Ve(a.loaded,a.total),loaded:a.loaded,total:a.total,abort:()=>i.abort()});},i.upload&&(i.upload.onprogress=a=>{n({status:"upload",progress:Ve(a.loaded,a.total),loaded:a.loaded,total:a.total,abort:()=>i.abort()});})),i.send(e.body);})}function Ur(t){let{hashedParam:e,requestKeyWithStartKey:n,url:r,fetched:s}=t;if(!s?.startKey)return s;this.__startKeyHistory.hasOwnProperty(r)||(this.__startKeyHistory[r]={}),this.__startKeyHistory[r].hasOwnProperty(e)||(this.__startKeyHistory[r][e]=[]);let i=s.startKey==="end"?"end":JSON.stringify(s.startKey);return this.__startKeyHistory[r][e].includes(i)||this.__startKeyHistory[r][e].push(i),this.__cached_requests?.[r]||(this.__cached_requests[r]={}),this.__cached_requests[r][n]=s,Object.assign({startKeyHistory:this.__startKeyHistory[r][e]},s)}async function Ie(t,e){await this.__connection;let{record_id:n,service:r=this.service,progress:s}=e;if(!n)throw new c('"record_id" is required.',{code:"INVALID_PARAMETER"});if(kt&&t instanceof SubmitEvent&&(t=t.target),vr&&t instanceof HTMLFormElement&&(t=new FormData(t)),!fe||!(t instanceof FormData))throw new c('"fileList" should be a FormData or HTMLFormElement.',{code:"INVALID_PARAMETER"});let o={reserved_key:re(),service:r,request:"post"};e?.record_id&&(o.id=e.record_id);let a,l=(w,h,m)=>new Promise((I,_)=>{a=new XMLHttpRequest,a.open("POST",w),a.onload=()=>{let S=a.responseText;try{S=JSON.parse(S);}catch{}if(a.status>=200&&a.status<300)I(S);else if(a.status===429){let v=a.getResponseHeader("Retry-After"),P=vt(v);P!==null?setTimeout(()=>{l(w,h,m).then(I,_);},P):_("Too many requests");}else _(S);},a.onerror=()=>_("Network error"),a.onabort=()=>_("Aborted"),a.ontimeout=()=>_("Timeout"),a.upload&&typeof m=="function"&&(a.upload.onprogress=m),a.send(h);});function u(w){let h="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";if(w===0)return h[0];let m="";for(;w>0;)m=h[w%62]+m,w=Math.floor(w/62);return m}let f=[],d=[],p=[];for(let[w,h]of t.entries()){if(!(h instanceof File))continue;let m=Object.assign({key:w+"/"+h.name,sizeKey:u(h.size),contentType:h.type||null},o),{fields:I=null,url:_,cdn:S}=await E.bind(this)("get-signed-url",m,{auth:!!this.__user});p.push(S);let v=new FormData;for(let P in I)v.append(P,I[P]);v.append("file",h);try{await l(_,v,typeof s=="function"?P=>s({status:"upload",progress:Ve(P.loaded,P.total),currentFile:h,completed:f,failed:d,loaded:P.loaded,total:P.total,abort:()=>a.abort()}):null),f.push(h);}catch{d.push(h);}}return {completed:f,failed:d,bin_endpoints:p}}var Ae={};function A(t){let{preventMultipleCalls:e=false}=t||{};return function(n,r,s){let i=s.value;s.value=function(...o){let a=o[0],l=true,u=null,f="",d={},p=false;if(kt&&a instanceof SubmitEvent){a.preventDefault();let _=window.location.href;u=a.target;let S=new URL(u.action);f=S.href;let v=f?f.match(/(?<=\{).*?(?=\})/g):"";if(v)for(let P of v){if(!P)continue;let x=u.querySelector(`[name="${P}"]`);if(x)if(x.type==="file")for(let H=0;H<=x.files.length-1;H++)x.files[H]&&(d[P]||(d[P]=[]),d[P].push(new Promise((Ne,$)=>{let k=new FileReader;k.onload=function(){Ne(k.result);},k.readAsDataURL(x.files[H]),k.onerror=$;})));else f=f.replace(`{${P}}`,x.value);}u.getAttribute("action")===null?l=false:p=S.href===_;}let w=async _=>{if(f)for(let S in d)d[S].length&&(f=f.replace(`{${S}}`,(await Promise.all(d[S])).join(",")));return u&&l&&(window.sessionStorage.setItem(`${this.service}:${M.hash(f)}`,JSON.stringify(_)),p?window.location.replace(f):window.location.href=f),_},h,m=_=>{throw _ instanceof c?_.name=r+"()":_=_ instanceof Error?_:new c(_,{name:r+"()"}),_},I=async()=>{try{if(h=i.bind(this)(...o),h instanceof Promise){let _=await h;return w(_)}return w(h)}catch(_){throw m(_)}};if(e){let _=`${r}:${this?.__public_identifier||""}:${this?.service||""}:${this?.owner||""}`;return Ae?.[_]||(Ae[_]=I().finally(()=>{delete Ae[_];})),Ae[_]}return I()};}}async function Ut(){await this.__connection;let t=`${this.service}:${M.hash(window.location.href.split("?")[0])}`,e=window.sessionStorage.getItem(t);if(window.sessionStorage.removeItem(t),e!==null){try{e=JSON.parse(e);}catch{}return e}return null}var Nr=128,Cr=64,Lr=128,Or=256,Mr="\u{10FFFF}",Fr=/[\u0000-\u001F\u007F]|\u{10FFFF}/u,qr=/[\/!*#]/,Vr={"/":"%2F","!":"%21","*":"%2A","#":"%23"},$r={"%2F":"/","%21":"!","%2A":"*","%23":"#"};function jr(t){return t.replace(/%/g,"%25").replace(/[\/!*#]/g,n=>Vr[n]||n)}function B(t){return typeof t!="string"?t:t.replace(/%(2F|21|2A|23)/gi,n=>{let r=n.toUpperCase();return $r[r]||n}).replace(/%25/gi,"%")}function ee(t,e,n={}){let{allowEmpty:r=false,maxLength:s,blockKeyDelimiters:i=false,disallowLeadingDollar:o=false,onlyAlphanumeric:a=false}=n;if(typeof t!="string")throw new c(`"${e}" should be type: <string>.`,{code:"INVALID_PARAMETER"});if(a&&/[^a-zA-Z0-9]/.test(t))throw new c(`"${e}" should only contain alphanumeric characters.`,{code:"INVALID_PARAMETER"});if(!r&&t.length===0)throw new c(`"${e}" is required.`,{code:"INVALID_PARAMETER"});if(s&&t.length>s)throw new c(`"${e}" should be <= ${s} characters.`,{code:"INVALID_PARAMETER"});if(Fr.test(t)||t.includes(Mr))throw new c(`"${e}" cannot include control characters or unsupported sentinel characters.`,{code:"INVALID_PARAMETER"});if(i&&qr.test(t)&&(t=jr(t)),o&&t.startsWith("$"))throw new c(`"${e}" cannot start with "$".`,{code:"INVALID_PARAMETER"});return t}function $e(t,e="table.name"){return ee(t,e,{allowEmpty:false,maxLength:Nr,blockKeyDelimiters:true})}function je(t,e="tag"){return ee(t,e,{allowEmpty:false,maxLength:Cr,blockKeyDelimiters:true})}function he(t,e="index.name"){return ee(t,e,{allowEmpty:false,maxLength:Lr,blockKeyDelimiters:true,disallowLeadingDollar:true})}function Nt(t,e="index.value"){return ee(t,e,{allowEmpty:true,maxLength:Or})}function Ct(t){if(!t.record_id&&!t.unique_id)return null;let e={};return t?.service&&(e.service=t.service),t?.owner&&(e.owner=t.owner),t?.record_id?e.record_id=ee(t.record_id,"record_id",{allowEmpty:false,onlyAlphanumeric:true}):t?.unique_id&&(e.unique_id=t.unique_id),e}function Be(t){if(t===void 0)return 0;if(typeof t=="number"){if(t>99||t<0)throw new c('"table.access_group" value should be within a range of 0 ~ 99.',{code:"INVALID_REQUEST"})}else if(typeof t=="string"){if(t={private:"private",public:0,authorized:1,admin:99}[t],t===void 0)throw new c('"table.access_group" is invalid.',{code:"INVALID_PARAMETER"})}else throw new c('"table.access_group" should be type: <number | string>.',{code:"INVALID_PARAMETER"});if(!this.__user&&t)throw new c("Unsigned users have no access to records with access group.",{code:"INVALID_REQUEST"});return t}var Te=4503599627370496;function Pe(t){if(typeof t=="number"){if(t>Te||t<-Te)throw new c(`Number value should be within range -${Te} ~ +${Te}`,{code:"INVALID_PARAMETER"});return t}if(typeof t=="boolean")return t;if(typeof t=="string")return Nt(t,"index.value");throw new c('"index.value" should be type: <number | boolean | string>.',{code:"INVALID_PARAMETER"})}function Lt(t,e){if(!e.index||!("value"in e.index))throw new c('"index.value" is required.',{code:"INVALID_PARAMETER"});if(e.index.name==="$record_id")throw new c(`Cannot do "index.range" on ${e.index.name}`,{code:"INVALID_PARAMETER"});if(typeof e.index.value!=typeof t)throw new c('"index.range" type should match the type of "index.value".',{code:"INVALID_PARAMETER"});return typeof t=="string"?Nt(t,"index.range"):t}var Se={};async function ce(t,e){let n={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:{}},r=false;function s(o){let a=o=="**"?"private":parseInt(o);return a=a==0?"public":a==1?"authorized":a==99?"admin":a,a}let i={ip:o=>{let a=o.split("#"),l=a[0];a.length>1&&(n.unique_id=a.slice(1).join("#")),l.slice(-1)==="R"?(n.readonly=true,l=l.slice(0,-1)):n.readonly=false,/^\d{1,3}-\d{1,3}-\d{1,3}-\d{1,3}$/.test(l)&&(l=l.split("-").join("."),r=true),n.ip=l;},rec:o=>{if(!o)return;n.record_id=o;let a=o.substring(0,o.length-9),l=j(a);n.uploaded=l;},usr:o=>{n.user_id=o;},tbl:o=>{if(o&&!n.table.name){let a=o.split("/");n.table.name=B(a[0]),n.table.access_group=s(a[2]),a?.[3]&&(n.table.subscription.is_subscription_record=true);}},usr_tbl:o=>{let a=o.split("/");n.user_id||(n.user_id=a[0]),n.table.name||(n.table.name=B(a[1]),n.table.access_group=s(a[3]),a?.[4]&&(n.table.subscription.is_subscription_record=true));},idx:o=>{if(!o)return;let a=o.split("!"),l=B(a.splice(0,1)[0]),u=Br("!"+a.join("!"));typeof u=="string"&&(u=B(u)),n.index={name:l,value:u};},ref:o=>{o&&(n.reference=o.split("/")[0]);},tags:o=>{n.tags=Array.isArray(o)?o.map(a=>B(a)):o;},upd:o=>{n.updated=o;},acpt_mrf:o=>{n.source.prevent_multiple_referencing=!o;},ref_limt:o=>{n.source.referencing_limit=o;},rfd:o=>{n.referenced_count=o;},bin:async o=>{let a={},l=n?.reference||null;if(Array.isArray(o)){let u=await Promise.all(o.map(async f=>{try{let d=f.split("/").slice(3).join("/"),p=d.split("/");if(p.length<12)return null;let w=decodeURIComponent(p[p.length-1]),h=decodeURIComponent(p[10]),m=p[9],I=p[8],_=s(p[6]),S=f;if(_!=="public")try{S=await ke.bind(this)(f,{dataType:"endpoint",_ref:l});}catch(P){console.error("Error getting signed url for private file:",P),S=f;}let v={access_group:_,filename:w,url:S,path:d,size:j(m),uploaded:j(I),getFile:(P,x)=>{let H={dataType:P||"download",progress:x,_ref:l,_update:v};return ke.bind(this)(S,H)}};return {pathKey:h,obj:v}}catch{return null}}));for(let f of u)if(f){if(a[f.pathKey]){a[f.pathKey].push(f.obj);continue}a[f.pathKey]=[f.obj];}}n.bin=a;},prv_acs:o=>{for(let a in o)["notify_subscribers","upload_to_feed","feed_referencing_records","notify_referencing_records"].includes(a)?n.table.subscription[a]=o[a]:n.source[a]=o[a];},data:o=>{let a=o;o==="!D%{}"?a={}:o==="!L%[]"&&(a=[]),n.data=a;}};if(t.record_id)return t;for(let o in i)if(t.hasOwnProperty(o)){let a=i[o](t[o]);a instanceof Promise&&await a;}return r&&(n.user_id="anonymous:"+n.user_id),n}function Br(t){let e=t.substring(3);switch(t.substring(0,3)){case "!S%":return e;case "!N%":let r=e.split("."),s=Number(r[0])-4503599627370496;return r.length===1?s:parseFloat(s.toString()+"."+r[1]);case "!B%":return e==="1";case "!L%":case "!D%":try{return JSON.parse(e)}catch{throw new c("Value parse error.",{code:"PARSE_ERROR"})}default:return t}}async function Ot(t){let{endpoints:e}=t;if(typeof e=="string"&&(e=[e]),!Array.isArray(e))throw new c('"endpoints" should be type: array | string.',{code:"INVALID_PARAMETER"});let n=await E.bind(this)("del-files",{endpoints:e,storage:"records"},{auth:true,method:"post"}),r=[];for(let s in n)r.push(ce.bind(this)(n[s]));return Promise.all(r)}async function ke(t,e){if(typeof t!="string")throw new c('"url" should be type: string.',{code:"INVALID_PARAMETER"});let n=t.split("?"),r=n.shift()||"",s=n.length?"?"+n.join("?"):"",i=g.Url(r);t=i+s;let o=false,a=i.split("/"),u=a[2].split("."),f=null;u.length===3&&u[1]==="skapi"&&(f=u[0],o=true);let d=a.slice(3),p=false;if(!o&&(d[0]==="auth"||d[0]==="publ"))try{g.UserId(d[2]),g.UserId(d[3]),p=d[0]=="auth",o=!0;}catch{throw new c("Invalid file url.",{code:"INVALID_PARAMETER"})}let w=f?null:d[1];if(e=g.Params(e,{expires:["number",()=>0],dataType:["base64","blob","endpoint","text","info",()=>"download"],progress:["function","undefined",null],_ref:[null,"string"],_update:_=>_}),e?.dataType==="info")return {url:t,filename:d[d.length-1],fileKey:d[d.length-2],access_group:d[6]==="**"?"private":d[6]==="01"?"authorized":d[6]==="00"?"public":parseInt(d[6]),uploader:d[3],record_id:d[4]==="records"?d[5]:"N/A",filesize:j(d[9]),uploaded:j(d[8])};let h=t.split("/").slice(-1)[0],m=e.expires;if(m){if(!o)throw new c("Expires option can only be used on skapi cdn endpoints.",{code:"INVALID_PARAMETER"});if(m<0)throw new c('"config.expires" should be > 0. (seconds)',{code:"INVALID_PARAMETER"});let _={request:f?"get-host":"get",id:f||d[5],key:t,expires:m};w&&(_.service=w),t=(await E.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 q.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(x){throw this.log("getFile:new token error",x),new c("User login is required.",{code:"INVALID_REQUEST"})}}let S=this.bearerToken||this.session?.idToken?.jwtToken;if(!S||!this.user?.user_id)throw new c("User login is required.",{code:"INVALID_REQUEST"});t+=`${t.includes("?")?"&":"?"}t=${encodeURIComponent(S)}`;let v=d[6]==="**"?"**":parseInt(d[6]),P=this.user?.access_group??-1;if(this.user.user_id!==d[3]&&(v==="**"||P<v)){let x=d[5];if(this.__private_access_key[x]&&typeof this.__private_access_key[x]=="string")t+=`&p=${encodeURIComponent(this.__private_access_key[x])}`;else if(this.owner!==this.host)try{let H=await this.requestPrivateRecordAccessKey({record_id:x,reference_id:e?._ref});t+=`&p=${encodeURIComponent(H)}`;}catch{}}}if(e?.dataType==="endpoint")return e._update&&(e._update.url=t),t;if(e?.dataType==="download"){let _=document.createElement("a");return _.href=t,document.body.appendChild(_),_.setAttribute("download",h),_.target="_blank",_.click(),document.body.removeChild(_),null}return new Promise(async(_,S)=>{try{let v=await E.bind(this)(t,null,{method:"get",contentType:null,responseType:e?.dataType==="text"?"text":"blob",fetchOptions:{progress:e?.progress}},{ignoreService:!0});if(e?.dataType==="base64"){let P=new FileReader;P.onloadend=()=>_(P.result),P.readAsDataURL(v);}else _(v);}catch(v){S(v);}})}async function Mt(t,e=false){t=N(t,{ignoreEmpty:true}).data||{};let n="",r=Ct(t);if(r)t=r,n=t.record_id||t.unique_id,typeof n=="string"&&(typeof this.__private_access_key?.[n]=="string"&&(t.private_key=this.__private_access_key?.[n]||void 0),this.__my_unique_ids[n]&&(e?delete this.__my_unique_ids[n]:t.record_id=this.__my_unique_ids[n]));else {let s=await F.bind(this)(),i=t?.reference,o=false;typeof i=="object"&&Object.keys(i).length&&(i?.record_id||i?.unique_id?(n=i.record_id||i.unique_id,n&&typeof this.__private_access_key?.[n]=="string"&&(t.private_key=this.__private_access_key?.[n]||void 0),t.reference=n):i?.user_id&&(o=i.user_id===this.user?.user_id,t.reference=i.user_id)),typeof t?.table=="string"&&(t.table={name:t.table,access_group:0}),t.index&&t.index.hasOwnProperty("range")&&t.index.hasOwnProperty("condition")&&delete t.index.range;let a=l=>({table:{name:u=>$e(u,"table.name"),access_group:Be.bind(this),subscription:u=>g.UserId(u,'User ID in "subscription"')},reference:"string",index:{name:["$updated","$uploaded","$referenced_count","$user_id",u=>he(u,"index.name")],value:u=>{let f={$updated:"number",$uploaded:"number",$referenced_count:"number",$user_id:g.UserId};if(f.hasOwnProperty(l.index.name)){let d=f[l.index.name];if(typeof d=="function")return d(u);if(d!==typeof u)throw new c(`"index.value" should be type: ${d}.`,{code:"INVALID_PARAMETER"});return u}return typeof u=="string"&&!u?"":Pe(u)},condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq"],range:u=>Lt(u,l)},tag:u=>{if(u==null)return u;if(typeof u=="string")return je(u,"tag");throw new c('"tag" should be type: string.',{code:"INVALID_PARAMETER"})},private_key:"string"});t=g.Params(t||{},a(t),o||s?[]:["table"],{ignoreEmpty:true});}return {query:t,is_reference_fetch:n}}async function Ft(t,e){await this.__connection;let n=await Mt.bind(this)(t),r=n.is_reference_fetch,s=await E.bind(this)("get-records",n.query,{fetchOptions:e,auth:!!this.__user,method:this.__user?"post":"get"});r&&s?.reference_private_key&&typeof s.reference_private_key=="string"&&(this.__private_access_key[r]=s.reference_private_key);let i=[];for(let o in s.list)i.push(ce.bind(this)(s.list[o]));return s.list=await Promise.all(i),s}function qt(t){let e="",n=[],r=g.Params(t||{},{record_id:i=>typeof i=="string"&&this.__my_unique_ids[i]?this.__my_unique_ids[i]:ee(i,"record_id",{allowEmpty:false}),unique_id:["string",null],readonly:"boolean",table:{name:i=>$e(i,"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:Be.bind(this)},source:{referencing_limit:i=>{if(i===null)return null;if(typeof i=="number"){if(0>i)throw new c('"reference_limit" should be >= 0',{code:"INVALID_PARAMETER"});if(i>4503599627370546)throw new c('"reference_limit" should be <= 4503599627370546',{code:"INVALID_PARAMETER"});return i}throw new c('"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:i=>{if(i===void 0)return;if(!i||Array.isArray(i)&&!i.length)return null;let o={name:l=>he(l,'"name" in "index_restrictions"'),value:l=>Pe(l),condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne",()=>null],range:l=>{if(l!==null&&typeof i.value!=typeof l)throw new c('Index restriction "range" type should match the type of "value".',{code:"INVALID_PARAMETER"});if(!i.hasOwnProperty("value"))throw new c('Index restriction "value" is required.',{code:"INVALID_PARAMETER"});return l}};Array.isArray(i)||(i=[i]);let a=i.map(l=>g.Params(l,o,["name"]));if(a.length)for(let l of a)l.condition&&l.hasOwnProperty("range")&&delete l.range;return a}},reference:i=>{if(i===null)return {record_id:null};if(i){if(typeof i=="string")return e=i,this.__my_unique_ids[i]?this.__my_unique_ids[i]:i;if(typeof i!="object")throw new c('"reference" should be type: <string | object>.',{code:"INVALID_PARAMETER"});return g.Params(i,{unique_id:"string",record_id:o=>o==null?o:(e=o,typeof this.__private_access_key?.[o]=="string"&&(t.reference_private_key=this.__private_access_key[o]||void 0),ee(o,"reference.record_id",{allowEmpty:false,onlyAlphanumeric:true}))})}},index:[null,{name:i=>he(i,"index.name"),value:i=>Pe(i)}],tags:i=>{if(i==null)return i;if(typeof i=="string"&&(i=i.split(",").map(o=>o.trim())),!Array.isArray(i))throw new c('"tag" should be type: <string | string[]>.',{code:"INVALID_PARAMETER"});return i.map(o=>je(o,"tag"))},remove_bin:i=>{if(!i)return null;let o=[];if(Array.isArray(i))for(let a of i)if(typeof a=="string")o.push(decodeURIComponent(a.split("?")[0]));else if(a.url&&a.size&&a.filename){let u=a.url.split("/").slice(0,3).join("/")+"/"+a.path;o.push(u);}else throw new c('"remove_bin" should be type: <string[] | BinaryFile[] | null>',{code:"INVALID_PARAMETER"});else throw new c('"remove_bin" should be type: <string[] | BinaryFile[] | null>',{code:"INVALID_PARAMETER"});return o},progress:"function",data:i=>i},[],{precall:i=>{let o=i?.data||{};if(!o?.record_id&&!o.table)throw new c('"table.name" is required.',{code:"INVALID_PARAMETER"});typeof o.table=="string"&&(o.table={name:o.table,access_group:0}),i.files&&(n=i.files);}}),s=t.progress||null;if(delete r.progress,!this.__user){let i=!!(r.table?.subscription?.is_subscription_record||r.table?.subscription?.upload_to_feed||r.table?.subscription?.notify_subscribers||r.table?.subscription?.feed_referencing_records||r.table?.subscription?.notify_referencing_records);if(r.record_id)throw new c("Public users cannot update existing records.",{code:"INVALID_REQUEST"});if(r.table.access_group!=="public"&&r.table.access_group!==0)throw new c("Public users can only post records to public tables.",{code:"INVALID_REQUEST"});if(i)throw new c("Public users cannot post subscription records.",{code:"INVALID_REQUEST"});if(r.remove_bin)throw new c("Public users cannot remove files from records.",{code:"INVALID_REQUEST"});if(r.unique_id)throw new c("Public users cannot set unique_id for records.",{code:"INVALID_REQUEST"})}return {config:r,progress:s,is_reference_post:e,files:n}}async function Vt(t){if(await this.__connection,!Array.isArray(t)||!t.length)throw new c('"params" should be a non-empty array.',{code:"INVALID_PARAMETER"});let e=[],n,r,s=null,o={_is_bulk_:t.map((d,p)=>{if(!d||typeof d!="object"||Array.isArray(d))throw new c(`"params[${p}]" should be type: <object>.`,{code:"INVALID_PARAMETER"});let w=qt.bind(this)(d),h=w.config;if(w.is_reference_post&&e.push(w.is_reference_post),typeof h.progress=="function"&&s===null&&(s=h.progress),h.service!==void 0){if(n===void 0)n=h.service;else if(n!==h.service)throw new c('All bulk params should share the same "service" value.',{code:"INVALID_PARAMETER"})}if(h.owner!==void 0){if(r===void 0)r=h.owner;else if(r!==h.owner)throw new c('All bulk params should share the same "owner" value.',{code:"INVALID_PARAMETER"})}return delete h.progress,delete h.service,delete h.owner,h}),service:"",owner:""};n!==void 0&&(o.service=n),r!==void 0&&(o.owner=r);let a={auth:!!this.__user,method:"post"},l={};Object.keys(l).length&&Object.assign(a,{fetchOptions:l});let u=await E.bind(this)("post-record",o,a),f=await Promise.all(u.map(d=>ce.bind(this)(d,"called from postRecord")));for(let d=0;d<u.length;d++){let p=u[d],w=f[d];if(typeof p?.reference_private_key=="string")for(let h of e)this.__private_access_key[h]=p.reference_private_key;w?.unique_id&&(this.__my_unique_ids[w.unique_id]=w.record_id);}return f}async function $t(t,e,n){if(await this.__connection,!e)throw new c('"config" argument is required.',{code:"INVALID_PARAMETER"});let r=qt.bind(this)(e),s=r.config,i=r.progress,o=r.is_reference_post,a={auth:!!this.__user,method:"post"},l=[],u=N(t);n&&Array.isArray(n)&&n.length&&(l=l.concat(n)),u.files&&Array.isArray(u.files)&&u.files.length&&(l=l.concat(u.files));let f=null;f=Object.assign({data:u.data},s);let d={};typeof i=="function"&&(d.progress=i),Object.keys(d).length&&Object.assign(a,{fetchOptions:d});let p=await E.bind(this)("post-record",f,a);if(V()&&l.length){let h=new FormData;for(let _ of l)h.append(_.name,_.file,_.file.name);let m={record_id:p.rec,progress:i};s.hasOwnProperty("service")&&(m.service=s.service);let{bin_endpoints:I}=await Ie.bind(this)(h,m);p.bin?p.bin.push(...I):p.bin=I;}o&&typeof p?.reference_private_key=="string"&&(this.__private_access_key[o]=p.reference_private_key);let w=await ce.bind(this)(p,"called from postRecord");return w.unique_id&&(this.__my_unique_ids[w.unique_id]=w.record_id,V()&&(this.__uniqueIdsPersistTimer!==null&&clearTimeout(this.__uniqueIdsPersistTimer),this.__uniqueIdsPersistTimer=setTimeout(()=>{this.__uniqueIdsPersistTimer=null;try{window.sessionStorage.setItem(`${this.service}:uniqueids`,JSON.stringify(this.__my_unique_ids));}catch{}},500))),w}async function jt(t,e){let n=await E.bind(this)("get-table",g.Params(t||{},{table:"string",condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}),Object.assign({auth:!!this.__user},{fetchOptions:e})),r={cnt_rec:"number_of_records",tbl:"table",srvc:"service",grp_:"number_of_records_in_access_group_"};if(Array.isArray(n?.list))for(let s of n.list){for(let i in r){if(i==="grp_"){for(let o in s)if(o.startsWith("grp_")){let a=o.substring(4);a==="pv"?a="private":a==="00"?a="public":a==="01"?a="authorized":a==="99"&&(a="admin"),s[`number_of_records_in_access_group_${a}`]=s[o],delete s[o];}}s.hasOwnProperty(i)&&(s[r[i]]=s[i],delete s[i]);}typeof s.table=="string"&&(s.table=B(s.table));}return n}async function Bt(t,e){if(!t?.table)throw new c('"table" is required.',{code:"INVALID_PARAMETER"});let n=g.Params(t||{},{table:"string",index:i=>he(i,"index.name"),order:{by:["average_number","total_number","number_count","average_bool","total_bool","bool_count","string_count","index_name","number_of_records"],value:["string","number","boolean"],condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}},["table"]);if(n.hasOwnProperty("order")){if(!n.order?.by)throw new c('"order.by" is required.',{code:"INVALID_PARAMETER"});if(n.order.hasOwnProperty("condition")&&!n.order.hasOwnProperty("value"))throw new c('"value" is required for "condition".',{code:"INVALID_PARAMETER"});if(n.hasOwnProperty("index")&&n.index.substring(n.index.length-1)!==".")throw new c('"index" should be a parent index name of the compound index when using "order.by"',{code:"INVALID_PARAMETER"})}let r=await E.bind(this)("get-index",n,Object.assign({auth:!!this.__user},{fetchOptions:e})),s={cnt_bool:"boolean_count",cnt_numb:"number_count",totl_numb:"total_number",totl_bool:"total_bool",avrg_numb:"average_number",avrg_bool:"average_bool",cnt_str:"string_count"};return Array.isArray(r?.list)&&(r.list=r.list.map(i=>{let o=i.idx.split("/"),a={table:B(o[1]),index:B(o[2]),number_of_records:i.cnt_rec};for(let l in s)Object.prototype.hasOwnProperty.call(i,l)&&(a[s[l]]=i[l]);return a})),r}async function Qt(t,e){let n=await E.bind(this)("get-tag",g.Params(t||{},{table:"string",tag:"string",condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}),Object.assign({auth:!!this.__user},{fetchOptions:e}));return Array.isArray(n?.list)&&(n.list=n.list.map(r=>{let s=r.tag.split("/");return {table:B(s[1]),tag:B(s[0]),number_of_records:r.cnt_rec}})),n}async function Kt(t,e){let n=await E.bind(this)("get-uniqueid",g.Params(t||{},{unique_id:"string",condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}),Object.assign({auth:!!this.__user},{fetchOptions:e}));if(Array.isArray(n?.list))for(let r in n.list){let s=n.list[r];n.list[r]={unique_id:s.unq,record_id:s.rec};}return n}async function Ht(t,e){await this.__connection;let n=await Mt.bind(this)(t,true),r=n.is_reference_fetch,s=await E.bind(this)("del-records",n.query,{auth:true,fetchOptions:e});return r&&typeof s?.reference_private_key=="string"&&(this.__private_access_key[r]=s.reference_private_key),s?.message||s}function Wt(t){return Xt.bind(this)({record_id:t.record_id,user_id:t.user_id,execute:"add"})}function zt(t){return Xt.bind(this)({record_id:t.record_id,user_id:t.user_id||null,execute:"remove"})}async function Jt(t,e){let n={record_id:t.record_id||void 0,user_id:t.user_id||void 0,execute:"list"};if(!n.record_id&&!n.user_id)throw new c("Either record_id or user_id must be provided.",{code:"INVALID_PARAMETER"});if(n.user_id)if(typeof n.user_id=="string")g.UserId(n.user_id),n.user_id=[n.user_id];else if(Array.isArray(n.user_id))for(let i of n.user_id)g.UserId(i);else throw new c("user_id should be type: <string | string[]>",{code:"INVALID_PARAMETER"});let r=i=>(i.rec_usr?(i.record_id=i.rec_usr.split("/")[0],i.user_id=i.rec_usr.split("/")[1]):i.usr_rec&&(i.user_id=i.usr_rec.split("/")[0],i.record_id=i.usr_rec.split("/")[1]),i),s=await E.bind(this)("grant-private-access",n,{auth:true,fetchOptions:e});return s.list=s.list.map(r),s}function Gt(t){let e=t.record_id,n=t.reference_id||void 0;if(!e)throw new c("Record ID is required.",{code:"INVALID_PARAMETER"});if(typeof e!="string")throw new c("Record ID should be type: <string | string[]>",{code:"INVALID_PARAMETER"});if(n&&typeof n!="string")throw new c("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(Se[e])return Se[e];let r=E.bind(this)("request-private-access-key",{record_id:e,reference_id:n},{auth:true}).then(s=>{let i=typeof s=="string"?s:s?.private_key;if(typeof i!="string")throw new c("Invalid private access key response.",{code:"ERROR"});return this.__private_access_key[e]=i,i}).finally(()=>{delete Se[e];});return Se[e]=r,r}function Xt(t){t.execute;let n=g.Params(t,{record_id:"string",user_id:r=>{if(!r)throw new c("User ID is required.",{code:"INVALID_PARAMETER"});let s=r;if(typeof s=="string"&&(s=[s]),s.length>100)throw new c("Cannot process more than 100 users at once.",{code:"INVALID_REQUEST"});for(let i of s)g.UserId(i,'User ID in "user_id"');return s},execute:["add","remove"]},["execute","record_id","user_id"]);return n.user_id||(n.user_id=null),E.bind(this)("grant-private-access",n,{auth:true})}var T={},O={},Q={},z={},W={},ve={},xe={};function Zt(t,e,n){t[e]||(t[e]=[]),t[e].push(n);}async function De(t,e,n){let r=[];if(t[e]){for(let s of t[e])if(s){let i=n(s);i instanceof Promise&&(i=await i),r.push(i);}delete t[e];}return r}async function Ke(t,e){if(!this?.session?.accessToken?.jwtToken)throw new c("Access token is required.",{code:"INVALID_PARAMETER"});let n=await this.__socket;async function r(s,i,o){this.log("answerSdpOffer from",i),await T[i].setRemoteDescription(new RTCSessionDescription(s));let a=await T[i].createAnswer();await T[i].setLocalDescription(a),o.send(JSON.stringify({action:"rtc",uid:i,content:{sdpanswer:a},token:this.session.accessToken.jwtToken}));}T?.[e]?t?(await De(xe,e,s=>r.bind(this)(s,e,n)),await r.bind(this)(t,e,n)):await De(xe,e,s=>r.bind(this)(s,e,n)):t&&Zt(xe,e,t);}async function He(t,e){if(this.log("receiveIceCandidate",t),T?.[e]&&T[e]?.remoteDescription&&T[e]?.remoteDescription?.type){if(!t)return De(ve,e,n=>T[e].addIceCandidate(n));await De(ve,e,n=>T[e].addIceCandidate(n)),await T[e].addIceCandidate(t);}else Zt(ve,e,t);}async function K(t){if(typeof window>"u"||window._runningInNodeJS)throw new c("WebRTC is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});g.Params(t,{cid:i=>{if(typeof i!="string")throw new c('"cid" should be type: <string>.',{code:"INVALID_PARAMETER"});if(i&&i.slice(0,4)!=="cid:")throw new c('"cid" should be a valid connection id.',{code:"INVALID_PARAMETER"});return i},close:"boolean"});let e=await this.__socket,{cid:n,close_all:r=false}=t||{};if(!r&&!n)throw new c('"cid" is required.',{code:"INVALID_PARAMETER"});let s=i=>{if(!i)throw new c('"cid" is required.',{code:"INVALID_PARAMETER"});if(delete xe[i],delete ve[i],O[i]&&Object.values(O[i]).forEach(o=>{o.readyState!=="closed"&&o.close();}),delete O[i],T?.[i]){T[i].connectionState!=="closed"&&(T[i].close(),e.send(JSON.stringify({action:"rtc",uid:i,content:{hungup:this.user.user_id},token:this.session.accessToken.jwtToken})));let o={type:"connectionstatechange",target:T[i],timestamp:new Date().toISOString(),state:T[i].connectionState,iceState:T[i].iceConnectionState,signalingState:T[i].signalingState};W[i]&&W[i](o),this.log("closeRTC",o);}delete W[i],delete z[i],delete Q[i],delete T[i];};if(r)for(let i in T)s(i);else s(n);this.log("Cleaning up media stream..."),this.__mediaStream&&(this.__mediaStream.getTracks().forEach(i=>{i.stop();}),this.__mediaStream=null);}async function Yt(t){if(t instanceof MediaStream)return t;if(!t.video&&!t.audio){let e=new MediaStream,n=document.createElement("canvas");n.width=1,n.height=1;let s=n.captureStream().getVideoTracks()[0];return e.addTrack(s),e}return window.navigator.mediaDevices.getUserMedia(t)}async function en(t,e){if(typeof window>"u"||window._runningInNodeJS)throw new c("WebRTC is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(typeof e!="function")throw new c("Callback is required.",{code:"INVALID_PARAMETER"});if(!this?.session?.accessToken?.jwtToken)throw new c("Access token is required.",{code:"INVALID_PARAMETER"});t=g.Params(t,{cid:o=>{if(typeof o!="string")throw new c('"cid" should be type: <string>.',{code:"INVALID_PARAMETER"});if(o&&o.slice(0,4)!=="cid:")throw new c('"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:n,ice:r}=t;if(!(t?.media instanceof MediaStream)&&(t?.media?.video||t?.media?.audio)&&window.location.hostname!=="localhost"&&window.location.protocol!=="https:")throw new c("Media stream is only supported on either localhost or https.",{code:"INVALID_REQUEST"});let s=this.__socket?await this.__socket:this.__socket;if(!s)throw new c("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});if(s.readyState!==1)throw new c("Realtime connection is not ready.",{code:"INVALID_REQUEST"});let i={iceServers:[{urls:r}]};T?.[n]||(T[n]=new RTCPeerConnection(i)),t?.media&&(this.__mediaStream=await Yt(t.media),this.__mediaStream.getTracks().forEach(o=>{T[n].addTrack(o,this.__mediaStream);})),W[n]=e,O[n]||(O[n]={});for(let o=0;o<t.channels.length;o++){let a=t.channels[o];if(typeof a=="string")switch(a){case "text-chat":a={ordered:true,maxRetransmits:10,protocol:"text-chat"};break;case "file-transfer":a={ordered:false,maxPacketLifeTime:3e3,protocol:"file-transfer"};break;case "video-chat":a={ordered:true,maxRetransmits:10,protocol:"video-chat"};break;case "voice-chat":a={ordered:true,maxRetransmits:10,protocol:"voice-chat"};break;case "gaming":a={ordered:false,maxPacketLifeTime:100,protocol:"gaming"};break;default:a={ordered:true,maxRetransmits:10,protocol:"default"};break}let l=a.protocol||"default";if(Object.keys(O[n]).includes(l))throw new c(`Data channel with the protocol "${l}" already exists.`,{code:"INVALID_REQUEST"});let u=T[n].createDataChannel(l,a);O[n][l]=u;}for(let o in O[n]){let a=O[n][o];rn.bind(this)(n,a);}return nn.bind(this)(n,["onnegotiationneeded"]),await Qe.bind(this)(n),{hangup:()=>Q[n]&&Q[n](false),connection:new Promise(o=>{Q[n]=(a=>{if(this.log("receiver picked up the call",n),!a)return K.bind(this)({cid:n}),null;T[n].onnegotiationneeded=()=>{this.log("onnegotiationneeded",`sending offer to "${n}".`),Qe.bind(this)(n),W[n]&&W[n]({type:"negotiationneeded",target:T[n],timestamp:new Date().toISOString(),signalingState:T[n].signalingState,connectionState:T[n].iceConnectionState,gatheringState:T[n].iceGatheringState});},o({target:T[n],channels:O[n],hangup:()=>K.bind(this)({cid:n}),media:this.__mediaStream});}).bind(this);})}}function tn(t){return async(e,n)=>{e=e||{},e=N(e).data;let r=t.sender_cid,s=await this.__socket;if(!z[r])return null;if(typeof n!="function")throw new c("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 c("Media stream is only supported on either localhost or https.",{code:"INVALID_REQUEST"});let{ice:i="stun:stun.skapi.com:3468"}=e;return T?.[r]||(T[r]=new RTCPeerConnection({iceServers:[{urls:i}]})),e?.media&&(this.__mediaStream=await Yt(e.media),this.__mediaStream.getTracks().forEach(o=>{T[r].addTrack(o,this.__mediaStream);})),delete z[r],W[r]=n,O[r]||(O[r]={}),T[r].ondatachannel=o=>{this.log("ondatachannel",`received data channel "${o.channel.label}".`);let a=o.channel;O[r][a.label]=a,rn.bind(this)(r,a);},nn.bind(this)(r,["onnegotiationneeded"]),await Ke.bind(this)(null,r),await He.bind(this)(null,r),s.send(JSON.stringify({action:"rtc",uid:r,content:{pickup:this.user.user_id},token:this.session.accessToken.jwtToken})),{target:T[r],channels:O[r],hangup:()=>K.bind(this)({cid:r}),media:this.__mediaStream}}}async function Qe(t){if(!this?.session?.accessToken?.jwtToken)throw new c("Access token is required.",{code:"INVALID_PARAMETER"});this.log("sendOffer",t);let e=await this.__socket,n=await T[t].createOffer();await T[t].setLocalDescription(n);let r=T[t].localDescription;this.log("rtcSdpOffer to",r),e.send(JSON.stringify({action:"rtc",uid:t,content:{sdpoffer:r},token:this.session.accessToken.jwtToken}));}async function Qr(t,e){if(!this?.session?.accessToken?.jwtToken)throw new c("Access token is required.",{code:"INVALID_PARAMETER"});this.log("sendIceCandidate to",e);let n=await this.__socket;if(!t.candidate){this.log("candidate-end","all ice candidates have been sent");return}let r=W[e]||(()=>{}),s=t.candidate;this.log("ice gathering state set to",T[e].iceGatheringState),r({type:"icecandidate",target:T[e],timestamp:new Date().toISOString(),candidate:t.candidate.candidate,sdpMid:t.candidate.sdpMid,sdpMLineIndex:t.candidate.sdpMLineIndex,usernameFragment:t.candidate.usernameFragment,protocol:t.candidate.protocol,gatheringState:T[e].iceGatheringState,connectionState:T[e].iceConnectionState}),n.send(JSON.stringify({action:"rtc",uid:e,content:{candidate:s},token:this.session.accessToken.jwtToken}));}function nn(t,e){let n=new Set(e),r=W[t]||(o=>{}),s=T[t],i={ontrack:o=>{r({type:"track",target:s,timeStamp:o.timeStamp,streams:o.streams,track:o.track});},onicecandidate:o=>{Qr.bind(this)(o,t),o.candidate?r({type:"icecandidate",target:s,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:s.iceGatheringState,connectionState:s.iceConnectionState}):r({type:"icecandidateend",target:s,timestamp:new Date().toISOString()});},onicecandidateerror:o=>{r({type:"icecandidateerror",target:s,timestamp:new Date().toISOString(),errorCode:o.errorCode,errorText:o.errorText,url:o.url,hostCandidate:o.hostCandidate,gatheringState:s.iceGatheringState,connectionState:s.iceConnectionState});},oniceconnectionstatechange:()=>{r({type:"iceconnectionstatechange",target:s,timestamp:new Date().toISOString(),state:s.iceConnectionState,gatheringState:s.iceGatheringState,signalingState:s.signalingState});},onicegatheringstatechange:()=>{r({type:"icegatheringstatechange",target:s,timestamp:new Date().toISOString(),state:s.iceGatheringState,connectionState:s.iceConnectionState,signalingState:s.signalingState});},onsignalingstatechange:()=>{r({type:"signalingstatechange",target:s,timestamp:new Date().toISOString(),state:s.signalingState,connectionState:s.iceConnectionState,gatheringState:s.iceGatheringState});},onnegotiationneeded:()=>{Qe.bind(this)(t),r({type:"negotiationneeded",target:s,timestamp:new Date().toISOString(),signalingState:s.signalingState,connectionState:s.iceConnectionState,gatheringState:s.iceGatheringState});},onconnectionstatechange:()=>{r({type:"connectionstatechange",target:s,timestamp:new Date().toISOString(),state:s.connectionState,iceState:s.iceConnectionState,signalingState:s.signalingState});let o=s.connectionState;(o==="disconnected"||o==="failed"||o==="closed")&&K.bind(this)({cid:t});}};for(let[o,a]of Object.entries(i))n.has(o)||(s[o]=a);}function rn(t,e,n){let r=new Set(n),s=W[t]||(o=>{}),i={onmessage:o=>{let a={type:o.type,target:e,timeStamp:o.timeStamp,data:o.data,lastEventId:o.lastEventId,origin:o.origin,readyState:e.readyState,bufferedAmount:e.bufferedAmount};this.log(`${e.label}: message`,o.data),s(a);},onerror:o=>{let a={type:o.type,target:e,timeStamp:o.timeStamp,error:o.error.message,errorCode:o.error.errorDetail,readyState:e.readyState,label:e.label};this.log(`${e.label}: error`,o.error.message),s(a);},onclose:o=>{let a={type:o.type,target:e,timeStamp:o.timeStamp,readyState:e.readyState,label:e.label,id:e.id};this.log(`${e.label}: closed`,null),s(a),O[t]&&(delete O[t][e.label],Object.keys(O[t]).length===0&&K.bind(this)({cid:t}));},onbufferedamountlow:o=>{let a={target:e,bufferedAmount:e.bufferedAmount,bufferedAmountLowThreshold:e.bufferedAmountLowThreshold,type:o.type,timeStamp:o.timeStamp};this.log(`${e.label}: bufferedamountlow`,e.bufferedAmount),s(a);},onopen:o=>{this.log("dataChannel",`data channel: "${e.label}" is open and ready to send messages.`);let a={type:o.type,target:e,timeStamp:o.timeStamp,readyState:e.readyState,label:e.label,id:e.id,ordered:e.ordered,maxRetransmits:e.maxRetransmits,protocol:e.protocol};s(a);}};for(let[o,a]of Object.entries(i))r.has(o)||(e[o]=a);}var ne,te=null,pe=true,le=0;async function Kr(){if(typeof window>"u"||window._runningInNodeJS)throw new c("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.getProfile(),!this.session)throw new c("No access.",{code:"INVALID_REQUEST"});let t=await this.record_endpoint;return new WebSocket(t.websocket_private+"?token="+this.session.accessToken.jwtToken)}var We=null;async function sn(){if(typeof window>"u"||window._runningInNodeJS)throw new c("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});pe=true;let t=this.__socket?await this.__socket:this.__socket;K.bind(this)({close_all:true}),ne&&ze.bind(this)({group:null}),le=0,te&&(te.terminate(),te=null);try{t&&t.close();}catch{}return window.removeEventListener("visibilitychange",We),this.__socket=null,null}async function Ue(t,e=50,n){if(typeof window>"u"||window._runningInNodeJS)throw new c("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(typeof t!="function")throw new c("Callback must be a function.",{code:"INVALID_REQUEST"});if(n==="reconnect"){if(this.__socket instanceof Promise){let r=await this.__socket;if(r.readyState!==WebSocket.CLOSED&&r.readyState!==WebSocket.CLOSING)return this.__socket}}else if(pe&&(We=()=>{!document.hidden&&!pe&&Ue.bind(this)(t,0,"reconnect");},this.__socket instanceof Promise))return this.__socket;te&&(te.terminate(),te=null),this.__socket=new Promise(async r=>{await oe.bind(this)(),setTimeout(async()=>{let s=await Kr.bind(this)();s.onopen=()=>{pe=false,le=0,n!=="reconnect"&&window.addEventListener("visibilitychange",We),this.log("realtime onopen","Connected to WebSocket server."),t({type:"success",message:"Connected to WebSocket server."}),ne&&s.send(JSON.stringify({action:"joinRoom",rid:ne,token:this.session.accessToken.jwtToken}));let i=`
207
207
  let interval = 15000; // Set interval time 15 seconds
208
208
 
209
209
  function runInterval() {
@@ -212,9 +212,9 @@ var Qn=Object.defineProperty;var Kn=Object.getOwnPropertyDescriptor;var re=(t=>t
212
212
  }
213
213
 
214
214
  runInterval(); // Start interval
215
- `,o=new Blob([i],{type:"application/javascript"});Y=new Worker(URL.createObjectURL(o)),Y.onmessage=a=>{s.readyState===1&&s.send(JSON.stringify({action:"keepAlive"}));},r(s);},s.onmessage=async i=>{let o="";try{o=JSON.parse(decodeURI(i.data)),this.log("socket onmessage",o);}catch{return}let a;switch(true){case !!o?.["#message"]:a="message";break;case !!o?.["#private"]:a="private";break;case !!o?.["#notice"]:a="notice";break;case !!o?.["#rtc"]:a="rtc";break;case !!o?.["#error"]:a="error";break}if(!a)return;let l={type:a,message:o?.["#rtc"]||o?.["#message"]||o?.["#private"]||o?.["#notice"]||o?.["#error"]||null,sender:o?.["#user_id"]||null,sender_cid:o?.["#scid"]?"cid:"+o["#scid"]:null,sender_rid:o?.["#srid"]||null,code:o?.["#code"]||null};if(a==="notice")t(l);else if(a==="rtc"){if(l.sender!==this.user.user_id){let u=l.message;if(u.hungup){Q[l.sender_cid]&&(Q[l.sender_cid](false),delete Q[l.sender_cid]),z[l.sender_cid]&&delete z[l.sender_cid],I?.[l.sender_cid]&&K.bind(this)({cid:l.sender_cid}),l.type="rtc:closed",t(l);return}if(u.candidate&&Qe.bind(this)(u.candidate,l.sender_cid),u.sdpoffer&&(Be.bind(this)(u.sdpoffer,l.sender_cid),z[l.sender_cid]||(z[l.sender_cid]=l.sender_cid,delete l.message,l.connectRTC=Yt.bind(this)(l),l.type="rtc:incoming",l.hangup=(()=>{I[l.sender_cid]?K.bind(this)({cid:l.sender_cid}):z[l.sender_cid]&&(delete z[l.sender_cid],s.send(JSON.stringify({action:"rtc",uid:l.sender_cid,content:{hungup:this.user.user_id},token:this.session.accessToken.jwtToken})));}).bind(this),t(l))),u.pickup&&Q[l.sender_cid]&&(Q[l.sender_cid](true),delete Q[l.sender_cid]),u.sdpanswer&&I[l.sender_cid])if(I[l.sender_cid].signalingState==="have-local-offer")await I[l.sender_cid].setRemoteDescription(new RTCSessionDescription(u.sdpanswer));else throw new c("Invalid signaling state.",{code:"INVALID_REQUEST"})}}else t(l);},s.onclose=()=>{he?(this.log("realtime onclose","WebSocket connection closed."),t({type:"close",message:"WebSocket connection closed."})):(this.log("realtime onclose","WebSocket unexpected close."),t({type:"error",message:"Skapi: WebSocket unexpected close."}),ce++,ce<3?(this.log("realtime onclose","Reconnecting to WebSocket server..."+ce),t({type:"reconnect",message:"Reconnecting to WebSocket server..."+ce}),xe.bind(this)(t,3e3,"reconnect")):(this.log("realtime onclose","Max reconnection attempts reached."),t({type:"error",message:"Skapi: Max reconnection attempts reached."})));},s.onerror=()=>{this.log("realtime onerror","WebSocket connection error."),t({type:"error",message:"Skapi: WebSocket connection error."});};},e);});}async function rn(t,e,n){if(typeof window>"u"||window._runningInNodeJS)throw new c("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});let r=this.__socket?await this.__socket:this.__socket;if(!r)throw new c("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});if(!e)throw new c("No recipient.",{code:"INVALID_REQUEST"});await se.bind(this)(),t=N(t).data;let s="";if(n&&(n=g.Params(n,{config:{always:"boolean"},title:"string",body:"string"},["title","body"]),s=JSON.stringify({title:n.title,body:n.body}),new Blob([s]).size>3072))throw new c("Notification size exceeds 3kb.",{code:"INVALID_PARAMETER"});if(r.readyState===1){try{g.UserId(e),r.send(JSON.stringify({action:"sendMessage",uid:e,content:t,notification:s,notificationConfig:n?.config||{},token:`IdT:${this.service}:${this.owner}:`+(this.bearerToken||this.session?.idToken?.jwtToken||"null")}));}catch(i){if(this.log("postRealtime:err",{err:i}),ee!==e)throw new c(`User has not joined to the recipient group. Run joinRealtime({ group: "${e}" })`,{code:"INVALID_REQUEST"});r.send(JSON.stringify({action:"broadcast",rid:e,content:t,notification:s,notificationConfig:n?.config||{},token:`IdT:${this.service}:${this.owner}:`+(this.bearerToken||this.session?.idToken?.jwtToken||"null")}));}return {type:"success",message:"Message sent."}}throw new c("Realtime connection is not open. Try reconnecting with connectRealtime().",{code:"INVALID_REQUEST"})}async function He(t){if(typeof window>"u"||window._runningInNodeJS)throw new c("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});let e=this.__socket?await this.__socket:this.__socket;if(!e)throw new c("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});await se.bind(this)(),t=N(t,{nullIfEmpty:true}).data;let{group:n=null}=t;if(!n&&!ee)return {type:"success",message:"Left realtime message group."};if(n!==null&&typeof n!="string")throw new c('"group" must be a string | null.',{code:"INVALID_PARAMETER"});return e.send(JSON.stringify({action:"joinRoom",rid:n,token:this.session.accessToken.jwtToken})),ee=n,{type:"success",message:n?`Joined realtime message group: "${n}".`:"Left realtime message group."}}async function sn(t,e){t=g.Params(t,{user_id:r=>g.UserId(r,'User ID in "user_id"'),group:["string",()=>{if(!ee)throw new c('No group has been joined. Otherwise "group" is required.',{code:"INVALID_REQUEST"});return ee}]});let n=await E.bind(this)("get-ws-group",t,{fetchOptions:e,auth:true,method:"post"});return n.list=n.list.map(r=>({user_id:r.uid.split("#")[1],cid:"cid:"+r.cid})),n}async function on(t,e){if(await this.__connection,t||(t={searchFor:"group",value:" ",condition:">"}),t=g.Params(t,{searchFor:["group","number_of_users",()=>"group"],value:["string","number",()=>t?.searchFor&&t?.searchFor==="number_of_users"?0:" "],condition:[">",">=","=","<","<=","!=","gt","gte","eq","lt","lte","ne"],range:["string","number"]}),t.condition||(t.value===" "||!t.value?t.condition=">":t.condition="="),t.range&&t.condition&&delete t.condition,t.searchFor==="number_of_users"&&typeof t.value!="number")throw new c('"value" must be a number.',{code:"INVALID_PARAMETER"});if(t.searchFor==="group"&&typeof t.value!="string")throw new c('"value" must be a string.',{code:"INVALID_PARAMETER"});if(t.hasOwnProperty("range")&&typeof t.range!=typeof t.value)throw new c(`"range" must be a ${typeof t.value}.`,{code:"INVALID_PARAMETER"});let n=await E.bind(this)("get-ws-group",t,{fetchOptions:e,auth:true,method:"post"});return n.list=n.list.map(r=>({group:r.rid.split("#")[1],number_of_users:r.cnt})),n}var jr=typeof FormData<"u",Br=typeof HTMLFormElement<"u",Qr=typeof SubmitEvent<"u",te={},We={};function cn({id:t,auth:e,service:n,owner:r,latency:s=1e3,queue:i,onResponse:o,onError:a}){if(typeof s!="number")throw new c('"latency" should be a number.',{code:"INVALID_PARAMETER"});if(s<0)throw new c('"latency" should be a non-negative number.',{code:"INVALID_PARAMETER"});i&&!te?.[i]&&(te[i]=new an({breakWhenError:false,batchSize:1}));let l=()=>new Promise((u,f)=>{let d=false,p=setInterval(async()=>{try{let _=await E.bind(this)("csr-poll",{id:t,service:n,owner:r},{auth:e});if(_.status==="running"||_.status==="pending"||d)return;d=!0,o&&o(_),clearInterval(p),u(_);}catch(_){if(d)return;d=true,a&&a(_),clearInterval(p),f(_);}},s);});return i?new Promise((u,f)=>{let d=te[i].add([async()=>{try{let p=await l();return u(p),p}catch(p){throw f(p),p}}])[0];We[t]=d;}):l()}function ln(t,e){if(!t.queue)throw new c('"queue" is required.',{code:"INVALID_PARAMETER"});let n={service:t.service||this.service,owner:t.owner||this.owner,queue:t.queue+":"};return E.bind(this)("csr-poll",n,{auth:true})}async function un(t){let e=false;if(typeof t.poll=="number"&&t.poll<0)throw new c('"poll" should be a non-negative number.',{code:"INVALID_PARAMETER"});let n=t?.onResponse,r=t?.onError,s=typeof t.poll=="number"?t.poll:t.poll?1e3:0;delete t.poll,s&&!t.queue&&(t.queue=(this.__user?.user_id||"anonymous")+"-"+ne());let i=l=>{for(let u in l)if(typeof l[u]=="string"&&l[u].includes("$CLIENT_SECRET")){e=true;break}};if(t=g.Params(t,{url:l=>{if(!l||typeof l!="string")throw new c('"url" should be type: <string>.',{code:"INVALID_PARAMETER"});return g.Url(l),l.includes("$CLIENT_SECRET")&&(e=true),l},clientSecretName:"string",method:l=>{if(l&&typeof l!="string")throw new c('"method" should be either "GET" or "POST" or "DELETE" or "PUT".',{code:"INVALID_PARAMETER"});let u=l.toLowerCase();if(u!=="get"&&u!=="post"&&u!=="delete"&&u!=="put")throw new c('"method" should be either "GET" or "POST" or "DELETE" or "PUT".',{code:"INVALID_PARAMETER"});return u},headers:l=>{if(l&&typeof l!="object")throw new c('"headers" should be type: <object>.',{code:"INVALID_PARAMETER"});return i(l),l},data:l=>{if(l&&typeof l!="object")throw new c('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return i(l),l},params:l=>{if(l&&typeof l!="object")throw new c('"params" should be type: <object>.',{code:"INVALID_PARAMETER"});return i(l),l},expires:"number",queue:"string"},["clientSecretName","method","url"]),!e)throw new c(`At least one parameter value should include "$CLIENT_SECRET" in ${t.method.toLowerCase()==="post"?'"data"':'"params"'} or "headers".`,{code:"INVALID_PARAMETER"});await this.__connection;let o=!!this.__user,a=()=>E.bind(this)("csr",t,{auth:o,tokenHeaders:{accessToken:!!o}}).then(l=>{if(l.status==="running"||l.status==="pending"){let u=`[${t.method.toUpperCase()}]${t.url.toLowerCase()}`,f=t.service||this.service,d=t.owner||this.owner,p=`${u}#${f}:${l.id}`;Object.assign(l,{poll:async _=>cn.call(this,{id:p,auth:o,service:f,owner:d,latency:_?.latency||1e3,queue:t?.queue,onResponse:n,onError:r})});}return n?n(l):l}).catch(l=>{if(r)return r(l);throw l});if(t?.queue){let l="base:"+t.queue;return te?.[l]||(te[l]=new an({breakWhenError:false,batchSize:1})),new Promise((u,f)=>{te[l].add([async()=>{try{let d=await a();if(s>0){let p=d.poll({latency:s});return u(p),p}return u(d),d}catch(d){throw f(d),d}}]);})}else return a()}async function dn(t,e){await this.__connection;let n=t.service||this.service,r=t.owner||this.owner;t=g.Params(t,{url:"string",method:["GET","POST","DELETE","PUT"],queue:"string",status:["pending","running","resolved","failed"]},["url","method"]);let s=!!this.__user,i=`[${t.method.toUpperCase()}]${t.url.toLowerCase()}#${n}:`,o={id:i,queue:t?.queue,status:t?.status,service:n,owner:r};Object.keys(o).forEach(l=>{o[l]||delete o[l];}),o.queue&&delete o.id;let a=await E.bind(this)("csr-poll",o,{auth:s,fetchOptions:e});return a.list=a.list.map(l=>{let u={id:l.id,status_code:l.rslv?.status_code||null,response_body:l.rslv?.body||l.rslv?.truncated||null,error:l?.err,updated:l?.utmp,request_body:l?.reqbdy,expires:l?.expt,status:l.stts,queue_name:l?.qid};for(let f in u)u[f]===void 0&&delete u[f];return (u.status==="running"||u.status==="pending")&&(u.poll=f=>cn.call(this,{id:i+u.id,auth:s,service:n,owner:r,latency:f?.latency||1e3,queue:l?.qid,onResponse:f?.onResponse,onError:f?.onError})),u}),a}async function gn(t){await this.__connection,t=g.Params(t,{url:"string",method:["GET","POST","DELETE","PUT"],id:"string",queue:"string"},["url","method","id"]);let e=t?.service||this.service,n=t?.owner||this.owner,r=!!this.__user,s=`[${t.method.toUpperCase()}]${t.url.toLowerCase()}#${e}`,i=t.id,o=`${s}:${i}`,a=t?.queue;return a&&te?.[a]&&(te[a].remove(We[o]),delete We[o]),E.bind(this)("csr-cancel",{id:o,service:e,owner:n},{auth:r})}async function fn(t){await this.__connection;let e={name:"string",email:n=>(g.Email(n),n),subject:"string",message:"string"};return t=g.Params(t,e,["name","email","subject","message"]),await E.bind(this)("send-inquiry",t),"SUCCESS: Inquiry has been sent."}async function hn(t,e){if(await this.__connection,jr&&t instanceof FormData||Br&&t instanceof HTMLFormElement||Qr&&t instanceof SubmitEvent){if(!e)throw new c("Url string as a second argument is required when form is passed.",{code:"INVALID_PARAMETER"});let r=N(t);t={url:e,data:r.data,sync:true};}let n={url:r=>g.Url(r),data:r=>r,sync:["boolean",()=>true]};if(Array.isArray(t))for(let r of t)r=g.Params(r,n);else t=g.Params(t,n);return E.bind(this)("post-secure",t,{auth:true})}async function pn(t,e){await this.__connection;let{auth:n=false,method:r="POST",bypassAwaitConnection:s=false,responseType:i,contentType:o,tokenHeaders:a,progress:l}=e||{};if(e=Object.assign({auth:n,method:r,bypassAwaitConnection:s,responseType:i,contentType:o,tokenHeaders:a},{fetchOptions:{progress:l}}),typeof t!="object"&&(o==="application/json"||o===void 0))throw new c('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return E.bind(this)("mock",t,e)}async function mn(t,e){await this.__connection,t=g.Params(t||{},{access_group:r=>{if(r==="authorized"&&(r=1),r==="public"&&(r=0),typeof r!="number")throw new c('"access_group" should be type number.',{code:"INVALID_PARAMETER"});if(r<0)throw new c('"access_group" should be zero or a positive number.',{code:"INVALID_PARAMETER"});if(r>this.__user.access_group)throw new c("User has no access.",{code:"INVALID_REQUEST"});return r}});let n=await E.bind(this)("get-feed",t,{auth:true,fetchOptions:e});for(let r in n.list)n.list[r]=await ae.bind(this)(n.list[r]);return n}function pe(t){if(t===this.__user.user_id)throw new c(`"user_id" cannot be the user's own ID.`,{code:"INVALID_PARAMETER"});return g.UserId(t,'"user_id"')}async function _n(t,e){if(t=N(t,{ignoreEmpty:true}).data,t=g.Params(t,{subscriber:r=>g.UserId(r,'User ID in "subscriber"'),subscription:pe.bind(this),blocked:"boolean"}),!t.subscriber&&!t.subscription)throw new c('At least either "subscriber" or "subscription" should have a value.',{code:"INVALID_PARAMETER"});let n=await E.bind(this)("get-subscription",t,Object.assign({auth:true},{fetchOptions:e}));return n.list=n.list.map((r=>{let s={};if(r.sub){let i=r.sub.split("#");s.subscriber=i[2],s.subscription=i[0];}else s.subscriber=r.subscriber,s.subscription=r.subscription;return s.timestamp=r?.timestamp||r.stmp,s.blocked=r?.blocked||r.grp.substring(0,1)==="N",Object.assign(s,r.opt),s})),n}async function bn(t){await this.__connection,t=g.Params(t,{user_id:pe.bind(this),get_feed:["boolean",()=>false],get_notified:["boolean",()=>false],get_email:r=>{if(r&&!this.__user.email||!this.__user.email_verified)throw new c("User has no verified email address.",{code:"INVALID_REQUEST"});return !!r}},["user_id"]);let e=await E.bind(this)("subscription",{subscribe:t.user_id,option:{get_feed:t.get_feed,get_notified:t.get_notified,get_email:t.get_email||false}},{auth:true}),n={};if(e.sub){let r=e.sub.split("#");n.subscriber=r[2],n.subscription=r[0];}else n.subscriber=e.subscriber,n.subscription=e.subscription;return n.timestamp=e?.timestamp||e.stmp,n.blocked=e?.blocked||e.grp.substring(0,1)==="N",Object.assign(n,e.opt),n}async function yn(t){await this.__connection;let{user_id:e}=g.Params(t,{user_id:pe.bind(this)},["user_id"]);return await E.bind(this)("subscription",{unsubscribe:e},{auth:true})}async function wn(t){await this.__connection;let{user_id:e}=g.Params(t,{user_id:pe.bind(this)},["user_id"]);return await E.bind(this)("subscription",{block:e},{auth:true})}async function En(t){await this.__connection;let{user_id:e}=g.Params(t,{user_id:pe.bind(this)},["user_id"]);return await E.bind(this)("subscription",{unblock:e},{auth:true})}async function Rn(t,e){await this.__connection;let n=await F.bind(this)();t=g.Params(t,{user_id:o=>{if(o!==this.__user.user_id&&!n)throw new c("No access.",{code:"INVALID_REQUEST"});return o},group:o=>{if(o==="public"&&(o=0),o==="authorized"&&(o=1),typeof o!="number")throw new c('"group" should be type number | "public" | "authorized".',{code:"INVALID_PARAMETER"});return o}});let r=await E.bind(this)("get-newsletter-subscription",t,{auth:true,fetchOptions:e||null}),s=r?.list||r,i=[];Array.isArray(s)||(s=[]);for(let o of s){let a=o.subt.split("#"),l=true;a[0].charAt(0)==="@"&&(l=false,a[0]=a[0].substring(1));let u=parseInt(a[0]);i.push({timestamp:o.stmp,group:u,subscribed_email:a[1],active:l});}return r?.list?(r.list=i,r):i}async function An(t){await this.__connection;let e=g.Params(t||{},{email:n=>Array.isArray(n)&&n.length>0?n.length===1?g.Email(n[0]):n.map(r=>g.Email(r)):g.Email(n),group:["number","public","authorized","admin",n=>{if(typeof n!="string"||n.length>20||!/^[a-zA-Z0-9]+$/.test(n))throw new c('"group" should be an alphanumeric string without spaces and less than 20 characters.',{code:"INVALID_PARAMETER"});return n}],redirect:n=>g.Url(n)},this.__user?["group"]:["email","group"]);return E.bind(this)(`subscribe-${this.__user?"":"public-"}newsletter`,e,{auth:!!this.__user})}async function In(t){await this.__connection,t=g.Params(t,{group:["number","public","authorized","admin"]},["group"]);let e=Object.assign({action:"unsubscribe"},t);return E.bind(this)("subscribe-newsletter",e,{auth:true})}async function Tn(t,e){let n=await F.bind(this)(),r={message_id:"string",timestamp:"number",read:"number",complaint:"number",subject:"string",bounced:"number"};t||(e=Object.assign({ascending:false},e||{})),t=N(t).data,t=t||{searchFor:"timestamp",value:Date.now(),condition:"<",group:"public"},t=g.Params(t,{searchFor:["message_id","timestamp","subject","complaint","read","bounced"],value:l=>{if(typeof l!==r[t.searchFor])throw new c(`"value" type does not match the type of "${t.searchFor}" index.`,{code:"INVALID_PARAMETER"});if(typeof l=="string"&&!l)throw new c('"value" should not be empty string.',{code:"INVALID_PARAMETER"});return l},range:l=>{if(!t.hasOwnProperty("value")||typeof l!=typeof t.value)throw new c('"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 c("User should be logged in.",{code:"INVALID_REQUEST"});if(l==="authorized")return 1;if(typeof l=="number"){if(!n&&l>parseInt(this.user?.access_group||this.session?.idToken?.payload?.access_group))throw new c("User has no access.",{code:"INVALID_REQUEST"});return l}throw new c('"group" should be type: number | "public" | "authorized".',{code:"INVALID_PARAMETER"})}},["searchFor","value","group"]);let s=t.group===0?"get-public-newsletters":"get-newsletters",i=await E.bind(this)(s,t,Object.assign({method:"get",auth:s==="get-public-newsletters"?!!this.__user:true},{fetchOptions:e})),o={message_id:"mid",timestamp:"stmp",complaint:"cmpl",read:"read",subject:"subj",bounced:"bnce",url:"url",delivered:"delv"},a={message_id:"",timestamp:0,complaint:0,read:0,subject:"",bounced:"",url:"",delivered:0};return i.list=i.list.map(l=>{let u={};for(let f in o)u[f]=l[o[f]]||a[f];return u.bounced=String(u.bounced),u}),i}async function Pn(t){let e=g.Params(t,{user_id:r=>g.UserId(r,'"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 F.bind(this)()){if(!this.__user)throw new c("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new c("Invalid access.",{code:"INVALID_REQUEST"})}return await E.bind(this)("block-account",e,{auth:true})}async function Sn(t){let e=g.Params(t,{user_id:r=>g.UserId(r,'"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 F.bind(this)()){if(!this.__user)throw new c("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new c("Invalid access.",{code:"INVALID_REQUEST"})}return await E.bind(this)("block-account",e,{auth:true})}async function kn(t){let e=g.Params(t,{user_id:r=>g.UserId(r,'"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 F.bind(this)()){if(!this.__user)throw new c("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new c("Invalid access.",{code:"INVALID_REQUEST"})}return await E.bind(this)("remove-account",e,{auth:true})}async function vn(t,e){let n={email:i=>g.Email(i),password:i=>g.Password(i),name:"string",username:"string",gender:"string",address:i=>{if(!i)return "";if(typeof i=="string")return i;if(typeof i=="object")return JSON.stringify(i)},birthdate:i=>g.Birthdate(i),phone_number:i=>g.PhoneNumber(i),picture:i=>{if(i)return g.Url(i)},profile:i=>{if(i)return g.Url(i)},website:i=>{if(i)return g.Url(i)},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:i=>{try{typeof i=="string"&&(i=i==="admin"?99:parseInt(i));}catch{throw new c('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof i!="number"||i<1||i>100)throw new c('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"});return i}},r=g.Params(t,n,["email"]);if(e=g.Params(e,{confirmation_url:i=>{let o=i;if(typeof i=="string")o=g.Url(i);else throw new c('"options.confirmation_url" should be type: <string>.',{code:"INVALID_PARAMETER"});if(o&&!r.email)throw new c('"email" is required for signup confirmation.',{code:"INVALID_PARAMETER"});return o},email_subscription:i=>{if(typeof i!="boolean")throw new c('"options.email_subscription" should be type: <boolean>.',{code:"INVALID_PARAMETER"});if(!e?.confirmation_url)throw new c('"options.confirmation_url" is required for email subscription.',{code:"INVALID_PARAMETER"});return i},template:i=>{if(typeof i!="object"||!i.url||!i.subject)throw new c('"options.template" should be type: <object> with "url" and "subject".',{code:"INVALID_PARAMETER"});return {url:g.Url(i.url),subject:i.subject}}}),r.signup_confirmation=e?.confirmation_url||true,r.email_subscription=e?.email_subscription||false,r.template=e?.template||{},!await F.bind(this)()){if(!this.__user)throw new c("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new c("Invalid access.",{code:"INVALID_REQUEST"})}return await E.bind(this)("admin-signup",r,{auth:true})}async function xn(t){let e={email:i=>g.Email(i),password:i=>g.Password(i),openid_id:"string",name:"string",username:"string",gender:"string",address:i=>{if(!i)return "";if(typeof i=="string")return i;if(typeof i=="object")return JSON.stringify(i)},birthdate:i=>g.Birthdate(i),phone_number:i=>g.PhoneNumber(i),picture:i=>i?g.Url(i):"",profile:i=>i?g.Url(i):"",website:i=>i?g.Url(i):"",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:i=>{try{typeof i=="string"&&(i=parseInt(i));}catch{throw new c('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof i!="number"||i<1||i>100)throw new c('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"});return i}},n=["email","password"],r=g.Params(t,e,n);if(!await F.bind(this)()){if(!this.__user)throw new c("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new c("Invalid access.",{code:"INVALID_REQUEST"})}return await E.bind(this)("admin-signup",r,{auth:true})}async function Dn(t){if(t=g.Params(t,{user_id:n=>g.UserId(n,'"user_id"'),access_group:n=>{try{typeof n=="string"&&(n=parseInt(n));}catch{throw new c('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof n=="number"&&n>0&&n<100)return n;throw new c('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"})}},["user_id","access_group"]),!await F.bind(this)()){if(!this.__user)throw new c("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new c("Invalid access.",{code:"INVALID_REQUEST"})}return await E.bind(this)("grant-access",t,{auth:true})}async function Un(t,e){if(t=g.Params(t,{email:"string"}),!await F.bind(this)()){if(!this.__user)throw new c("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new c("Invalid access.",{code:"INVALID_REQUEST"})}let r=await E.bind(this)("invitation-list",Object.assign({mode:"search"},t),{fetchOptions:e,auth:true});return r.list=r.list.map(s=>le(s.user)),r}async function Nn(t){if(t=g.Params(t,{email:n=>g.Email(n)},["email"]),!await F.bind(this)()){if(!this.__user)throw new c("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new c("Invalid access.",{code:"INVALID_REQUEST"})}return await E.bind(this)("invitation-list",Object.assign({mode:"cancel"},t),{auth:true})}async function Cn(t){if(t=g.Params(t,{email:n=>g.Email(n)},["email"]),!await F.bind(this)()){if(!this.__user)throw new c("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new c("Invalid access.",{code:"INVALID_REQUEST"})}return await E.bind(this)("invitation-list",Object.assign({mode:"resend"},t),{auth:true})}async function Ln(t){let e=g.Params(t,{user_id:o=>g.UserId(o,'"user_id"'),email:o=>g.Email(o),address:o=>{if(!o)return "";if(typeof o=="string")return o;if(typeof o=="object")return JSON.stringify(o)},name:"string",gender:"string",birthdate:o=>o?g.Birthdate(o):"",phone_number:o=>o?g.PhoneNumber(o):"",email_public:"boolean",phone_number_public:"boolean",address_public:"boolean",gender_public:"boolean",birthdate_public:"boolean",misc:"string",picture:o=>o?g.Url(o):"",profile:o=>o?g.Url(o):"",nickname:"string",website:o=>o?g.Url(o):""},["user_id"]),n=e.service,r=e.owner;if(delete e.service,delete e.owner,Object.keys(e).filter(o=>o!=="user_id"&&e[o]!==void 0).length===0)throw new c("At least one attribute to update is required.",{code:"INVALID_PARAMETER"});if(!await F.bind(this)()){if(!this.__user)throw new c("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new c("Invalid access.",{code:"INVALID_REQUEST"})}e.email&&(e.preferred_username=(n||this.service)+"-"+M.hash(e.email));let i={attributes:e};return n&&r&&(i.service=n,i.owner=r),await E.bind(this)("admin-edit-profile",i,{auth:true})}async function On(t){if(typeof window>"u"||window._runningInNodeJS)throw new c("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.__connection,!t.endpoint)throw new c("Missing parameter: endpoint",{code:"INVALID_PARAMETER"});if(!t.keys||!t.keys.p256dh||!t.keys.auth)throw new c("Missing parameter: keys.p256dh or keys.auth",{code:"INVALID_PARAMETER"});return await E.bind(this)("store-subscription",{endpoint:t.endpoint,keys:t.keys},{auth:true}),"SUCCESS: Subscribed to receive notifications."}async function Mn(t){if(typeof window>"u"||window._runningInNodeJS)throw new c("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.__connection,!t.endpoint)throw new c("Missing parameter: endpoint",{code:"INVALID_PARAMETER"});if(!t.keys||!t.keys.p256dh||!t.keys.auth)throw new c("Missing parameter: keys.p256dh or keys.auth",{code:"INVALID_PARAMETER"});return await E.bind(this)("delete-subscription",{endpoint:t.endpoint,keys:t.keys},{auth:true}),"SUCCESS: Unsubscribed from notifications."}async function Fn(){if(typeof window>"u"||window._runningInNodeJS)throw new c("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 qn(t,e){if(typeof window>"u"||window._runningInNodeJS)throw new c("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});await this.__connection;let{title:n,body:r}=N(t||{},{nullIfEmpty:true}).data;if(!n)throw new c("Missing parameter: message title",{code:"INVALID_PARAMETER"});if(!r)throw new c("Missing parameter: message body",{code:"INVALID_PARAMETER"});let s={title:n,body:r};return e?(typeof e=="string"&&(e=[e]),s.user_ids=e):s.user_ids="all_users",await E.bind(this)("push-notification",s,{auth:true}),"SUCCESS: Notification sent."}async function Vn(t){await this.__connection,t=g.Params(t,{spell:"string",name:"string",magic:n=>n},["spell","name"]);await E.bind(this)("castspell",t);return `The spell "${t.spell}" has been cast.`}async function $n(t){return await this.__connection,t=g.Params(t||{},{search:["spell","name",()=>"spell"],value:"string"}),await E.bind(this)("getspell",t)}async function jn(t){await this.__connection,t=g.Params(t,{message:"string",name:"string"},["message","name"]);let e=await E.bind(this)("dopamine",t,{auth:true}),n=e?.previous_message?.message,r=e?.previous_message?.name;if(V())n&&r&&window.alert(`${r} said: ${n}`),window.location.href=e.video;else return n&&r?`${r} said: ${n}
215
+ `,o=new Blob([i],{type:"application/javascript"});te=new Worker(URL.createObjectURL(o)),te.onmessage=a=>{s.readyState===1&&s.send(JSON.stringify({action:"keepAlive"}));},r(s);},s.onmessage=async i=>{let o="";try{o=JSON.parse(decodeURI(i.data)),this.log("socket onmessage",o);}catch{return}let a;switch(true){case !!o?.["#message"]:a="message";break;case !!o?.["#private"]:a="private";break;case !!o?.["#notice"]:a="notice";break;case !!o?.["#rtc"]:a="rtc";break;case !!o?.["#error"]:a="error";break}if(!a)return;let l={type:a,message:o?.["#rtc"]||o?.["#message"]||o?.["#private"]||o?.["#notice"]||o?.["#error"]||null,sender:o?.["#user_id"]||null,sender_cid:o?.["#scid"]?"cid:"+o["#scid"]:null,sender_rid:o?.["#srid"]||null,code:o?.["#code"]||null};if(a==="notice")t(l);else if(a==="rtc"){if(l.sender!==this.user.user_id){let u=l.message;if(u.hungup){Q[l.sender_cid]&&(Q[l.sender_cid](false),delete Q[l.sender_cid]),z[l.sender_cid]&&delete z[l.sender_cid],T?.[l.sender_cid]&&K.bind(this)({cid:l.sender_cid}),l.type="rtc:closed",t(l);return}if(u.candidate&&He.bind(this)(u.candidate,l.sender_cid),u.sdpoffer&&(Ke.bind(this)(u.sdpoffer,l.sender_cid),z[l.sender_cid]||(z[l.sender_cid]=l.sender_cid,delete l.message,l.connectRTC=tn.bind(this)(l),l.type="rtc:incoming",l.hangup=(()=>{T[l.sender_cid]?K.bind(this)({cid:l.sender_cid}):z[l.sender_cid]&&(delete z[l.sender_cid],s.send(JSON.stringify({action:"rtc",uid:l.sender_cid,content:{hungup:this.user.user_id},token:this.session.accessToken.jwtToken})));}).bind(this),t(l))),u.pickup&&Q[l.sender_cid]&&(Q[l.sender_cid](true),delete Q[l.sender_cid]),u.sdpanswer&&T[l.sender_cid])if(T[l.sender_cid].signalingState==="have-local-offer")await T[l.sender_cid].setRemoteDescription(new RTCSessionDescription(u.sdpanswer));else throw new c("Invalid signaling state.",{code:"INVALID_REQUEST"})}}else t(l);},s.onclose=()=>{pe?(this.log("realtime onclose","WebSocket connection closed."),t({type:"close",message:"WebSocket connection closed."})):(this.log("realtime onclose","WebSocket unexpected close."),t({type:"error",message:"Skapi: WebSocket unexpected close."}),le++,le<3?(this.log("realtime onclose","Reconnecting to WebSocket server..."+le),t({type:"reconnect",message:"Reconnecting to WebSocket server..."+le}),Ue.bind(this)(t,3e3,"reconnect")):(this.log("realtime onclose","Max reconnection attempts reached."),t({type:"error",message:"Skapi: Max reconnection attempts reached."})));},s.onerror=()=>{this.log("realtime onerror","WebSocket connection error."),t({type:"error",message:"Skapi: WebSocket connection error."});};},e);});}async function on(t,e,n){if(typeof window>"u"||window._runningInNodeJS)throw new c("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});let r=this.__socket?await this.__socket:this.__socket;if(!r)throw new c("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});if(!e)throw new c("No recipient.",{code:"INVALID_REQUEST"});await oe.bind(this)(),t=N(t).data;let s="";if(n&&(n=g.Params(n,{config:{always:"boolean"},title:"string",body:"string"},["title","body"]),s=JSON.stringify({title:n.title,body:n.body}),new Blob([s]).size>3072))throw new c("Notification size exceeds 3kb.",{code:"INVALID_PARAMETER"});if(r.readyState===1){try{g.UserId(e),r.send(JSON.stringify({action:"sendMessage",uid:e,content:t,notification:s,notificationConfig:n?.config||{},token:`IdT:${this.service}:${this.owner}:`+(this.bearerToken||this.session?.idToken?.jwtToken||"null")}));}catch(i){if(this.log("postRealtime:err",{err:i}),ne!==e)throw new c(`User has not joined to the recipient group. Run joinRealtime({ group: "${e}" })`,{code:"INVALID_REQUEST"});r.send(JSON.stringify({action:"broadcast",rid:e,content:t,notification:s,notificationConfig:n?.config||{},token:`IdT:${this.service}:${this.owner}:`+(this.bearerToken||this.session?.idToken?.jwtToken||"null")}));}return {type:"success",message:"Message sent."}}throw new c("Realtime connection is not open. Try reconnecting with connectRealtime().",{code:"INVALID_REQUEST"})}async function ze(t){if(typeof window>"u"||window._runningInNodeJS)throw new c("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});let e=this.__socket?await this.__socket:this.__socket;if(!e)throw new c("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});await oe.bind(this)(),t=N(t,{nullIfEmpty:true}).data;let{group:n=null}=t;if(!n&&!ne)return {type:"success",message:"Left realtime message group."};if(n!==null&&typeof n!="string")throw new c('"group" must be a string | null.',{code:"INVALID_PARAMETER"});return e.send(JSON.stringify({action:"joinRoom",rid:n,token:this.session.accessToken.jwtToken})),ne=n,{type:"success",message:n?`Joined realtime message group: "${n}".`:"Left realtime message group."}}async function an(t,e){t=g.Params(t,{user_id:r=>g.UserId(r,'User ID in "user_id"'),group:["string",()=>{if(!ne)throw new c('No group has been joined. Otherwise "group" is required.',{code:"INVALID_REQUEST"});return ne}]});let n=await E.bind(this)("get-ws-group",t,{fetchOptions:e,auth:true,method:"post"});return n.list=n.list.map(r=>({user_id:r.uid.split("#")[1],cid:"cid:"+r.cid})),n}async function cn(t,e){if(await this.__connection,t||(t={searchFor:"group",value:" ",condition:">"}),t=g.Params(t,{searchFor:["group","number_of_users",()=>"group"],value:["string","number",()=>t?.searchFor&&t?.searchFor==="number_of_users"?0:" "],condition:[">",">=","=","<","<=","!=","gt","gte","eq","lt","lte","ne"],range:["string","number"]}),t.condition||(t.value===" "||!t.value?t.condition=">":t.condition="="),t.range&&t.condition&&delete t.condition,t.searchFor==="number_of_users"&&typeof t.value!="number")throw new c('"value" must be a number.',{code:"INVALID_PARAMETER"});if(t.searchFor==="group"&&typeof t.value!="string")throw new c('"value" must be a string.',{code:"INVALID_PARAMETER"});if(t.hasOwnProperty("range")&&typeof t.range!=typeof t.value)throw new c(`"range" must be a ${typeof t.value}.`,{code:"INVALID_PARAMETER"});let n=await E.bind(this)("get-ws-group",t,{fetchOptions:e,auth:true,method:"post"});return n.list=n.list.map(r=>({group:r.rid.split("#")[1],number_of_users:r.cnt})),n}var Hr=typeof FormData<"u",Wr=typeof HTMLFormElement<"u",zr=typeof SubmitEvent<"u",J={},me={},G={};function Je(t){return Object.freeze({id:t,status:"stopped"})}function un(t){return !!t&&typeof t=="object"&&t.status==="stopped"}function dn({id:t,auth:e,service:n,owner:r,latency:s=1e3,queue:i,onResponse:o,onError:a}){if(typeof s!="number")throw new c('"latency" should be a number.',{code:"INVALID_PARAMETER"});if(s<0)throw new c('"latency" should be a non-negative number.',{code:"INVALID_PARAMETER"});i&&!J?.[i]&&(J[i]=new ln({breakWhenError:false,batchSize:1}));let l={stop:null,aborted:false,queue:i};G[t]=l;let u=()=>{G[t]===l&&delete G[t];},f=()=>new Promise((p,w)=>{let h=false;if(l.aborted){u(),p(Je(t));return}let m=setInterval(async()=>{try{let I=await E.bind(this)("csr-poll",{id:t,service:n,owner:r},{auth:e});if(I.status==="running"||I.status==="pending"||h)return;h=!0,o&&o(I),clearInterval(m),u(),p(I);}catch(I){if(h)return;h=true,a&&a(I),clearInterval(m),u(),w(I);}},s);l.stop=()=>{h||(h=true,clearInterval(m),u(),p(Je(t)));};}),d=()=>{let p=G[t];p&&(p.stop?p.stop():(p.aborted=true,delete G[t]));};if(i){let p=new Promise((w,h)=>{let m=false,I=J[i].add([async()=>{try{let _=await f();return m||(m=!0,w(_)),_}catch(_){throw m||(m=true,h(_)),_}}])[0];me[t]=I,l.stop=()=>{if(!m){l.aborted=true;try{J[i]&&J[i].remove(me[t]);}catch{}delete me[t],u(),m=true,w(Je(t));}};});return Object.assign(p,{stop:d})}else return Object.assign(f(),{stop:d})}function gn(t){let e=0,n=[];if(t?.id){if(t.url&&t.method){let r=t.service||this.service;n.push(`[${t.method.toUpperCase()}]${t.url.toLowerCase()}#${r}:${t.id}`);}n.push(t.id);}else if(t?.queue)for(let r in G)G[r]?.queue===t.queue&&n.push(r);else for(let r in G)n.push(r);for(let r of n){let s=G[r];s&&(s.stop?s.stop():(s.aborted=true,delete G[r]),e+=1);}return e}function fn(t,e){if(!t.queue)throw new c('"queue" is required.',{code:"INVALID_PARAMETER"});let n={service:t.service||this.service,owner:t.owner||this.owner,queue:t.queue+":"};return E.bind(this)("csr-poll",n,{auth:true})}async function hn(t){let e=false;if(typeof t.poll=="number"&&t.poll<0)throw new c('"poll" should be a non-negative number.',{code:"INVALID_PARAMETER"});let n=t?.onResponse,r=t?.onError,s=typeof t.poll=="number"?t.poll:t.poll?1e3:0;delete t.poll,s&&!t.queue&&(t.queue=(this.__user?.user_id||"anonymous")+"-"+re());let i=l=>{for(let u in l)if(typeof l[u]=="string"&&l[u].includes("$CLIENT_SECRET")){e=true;break}};if(t=g.Params(t,{url:l=>{if(!l||typeof l!="string")throw new c('"url" should be type: <string>.',{code:"INVALID_PARAMETER"});return g.Url(l),l.includes("$CLIENT_SECRET")&&(e=true),l},clientSecretName:"string",method:l=>{if(l&&typeof l!="string")throw new c('"method" should be either "GET" or "POST" or "DELETE" or "PUT".',{code:"INVALID_PARAMETER"});let u=l.toLowerCase();if(u!=="get"&&u!=="post"&&u!=="delete"&&u!=="put")throw new c('"method" should be either "GET" or "POST" or "DELETE" or "PUT".',{code:"INVALID_PARAMETER"});return u},headers:l=>{if(l&&typeof l!="object")throw new c('"headers" should be type: <object>.',{code:"INVALID_PARAMETER"});return i(l),l},data:l=>{if(l&&typeof l!="object")throw new c('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return i(l),l},params:l=>{if(l&&typeof l!="object")throw new c('"params" should be type: <object>.',{code:"INVALID_PARAMETER"});return i(l),l},expires:"number",queue:"string"},["clientSecretName","method","url"]),!e)throw new c(`At least one parameter value should include "$CLIENT_SECRET" in ${t.method.toLowerCase()==="post"?'"data"':'"params"'} or "headers".`,{code:"INVALID_PARAMETER"});await this.__connection;let o=!!this.__user,a=()=>E.bind(this)("csr",t,{auth:o,tokenHeaders:{accessToken:!!o}}).then(l=>{if(l.status==="running"||l.status==="pending"){let u=`[${t.method.toUpperCase()}]${t.url.toLowerCase()}`,f=t.service||this.service,d=t.owner||this.owner,p=`${u}#${f}:${l.id}`;Object.assign(l,{poll:w=>dn.call(this,{id:p,auth:o,service:f,owner:d,latency:w?.latency||1e3,queue:t?.queue,onResponse:n,onError:r})});}return n?n(l):l}).catch(l=>{if(r)return r(l);throw l});if(t?.queue){let l="base:"+t.queue;return J?.[l]||(J[l]=new ln({breakWhenError:false,batchSize:1})),new Promise((u,f)=>{J[l].add([async()=>{try{let d=await a();if(s>0){let p=d.poll({latency:s});return u(p),p}return u(d),d}catch(d){throw f(d),d}}]);})}else return a()}async function pn(t,e){await this.__connection;let n=t.service||this.service,r=t.owner||this.owner;t=g.Params(t,{url:"string",method:["GET","POST","DELETE","PUT"],queue:"string",status:["pending","running","resolved","failed"]},["url","method"]);let s=!!this.__user,i=`[${t.method.toUpperCase()}]${t.url.toLowerCase()}#${n}:`,o={id:i,queue:t?.queue,status:t?.status,service:n,owner:r};Object.keys(o).forEach(l=>{o[l]||delete o[l];}),o.queue&&delete o.id;let a=await E.bind(this)("csr-poll",o,{auth:s,fetchOptions:e});return a.list=a.list.map(l=>{let u={id:l.id,status_code:l.rslv?.status_code||null,response_body:l.rslv?.body||l.rslv?.truncated||null,error:l?.err,updated:l?.utmp,request_body:l?.reqbdy,expires:l?.expt,status:l.stts,queue_name:l?.qid};for(let f in u)u[f]===void 0&&delete u[f];return (u.status==="running"||u.status==="pending")&&(u.poll=f=>dn.call(this,{id:i+u.id,auth:s,service:n,owner:r,latency:f?.latency||1e3,queue:l?.qid,onResponse:f?.onResponse,onError:f?.onError})),u}),a}async function mn(t){await this.__connection,t=g.Params(t,{url:"string",method:["GET","POST","DELETE","PUT"],id:"string",queue:"string"},["url","method","id"]);let e=t?.service||this.service,n=t?.owner||this.owner,r=!!this.__user,s=`[${t.method.toUpperCase()}]${t.url.toLowerCase()}#${e}`,i=t.id,o=`${s}:${i}`,a=t?.queue;return a&&J?.[a]&&(J[a].remove(me[o]),delete me[o]),E.bind(this)("csr-cancel",{id:o,service:e,owner:n},{auth:r})}async function _n(t){await this.__connection;let e={name:"string",email:n=>(g.Email(n),n),subject:"string",message:"string"};return t=g.Params(t,e,["name","email","subject","message"]),await E.bind(this)("send-inquiry",t),"SUCCESS: Inquiry has been sent."}async function bn(t,e){if(await this.__connection,Hr&&t instanceof FormData||Wr&&t instanceof HTMLFormElement||zr&&t instanceof SubmitEvent){if(!e)throw new c("Url string as a second argument is required when form is passed.",{code:"INVALID_PARAMETER"});let r=N(t);t={url:e,data:r.data,sync:true};}let n={url:r=>g.Url(r),data:r=>r,sync:["boolean",()=>true]};if(Array.isArray(t))for(let r of t)r=g.Params(r,n);else t=g.Params(t,n);return E.bind(this)("post-secure",t,{auth:true})}async function yn(t,e){await this.__connection;let{auth:n=false,method:r="POST",bypassAwaitConnection:s=false,responseType:i,contentType:o,tokenHeaders:a,progress:l}=e||{};if(e=Object.assign({auth:n,method:r,bypassAwaitConnection:s,responseType:i,contentType:o,tokenHeaders:a},{fetchOptions:{progress:l}}),typeof t!="object"&&(o==="application/json"||o===void 0))throw new c('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return E.bind(this)("mock",t,e)}async function wn(t,e){await this.__connection,t=g.Params(t||{},{access_group:r=>{if(r==="authorized"&&(r=1),r==="public"&&(r=0),typeof r!="number")throw new c('"access_group" should be type number.',{code:"INVALID_PARAMETER"});if(r<0)throw new c('"access_group" should be zero or a positive number.',{code:"INVALID_PARAMETER"});if(r>this.__user.access_group)throw new c("User has no access.",{code:"INVALID_REQUEST"});return r}});let n=await E.bind(this)("get-feed",t,{auth:true,fetchOptions:e});for(let r in n.list)n.list[r]=await ce.bind(this)(n.list[r]);return n}function _e(t){if(t===this.__user.user_id)throw new c(`"user_id" cannot be the user's own ID.`,{code:"INVALID_PARAMETER"});return g.UserId(t,'"user_id"')}async function En(t,e){if(t=N(t,{ignoreEmpty:true}).data,t=g.Params(t,{subscriber:r=>g.UserId(r,'User ID in "subscriber"'),subscription:_e.bind(this),blocked:"boolean"}),!t.subscriber&&!t.subscription)throw new c('At least either "subscriber" or "subscription" should have a value.',{code:"INVALID_PARAMETER"});let n=await E.bind(this)("get-subscription",t,Object.assign({auth:true},{fetchOptions:e}));return n.list=n.list.map((r=>{let s={};if(r.sub){let i=r.sub.split("#");s.subscriber=i[2],s.subscription=i[0];}else s.subscriber=r.subscriber,s.subscription=r.subscription;return s.timestamp=r?.timestamp||r.stmp,s.blocked=r?.blocked||r.grp.substring(0,1)==="N",Object.assign(s,r.opt),s})),n}async function Rn(t){await this.__connection,t=g.Params(t,{user_id:_e.bind(this),get_feed:["boolean",()=>false],get_notified:["boolean",()=>false],get_email:r=>{if(r&&!this.__user.email||!this.__user.email_verified)throw new c("User has no verified email address.",{code:"INVALID_REQUEST"});return !!r}},["user_id"]);let e=await E.bind(this)("subscription",{subscribe:t.user_id,option:{get_feed:t.get_feed,get_notified:t.get_notified,get_email:t.get_email||false}},{auth:true}),n={};if(e.sub){let r=e.sub.split("#");n.subscriber=r[2],n.subscription=r[0];}else n.subscriber=e.subscriber,n.subscription=e.subscription;return n.timestamp=e?.timestamp||e.stmp,n.blocked=e?.blocked||e.grp.substring(0,1)==="N",Object.assign(n,e.opt),n}async function An(t){await this.__connection;let{user_id:e}=g.Params(t,{user_id:_e.bind(this)},["user_id"]);return await E.bind(this)("subscription",{unsubscribe:e},{auth:true})}async function In(t){await this.__connection;let{user_id:e}=g.Params(t,{user_id:_e.bind(this)},["user_id"]);return await E.bind(this)("subscription",{block:e},{auth:true})}async function Tn(t){await this.__connection;let{user_id:e}=g.Params(t,{user_id:_e.bind(this)},["user_id"]);return await E.bind(this)("subscription",{unblock:e},{auth:true})}async function Pn(t,e){await this.__connection;let n=await F.bind(this)();t=g.Params(t,{user_id:o=>{if(o!==this.__user.user_id&&!n)throw new c("No access.",{code:"INVALID_REQUEST"});return o},group:o=>{if(o==="public"&&(o=0),o==="authorized"&&(o=1),typeof o!="number")throw new c('"group" should be type number | "public" | "authorized".',{code:"INVALID_PARAMETER"});return o}});let r=await E.bind(this)("get-newsletter-subscription",t,{auth:true,fetchOptions:e||null}),s=r?.list||r,i=[];Array.isArray(s)||(s=[]);for(let o of s){let a=o.subt.split("#"),l=true;a[0].charAt(0)==="@"&&(l=false,a[0]=a[0].substring(1));let u=parseInt(a[0]);i.push({timestamp:o.stmp,group:u,subscribed_email:a[1],active:l});}return r?.list?(r.list=i,r):i}async function Sn(t){await this.__connection;let e=g.Params(t||{},{email:n=>Array.isArray(n)&&n.length>0?n.length===1?g.Email(n[0]):n.map(r=>g.Email(r)):g.Email(n),group:["number","public","authorized","admin",n=>{if(typeof n!="string"||n.length>20||!/^[a-zA-Z0-9]+$/.test(n))throw new c('"group" should be an alphanumeric string without spaces and less than 20 characters.',{code:"INVALID_PARAMETER"});return n}],redirect:n=>g.Url(n)},this.__user?["group"]:["email","group"]);return E.bind(this)(`subscribe-${this.__user?"":"public-"}newsletter`,e,{auth:!!this.__user})}async function kn(t){await this.__connection,t=g.Params(t,{group:["number","public","authorized","admin"]},["group"]);let e=Object.assign({action:"unsubscribe"},t);return E.bind(this)("subscribe-newsletter",e,{auth:true})}async function vn(t,e){let n=await F.bind(this)(),r={message_id:"string",timestamp:"number",read:"number",complaint:"number",subject:"string",bounced:"number"};t||(e=Object.assign({ascending:false},e||{})),t=N(t).data,t=t||{searchFor:"timestamp",value:Date.now(),condition:"<",group:"public"},t=g.Params(t,{searchFor:["message_id","timestamp","subject","complaint","read","bounced"],value:l=>{if(typeof l!==r[t.searchFor])throw new c(`"value" type does not match the type of "${t.searchFor}" index.`,{code:"INVALID_PARAMETER"});if(typeof l=="string"&&!l)throw new c('"value" should not be empty string.',{code:"INVALID_PARAMETER"});return l},range:l=>{if(!t.hasOwnProperty("value")||typeof l!=typeof t.value)throw new c('"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 c("User should be logged in.",{code:"INVALID_REQUEST"});if(l==="authorized")return 1;if(typeof l=="number"){if(!n&&l>parseInt(this.user?.access_group||this.session?.idToken?.payload?.access_group))throw new c("User has no access.",{code:"INVALID_REQUEST"});return l}throw new c('"group" should be type: number | "public" | "authorized".',{code:"INVALID_PARAMETER"})}},["searchFor","value","group"]);let s=t.group===0?"get-public-newsletters":"get-newsletters",i=await E.bind(this)(s,t,Object.assign({method:"get",auth:s==="get-public-newsletters"?!!this.__user:true},{fetchOptions:e})),o={message_id:"mid",timestamp:"stmp",complaint:"cmpl",read:"read",subject:"subj",bounced:"bnce",url:"url",delivered:"delv"},a={message_id:"",timestamp:0,complaint:0,read:0,subject:"",bounced:"",url:"",delivered:0};return i.list=i.list.map(l=>{let u={};for(let f in o)u[f]=l[o[f]]||a[f];return u.bounced=String(u.bounced),u}),i}async function xn(t){let e=g.Params(t,{user_id:r=>g.UserId(r,'"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 F.bind(this)()){if(!this.__user)throw new c("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new c("Invalid access.",{code:"INVALID_REQUEST"})}return await E.bind(this)("block-account",e,{auth:true})}async function Dn(t){let e=g.Params(t,{user_id:r=>g.UserId(r,'"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 F.bind(this)()){if(!this.__user)throw new c("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new c("Invalid access.",{code:"INVALID_REQUEST"})}return await E.bind(this)("block-account",e,{auth:true})}async function Un(t){let e=g.Params(t,{user_id:r=>g.UserId(r,'"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 F.bind(this)()){if(!this.__user)throw new c("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new c("Invalid access.",{code:"INVALID_REQUEST"})}return await E.bind(this)("remove-account",e,{auth:true})}async function Nn(t,e){let n={email:i=>g.Email(i),password:i=>g.Password(i),name:"string",username:"string",gender:"string",address:i=>{if(!i)return "";if(typeof i=="string")return i;if(typeof i=="object")return JSON.stringify(i)},birthdate:i=>g.Birthdate(i),phone_number:i=>g.PhoneNumber(i),picture:i=>{if(i)return g.Url(i)},profile:i=>{if(i)return g.Url(i)},website:i=>{if(i)return g.Url(i)},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:i=>{try{typeof i=="string"&&(i=i==="admin"?99:parseInt(i));}catch{throw new c('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof i!="number"||i<1||i>100)throw new c('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"});return i}},r=g.Params(t,n,["email"]);if(e=g.Params(e,{confirmation_url:i=>{let o=i;if(typeof i=="string")o=g.Url(i);else throw new c('"options.confirmation_url" should be type: <string>.',{code:"INVALID_PARAMETER"});if(o&&!r.email)throw new c('"email" is required for signup confirmation.',{code:"INVALID_PARAMETER"});return o},email_subscription:i=>{if(typeof i!="boolean")throw new c('"options.email_subscription" should be type: <boolean>.',{code:"INVALID_PARAMETER"});if(!e?.confirmation_url)throw new c('"options.confirmation_url" is required for email subscription.',{code:"INVALID_PARAMETER"});return i},template:i=>{if(typeof i!="object"||!i.url||!i.subject)throw new c('"options.template" should be type: <object> with "url" and "subject".',{code:"INVALID_PARAMETER"});return {url:g.Url(i.url),subject:i.subject}}}),r.signup_confirmation=e?.confirmation_url||true,r.email_subscription=e?.email_subscription||false,r.template=e?.template||{},!await F.bind(this)()){if(!this.__user)throw new c("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new c("Invalid access.",{code:"INVALID_REQUEST"})}return await E.bind(this)("admin-signup",r,{auth:true})}async function Cn(t){let e={email:i=>g.Email(i),password:i=>g.Password(i),openid_id:"string",name:"string",username:"string",gender:"string",address:i=>{if(!i)return "";if(typeof i=="string")return i;if(typeof i=="object")return JSON.stringify(i)},birthdate:i=>g.Birthdate(i),phone_number:i=>g.PhoneNumber(i),picture:i=>i?g.Url(i):"",profile:i=>i?g.Url(i):"",website:i=>i?g.Url(i):"",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:i=>{try{typeof i=="string"&&(i=parseInt(i));}catch{throw new c('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof i!="number"||i<1||i>100)throw new c('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"});return i}},n=["email","password"],r=g.Params(t,e,n);if(!await F.bind(this)()){if(!this.__user)throw new c("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new c("Invalid access.",{code:"INVALID_REQUEST"})}return await E.bind(this)("admin-signup",r,{auth:true})}async function Ln(t){if(t=g.Params(t,{user_id:n=>g.UserId(n,'"user_id"'),access_group:n=>{try{typeof n=="string"&&(n=parseInt(n));}catch{throw new c('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof n=="number"&&n>0&&n<100)return n;throw new c('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"})}},["user_id","access_group"]),!await F.bind(this)()){if(!this.__user)throw new c("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new c("Invalid access.",{code:"INVALID_REQUEST"})}return await E.bind(this)("grant-access",t,{auth:true})}async function On(t,e){if(t=g.Params(t,{email:"string"}),!await F.bind(this)()){if(!this.__user)throw new c("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new c("Invalid access.",{code:"INVALID_REQUEST"})}let r=await E.bind(this)("invitation-list",Object.assign({mode:"search"},t),{fetchOptions:e,auth:true});return r.list=r.list.map(s=>ue(s.user)),r}async function Mn(t){if(t=g.Params(t,{email:n=>g.Email(n)},["email"]),!await F.bind(this)()){if(!this.__user)throw new c("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new c("Invalid access.",{code:"INVALID_REQUEST"})}return await E.bind(this)("invitation-list",Object.assign({mode:"cancel"},t),{auth:true})}async function Fn(t){if(t=g.Params(t,{email:n=>g.Email(n)},["email"]),!await F.bind(this)()){if(!this.__user)throw new c("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new c("Invalid access.",{code:"INVALID_REQUEST"})}return await E.bind(this)("invitation-list",Object.assign({mode:"resend"},t),{auth:true})}async function qn(t){let e=g.Params(t,{user_id:o=>g.UserId(o,'"user_id"'),email:o=>g.Email(o),address:o=>{if(!o)return "";if(typeof o=="string")return o;if(typeof o=="object")return JSON.stringify(o)},name:"string",gender:"string",birthdate:o=>o?g.Birthdate(o):"",phone_number:o=>o?g.PhoneNumber(o):"",email_public:"boolean",phone_number_public:"boolean",address_public:"boolean",gender_public:"boolean",birthdate_public:"boolean",misc:"string",picture:o=>o?g.Url(o):"",profile:o=>o?g.Url(o):"",nickname:"string",website:o=>o?g.Url(o):""},["user_id"]),n=e.service,r=e.owner;if(delete e.service,delete e.owner,Object.keys(e).filter(o=>o!=="user_id"&&e[o]!==void 0).length===0)throw new c("At least one attribute to update is required.",{code:"INVALID_PARAMETER"});if(!await F.bind(this)()){if(!this.__user)throw new c("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new c("Invalid access.",{code:"INVALID_REQUEST"})}e.email&&(e.preferred_username=(n||this.service)+"-"+M.hash(e.email));let i={attributes:e};return n&&r&&(i.service=n,i.owner=r),await E.bind(this)("admin-edit-profile",i,{auth:true})}async function Vn(t){if(typeof window>"u"||window._runningInNodeJS)throw new c("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.__connection,!t.endpoint)throw new c("Missing parameter: endpoint",{code:"INVALID_PARAMETER"});if(!t.keys||!t.keys.p256dh||!t.keys.auth)throw new c("Missing parameter: keys.p256dh or keys.auth",{code:"INVALID_PARAMETER"});return await E.bind(this)("store-subscription",{endpoint:t.endpoint,keys:t.keys},{auth:true}),"SUCCESS: Subscribed to receive notifications."}async function $n(t){if(typeof window>"u"||window._runningInNodeJS)throw new c("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.__connection,!t.endpoint)throw new c("Missing parameter: endpoint",{code:"INVALID_PARAMETER"});if(!t.keys||!t.keys.p256dh||!t.keys.auth)throw new c("Missing parameter: keys.p256dh or keys.auth",{code:"INVALID_PARAMETER"});return await E.bind(this)("delete-subscription",{endpoint:t.endpoint,keys:t.keys},{auth:true}),"SUCCESS: Unsubscribed from notifications."}async function jn(){if(typeof window>"u"||window._runningInNodeJS)throw new c("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 Bn(t,e){if(typeof window>"u"||window._runningInNodeJS)throw new c("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});await this.__connection;let{title:n,body:r}=N(t||{},{nullIfEmpty:true}).data;if(!n)throw new c("Missing parameter: message title",{code:"INVALID_PARAMETER"});if(!r)throw new c("Missing parameter: message body",{code:"INVALID_PARAMETER"});let s={title:n,body:r};return e?(typeof e=="string"&&(e=[e]),s.user_ids=e):s.user_ids="all_users",await E.bind(this)("push-notification",s,{auth:true}),"SUCCESS: Notification sent."}async function Qn(t){await this.__connection,t=g.Params(t,{spell:"string",name:"string",magic:n=>n},["spell","name"]);await E.bind(this)("castspell",t);return `The spell "${t.spell}" has been cast.`}async function Kn(t){return await this.__connection,t=g.Params(t||{},{search:["spell","name",()=>"spell"],value:"string"}),await E.bind(this)("getspell",t)}async function Hn(t){await this.__connection,t=g.Params(t,{message:"string",name:"string"},["message","name"]);let e=await E.bind(this)("dopamine",t,{auth:true}),n=e?.previous_message?.message,r=e?.previous_message?.name;if(V())n&&r&&window.alert(`${r} said: ${n}`),window.location.href=e.video;else return n&&r?`${r} said: ${n}
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 y=class{constructor(e,n,r,s){this.__version="1.7.3-beta.1";this.session=null;this.connection=null;this.__my_unique_ids={};this.__uniqueIdsPersistTimer=null;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,n,r){return g.Params(e,n,r)}};this.util={MD5:M,generateRandom:ne,toBase62:et,fromBase62:j,decodeServiceId:Ce,formatServiceId:tt,extractFormData:N,terminatePendingRequests:kt,request:(e,n,r)=>E.bind(this)(e,n,r,{ignoreService:true})};this.__network_logs=false;this.__endpoint_version="v1";this.__public_identifier="";this.bearerToken="";this.registerTicket=ot.bind(this);this.unregisterTicket=at.bind(this);if(!e||typeof e!="string")throw this._alert("Service ID is required."),new c("Service ID is required.",{code:"INVALID_PARAMETER"});let i=e.split("-").length;if(i===2||i===7)try{let w=Ce(e);r&&typeof r=="object"&&(s=r),n&&typeof n=="object"&&(r=n),n=w.owner,e=w.service;}catch{throw this._alert("Service ID is invalid."),new c("Service ID is invalid.",{code:"INVALID_PARAMETER"})}if(!n||typeof n!="string")throw this._alert("Owner ID is invalid."),new c("Owner ID is invalid.",{code:"INVALID_PARAMETER"});if(e.toLowerCase()==="service_id")throw this._alert('Replace "service_id" with your actual Service ID.'),new c("Service ID is required.",{code:"INVALID_PARAMETER"});if(n!==this.host)try{g.UserId(n,'"owner"');}catch{throw this._alert("Owner ID is invalid."),new c("Owner ID is invalid.",{code:"INVALID_PARAMETER"})}this.service=e,this.owner=n;let l=true,u=false;if(r&&(typeof r.refetchServiceInfo=="boolean"&&(u=r.refetchServiceInfo),typeof r.autoLogin=="boolean"&&(l=r.autoLogin),typeof r.requestBatchSize=="number")){if(r.requestBatchSize<1)throw new c('"requestBatchSize" must be greater than 0.',{code:"INVALID_PARAMETER"});this.requestBatchSize=r.requestBatchSize;}r?.eventListener&&typeof r.eventListener=="object"&&(r.eventListener?.onLogin&&typeof r.eventListener.onLogin=="function"&&(this.onLogin=r.eventListener.onLogin),r.eventListener?.onUserUpdate&&typeof r.eventListener.onUserUpdate=="function"&&(this.onUserUpdate=r.eventListener.onUserUpdate),r.eventListener?.onBatchProcess&&typeof r.eventListener.onBatchProcess=="function"&&(this.onBatchProcess=r.eventListener.onBatchProcess)),this.target_cdn=s?.target_cdn||this.target_cdn,this.hostDomain=s?.hostDomain||this.hostDomain,this.customApiDomain=s?.customApiDomain||this.customApiDomain,this.__network_logs=!!s?.network_logs;let f=`https://${this.target_cdn}.cloudfront.net`,d=e.substring(0,4);this.admin_endpoint=fetch(`${f}/${d}/admin-${this.__endpoint_version}.json`).then(w=>w.blob()).then(w=>new Promise((P,b)=>{let S=new FileReader;S.onloadend=()=>P(S.result),S.onerror=b,S.readAsDataURL(w);})).then(w=>{try{return typeof w=="string"?JSON.parse(atob(w.split(",")[1])):null}catch{throw new c("Service does not exist. Create your service from skapi.com",{code:"NOT_EXISTS"})}}),this.record_endpoint=fetch(`${f}/${d}/record-${this.__endpoint_version}.json`).then(w=>w.blob()).then(w=>new Promise((P,b)=>{let S=new FileReader;S.onloadend=()=>P(S.result),S.onerror=b,S.readAsDataURL(w);})).then(w=>{try{return typeof w=="string"?JSON.parse(atob(w.split(",")[1])):null}catch{throw new c("Service does not exist. Create your service from skapi.com",{code:"NOT_EXISTS"})}});let p=V();if(p&&!window.sessionStorage)throw this._alert("This browser is not supported."),new Error("This browser is not supported.");let _=p?JSON.parse(window.sessionStorage.getItem(`${e}#${n}`)||"null"):null;if(this.log("constructor:restore",_),_?.connection){for(let w in _)this[w]=_[w];_.__public_identifier||(this.__public_identifier=`${this.service}:${this.owner}:${ne(16)}`);}this.__authConnection=(async()=>{let w=await this.admin_endpoint,P={UserPoolId:w.userpool_id,ClientId:w.userpool_client};Ne()&&(P.Storage=window.localStorage),this.userPool=new CognitoUserPool(P);try{this.user||await q.bind(this)().getSession({skipUserUpdateEventTrigger:!0}),this.user&&(!_?.connection&&!l?X.bind(this)():(this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user)));}catch{}})();let h=p?window.sessionStorage.getItem(`${this.service}:uniqueids`):null;if(h)try{this.__my_unique_ids=JSON.parse(h);}catch{this.__my_unique_ids={};}this.__connection=(async()=>{let w=null;await this.record_endpoint,_?.connection||(w=this._updateConnection({refresh:u}));let P=()=>{if(this.__class_properties_has_been_cached)return;let b=()=>{let S={},v=["__startKeyHistory","__disabledAccount","__cached_requests","__request_signup_confirmation","__public_identifier","connection"];if(this.connection){for(let T of v)S[T]=this[T];p&&window.sessionStorage.setItem(`${e}#${n}`,JSON.stringify(S)),this.__class_properties_has_been_cached=true;}};return w instanceof Promise?w.then(()=>b()):b()};return p&&(window.addEventListener("beforeunload",()=>{this.closeRealtime(),P();}),window.addEventListener("visibilitychange",()=>{P();})),await w,await this.__authConnection,this.connection})(),this.__connection.then(w=>{((w?.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 n of this._userProfileListeners)typeof n=="function"&&n(e);}_runOnLoginListeners(e){for(let n of this._onLoginListeners)typeof n=="function"&&n(e);}get onBatchProcess(){return this._onBatchProcessListeners}set onBatchProcess(e){typeof e=="function"&&this._onBatchProcessListeners.push(e);}_alert(e){V()&&typeof window.alert=="function"&&window.alert(e);}async getConnectionInfo(e){e?.refresh&&(this.__connection instanceof Promise&&await this.__connection,this.__connection=this._updateConnection({refresh:true}));let r=await this.__connection,s=r?.user_agent||(V()&&typeof window.navigator?.userAgent=="string"?window.navigator.userAgent:`skapi-node/${globalThis?.process?.versions?.node||"unknown"}`);return {user_ip:r.ip,user_agent:s,user_location:r.locale,service_name:r.service_name,version:this.__version,service_description:r?.service_description||"",ai_agent:r?.ai_agent||"",conf:r?.opt}}async _updateConnection(e){let n=e?.refresh||false;try{this.connection=await E.bind(this)("service",{service:this.service,owner:this.owner,refresh:n},{bypassAwaitConnection:!0,method:"get"});}catch(r){throw this.log("connection fail",r),this._alert("Service is not available: "+(r.message||r.toString())),this.connection=null,r}return this.connection}async version(){if(await this.__connection,V()){let n=`Built with:
217
+ Watch the video here: ${e.video}`}var y=class{constructor(e,n,r,s){this.__version="1.7.7";this.session=null;this.connection=null;this.__my_unique_ids={};this.__uniqueIdsPersistTimer=null;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,n,r){return g.Params(e,n,r)}};this.util={MD5:M,generateRandom:re,toBase62:nt,fromBase62:j,decodeServiceId:Oe,formatServiceId:rt,extractFormData:N,terminatePendingRequests:xt,request:(e,n,r)=>E.bind(this)(e,n,r,{ignoreService:true})};this.__network_logs=false;this.__endpoint_version="v1";this.__public_identifier="";this.bearerToken="";this.registerTicket=ct.bind(this);this.unregisterTicket=lt.bind(this);if(!e||typeof e!="string")throw this._alert("Service ID is required."),new c("Service ID is required.",{code:"INVALID_PARAMETER"});let i=e.split("-").length;if(i===2||i===7)try{let m=Oe(e);r&&typeof r=="object"&&(s=r),n&&typeof n=="object"&&(r=n),n=m.owner,e=m.service;}catch{throw this._alert("Service ID is invalid."),new c("Service ID is invalid.",{code:"INVALID_PARAMETER"})}if(!n||typeof n!="string")throw this._alert("Owner ID is invalid."),new c("Owner ID is invalid.",{code:"INVALID_PARAMETER"});if(e.toLowerCase()==="service_id")throw this._alert('Replace "service_id" with your actual Service ID.'),new c("Service ID is required.",{code:"INVALID_PARAMETER"});if(n!==this.host)try{g.UserId(n,'"owner"');}catch{throw this._alert("Owner ID is invalid."),new c("Owner ID is invalid.",{code:"INVALID_PARAMETER"})}this.service=e,this.owner=n;let l=true,u=false;if(r&&(typeof r.refetchServiceInfo=="boolean"&&(u=r.refetchServiceInfo),typeof r.autoLogin=="boolean"&&(l=r.autoLogin),typeof r.requestBatchSize=="number")){if(r.requestBatchSize<1)throw new c('"requestBatchSize" must be greater than 0.',{code:"INVALID_PARAMETER"});this.requestBatchSize=r.requestBatchSize;}r?.eventListener&&typeof r.eventListener=="object"&&(r.eventListener?.onLogin&&typeof r.eventListener.onLogin=="function"&&(this.onLogin=r.eventListener.onLogin),r.eventListener?.onUserUpdate&&typeof r.eventListener.onUserUpdate=="function"&&(this.onUserUpdate=r.eventListener.onUserUpdate),r.eventListener?.onBatchProcess&&typeof r.eventListener.onBatchProcess=="function"&&(this.onBatchProcess=r.eventListener.onBatchProcess)),this.target_cdn=s?.target_cdn||this.target_cdn,this.hostDomain=s?.hostDomain||this.hostDomain,this.customApiDomain=s?.customApiDomain||this.customApiDomain,this.__network_logs=!!s?.network_logs;let f=`https://${this.target_cdn}.cloudfront.net`,d=e.substring(0,4);this.admin_endpoint=fetch(`${f}/${d}/admin-${this.__endpoint_version}.json`).then(m=>m.blob()).then(m=>new Promise((I,_)=>{let S=new FileReader;S.onloadend=()=>I(S.result),S.onerror=_,S.readAsDataURL(m);})).then(m=>{try{return typeof m=="string"?JSON.parse(atob(m.split(",")[1])):null}catch{throw new c("Service does not exist. Create your service from skapi.com",{code:"NOT_EXISTS"})}}),this.record_endpoint=fetch(`${f}/${d}/record-${this.__endpoint_version}.json`).then(m=>m.blob()).then(m=>new Promise((I,_)=>{let S=new FileReader;S.onloadend=()=>I(S.result),S.onerror=_,S.readAsDataURL(m);})).then(m=>{try{return typeof m=="string"?JSON.parse(atob(m.split(",")[1])):null}catch{throw new c("Service does not exist. Create your service from skapi.com",{code:"NOT_EXISTS"})}});let p=V();if(p&&!window.sessionStorage)throw this._alert("This browser is not supported."),new Error("This browser is not supported.");let w=p?JSON.parse(window.sessionStorage.getItem(`${e}#${n}`)||"null"):null;if(this.log("constructor:restore",w),w?.connection){for(let m in w)this[m]=w[m];w.__public_identifier||(this.__public_identifier=`${this.service}:${this.owner}:${re(16)}`);}this.__authConnection=(async()=>{let m=await this.admin_endpoint,I={UserPoolId:m.userpool_id,ClientId:m.userpool_client};Le()&&(I.Storage=window.localStorage),this.userPool=new CognitoUserPool(I);try{this.user||await q.bind(this)().getSession({skipUserUpdateEventTrigger:!0}),this.user&&(!w?.connection&&!l?Y.bind(this)():(this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user)));}catch{}})();let h=p?window.sessionStorage.getItem(`${this.service}:uniqueids`):null;if(h)try{this.__my_unique_ids=JSON.parse(h);}catch{this.__my_unique_ids={};}this.__connection=(async()=>{let m=null;await this.record_endpoint,w?.connection||(m=this._updateConnection({refresh:u}));let I=()=>{if(this.__class_properties_has_been_cached)return;let _=()=>{let S={},v=["__startKeyHistory","__disabledAccount","__cached_requests","__request_signup_confirmation","__public_identifier","connection"];if(this.connection){for(let P of v)S[P]=this[P];p&&window.sessionStorage.setItem(`${e}#${n}`,JSON.stringify(S)),this.__class_properties_has_been_cached=true;}};return m instanceof Promise?m.then(()=>_()):_()};return p&&(window.addEventListener("beforeunload",()=>{this.closeRealtime(),I();}),window.addEventListener("visibilitychange",()=>{I();})),await m,await this.__authConnection,this.connection})(),this.__connection.then(m=>{((m?.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 n of this._userProfileListeners)typeof n=="function"&&n(e);}_runOnLoginListeners(e){for(let n of this._onLoginListeners)typeof n=="function"&&n(e);}get onBatchProcess(){return this._onBatchProcessListeners}set onBatchProcess(e){typeof e=="function"&&this._onBatchProcessListeners.push(e);}_alert(e){V()&&typeof window.alert=="function"&&window.alert(e);}async getConnectionInfo(e){e?.refresh&&(this.__connection instanceof Promise&&await this.__connection,this.__connection=this._updateConnection({refresh:true}));let r=await this.__connection,s=r?.user_agent||(V()&&typeof window.navigator?.userAgent=="string"?window.navigator.userAgent:`skapi-node/${globalThis?.process?.versions?.node||"unknown"}`);return {user_ip:r.ip,user_agent:s,user_location:r.locale,service_name:r.service_name,version:this.__version,service_description:r?.service_description||"",ai_agent:r?.ai_agent||"",conf:r?.opt}}async _updateConnection(e){let n=e?.refresh||false;try{this.connection=await E.bind(this)("service",{service:this.service,owner:this.owner,refresh:n},{bypassAwaitConnection:!0,method:"get"});}catch(r){throw this.log("connection fail",r),this._alert("Service is not available: "+(r.message||r.toString())),this.connection=null,r}return this.connection}async version(){if(await this.__connection,V()){let n=`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(n,"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,n){if(this.__network_logs){if(n!==null&&typeof n=="object")try{V()?n=JSON.parse(JSON.stringify(n)):n=JSON.stringify(n,null,2);}catch{n=String(n);}else typeof n=="string"&&n.length>100&&(n=n.substring(0,100)+"...");console.log(`%c${e}:`,"color: blue;",n);}}getFeed(e,n){return mn.bind(this)(e,n)}closeRTC(e){return K.bind(this)(e)}connectRTC(e,n){return Zt.bind(this)(e,n)}connectRealtime(e){return xe.bind(this)(e)}spellcast(e){return Vn.bind(this)(e)}getspell(e){return $n.bind(this)(e)}dopamine(e){return jn.bind(this)(e)}getUniqueId(e,n){return Bt.bind(this)(e,n)}resendInvitation(e){return Cn.bind(this)(e)}cancelInvitation(e){return Nn.bind(this)(e)}getInvitations(e,n){return Un.bind(this)(e,n)}openIdLogin(e){return lt.bind(this)(e)}loginWithToken(e){return ut.bind(this)(e)}clientSecretRequest(e){return un.bind(this)(e)}clientSecretRequestHistory(e,n){return dn.bind(this)(e,n)}cancelClientSecretRequest(e){return gn.bind(this)(e)}clientSecretRequestQueueCount(e){return ln.bind(this)(e)}consumeTicket(e){return rt.bind(this)(e)}getConsumedTickets(e,n){return st.bind(this)(e,n)}getTickets(e,n){return it.bind(this)(e,n)}closeRealtime(){return nn.bind(this)()}getRealtimeUsers(e,n){return sn.bind(this)(e,n)}sendInquiry(e){return fn.bind(this)(e)}blockAccount(e){return Pn.bind(this)(e)}unblockAccount(e){return Sn.bind(this)(e)}deleteAccount(e){return kn.bind(this)(e)}inviteUser(e,n){return vn.bind(this)(e,n)}createAccount(e){return xn.bind(this)(e)}grantAccess(e){return Dn.bind(this)(e)}updateUserAttributes(e){return Ln.bind(this)(e)}getRealtimeGroups(e,n){return on.bind(this)(e,n)}postRealtime(e,n,r){return rn.bind(this)(e,n,r)}joinRealtime(e){return He.bind(this)(e)}getProfile(e){return ct.bind(this)(e)}getFile(e,n){return Pe.bind(this)(e,n)}secureRequest(e,n){return hn.bind(this)(e,n)}getFormResponse(){return xt.bind(this)()}getRecords(e,n){return Ot.bind(this)(e,n)}getTables(e,n){return Vt.bind(this)(e,n)}getIndexes(e,n){return $t.bind(this)(e,n)}getTags(e,n){return jt.bind(this)(e,n)}deleteRecords(e,n){return Qt.bind(this)(e,n)}resendSignupConfirmation(){return dt.bind(this)()}recoverAccount(e=false){return gt.bind(this)(e)}getUsers(e,n){return Rt.bind(this)(e,n)}disableAccount(){return ht.bind(this)()}lastVerifiedEmail(e){return At.bind(this)(e)}unsubscribeNewsletter(e){return In.bind(this)(e)}subscribeNotification(e,n){return On.bind(this)({endpoint:e,keys:n})}unsubscribeNotification(e,n){return Mn.bind(this)({endpoint:e,keys:n})}vapidPublicKey(){return Fn.bind(this)()}pushNotification(e,n){return qn.bind(this)(e,n)}getNewsletters(e,n){return Tn.bind(this)(e,n)}getNewsletterSubscription(e,n){return Rn.bind(this)(e,n)}requestUsernameChange(e){return It.bind(this)(e)}grantPrivateRecordAccess(e){return Kt.bind(this)(e)}removePrivateRecordAccess(e){return Ht.bind(this)(e)}listPrivateRecordAccess(e,n){return Wt.bind(this)(e,n)}requestPrivateRecordAccessKey(e){return zt.bind(this)(e)}deleteFiles(e){return Ct.bind(this)(e)}uploadFiles(e,n){return Re.bind(this)(e,n)}mock(e,n){return pn.bind(this)(e,n)}login(e){return Oe.bind(this)(e)}logout(e){return ue.bind(this)(e)}signup(e,n){return ft.bind(this)(e,n)}resetPassword(e){return pt.bind(this)(e)}verifyEmail(e,n){return bt.bind(this)(e,n)}verifyPhoneNumber(e,n){return _t.bind(this)(e,n)}forgotPassword(e,n){return yt.bind(this)(e,n)}changePassword(e){return wt.bind(this)(e)}updateProfile(e){return Et.bind(this)(e)}postRecord(e,n,r){return qt.bind(this)(e,n,r)}getSubscriptions(e,n){return _n.bind(this)(e,n)}subscribe(e){return bn.bind(this)(e)}unsubscribe(e){return yn.bind(this)(e)}blockSubscriber(e){return wn.bind(this)(e)}unblockSubscriber(e){return En.bind(this)(e)}subscribeNewsletter(e){return An.bind(this)(e)}bulkPostRecords(e){return Ft.bind(this)(e)}};R([A()],y.prototype,"getFeed"),R([A()],y.prototype,"closeRTC"),R([A()],y.prototype,"connectRTC"),R([A()],y.prototype,"spellcast"),R([A()],y.prototype,"getspell"),R([A()],y.prototype,"dopamine"),R([A()],y.prototype,"getUniqueId"),R([A()],y.prototype,"resendInvitation"),R([A()],y.prototype,"cancelInvitation"),R([A()],y.prototype,"getInvitations"),R([A()],y.prototype,"openIdLogin"),R([A()],y.prototype,"loginWithToken"),R([A()],y.prototype,"clientSecretRequest"),R([A()],y.prototype,"clientSecretRequestHistory"),R([A()],y.prototype,"cancelClientSecretRequest"),R([A()],y.prototype,"consumeTicket"),R([A()],y.prototype,"getConsumedTickets"),R([A()],y.prototype,"getTickets"),R([A()],y.prototype,"getRealtimeUsers"),R([A()],y.prototype,"sendInquiry"),R([A()],y.prototype,"blockAccount"),R([A()],y.prototype,"unblockAccount"),R([A()],y.prototype,"deleteAccount"),R([A()],y.prototype,"inviteUser"),R([A()],y.prototype,"createAccount"),R([A()],y.prototype,"grantAccess"),R([A()],y.prototype,"updateUserAttributes"),R([A()],y.prototype,"getRealtimeGroups"),R([A()],y.prototype,"postRealtime"),R([A()],y.prototype,"joinRealtime"),R([A()],y.prototype,"getProfile"),R([A()],y.prototype,"getFile"),R([A()],y.prototype,"secureRequest"),R([A()],y.prototype,"getFormResponse"),R([A()],y.prototype,"getRecords"),R([A()],y.prototype,"getTables"),R([A()],y.prototype,"getIndexes"),R([A()],y.prototype,"getTags"),R([A()],y.prototype,"deleteRecords"),R([A()],y.prototype,"resendSignupConfirmation"),R([A()],y.prototype,"recoverAccount"),R([A()],y.prototype,"getUsers"),R([A()],y.prototype,"disableAccount"),R([A()],y.prototype,"lastVerifiedEmail"),R([A()],y.prototype,"unsubscribeNewsletter"),R([A()],y.prototype,"subscribeNotification"),R([A()],y.prototype,"unsubscribeNotification"),R([A()],y.prototype,"vapidPublicKey"),R([A()],y.prototype,"pushNotification"),R([A()],y.prototype,"getNewsletters"),R([A()],y.prototype,"getNewsletterSubscription"),R([A()],y.prototype,"requestUsernameChange"),R([A()],y.prototype,"grantPrivateRecordAccess"),R([A()],y.prototype,"removePrivateRecordAccess"),R([A()],y.prototype,"listPrivateRecordAccess"),R([A()],y.prototype,"requestPrivateRecordAccessKey"),R([A()],y.prototype,"deleteFiles"),R([A()],y.prototype,"uploadFiles"),R([A()],y.prototype,"mock"),R([A({preventMultipleCalls:true})],y.prototype,"login"),R([A()],y.prototype,"logout"),R([A({preventMultipleCalls:true})],y.prototype,"signup"),R([A({preventMultipleCalls:true})],y.prototype,"resetPassword"),R([A({preventMultipleCalls:true})],y.prototype,"verifyEmail"),R([A({preventMultipleCalls:true})],y.prototype,"verifyPhoneNumber"),R([A({preventMultipleCalls:true})],y.prototype,"forgotPassword"),R([A({preventMultipleCalls:true})],y.prototype,"changePassword"),R([A({preventMultipleCalls:true})],y.prototype,"updateProfile"),R([A()],y.prototype,"postRecord"),R([A()],y.prototype,"getSubscriptions"),R([A()],y.prototype,"subscribe"),R([A()],y.prototype,"unsubscribe"),R([A()],y.prototype,"blockSubscriber"),R([A()],y.prototype,"unblockSubscriber"),R([A()],y.prototype,"subscribeNewsletter");var Hr={};
233
- export{y as Skapi,c as SkapiError,Hr as Types};//# sourceMappingURL=skapi.mjs.map
232
+ Full Documentation: https://docs.skapi.com/skapi.md`;console.log(n,"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,n){if(this.__network_logs){if(n!==null&&typeof n=="object")try{V()?n=JSON.parse(JSON.stringify(n)):n=JSON.stringify(n,null,2);}catch{n=String(n);}else typeof n=="string"&&n.length>100&&(n=n.substring(0,100)+"...");console.log(`%c${e}:`,"color: blue;",n);}}getFeed(e,n){return wn.bind(this)(e,n)}closeRTC(e){return K.bind(this)(e)}connectRTC(e,n){return en.bind(this)(e,n)}connectRealtime(e){return Ue.bind(this)(e)}spellcast(e){return Qn.bind(this)(e)}getspell(e){return Kn.bind(this)(e)}dopamine(e){return Hn.bind(this)(e)}getUniqueId(e,n){return Kt.bind(this)(e,n)}resendInvitation(e){return Fn.bind(this)(e)}cancelInvitation(e){return Mn.bind(this)(e)}getInvitations(e,n){return On.bind(this)(e,n)}openIdLogin(e){return dt.bind(this)(e)}loginWithToken(e){return gt.bind(this)(e)}clientSecretRequest(e){return hn.bind(this)(e)}clientSecretRequestHistory(e,n){return pn.bind(this)(e,n)}cancelClientSecretRequest(e){return mn.bind(this)(e)}stopClientSecretPolling(e){return gn.bind(this)(e||{})}isPollStopped(e){return un(e)}clientSecretRequestQueueCount(e){return fn.bind(this)(e)}consumeTicket(e){return st.bind(this)(e)}getConsumedTickets(e,n){return at.bind(this)(e,n)}getTickets(e,n){return ot.bind(this)(e,n)}closeRealtime(){return sn.bind(this)()}getRealtimeUsers(e,n){return an.bind(this)(e,n)}sendInquiry(e){return _n.bind(this)(e)}blockAccount(e){return xn.bind(this)(e)}unblockAccount(e){return Dn.bind(this)(e)}deleteAccount(e){return Un.bind(this)(e)}inviteUser(e,n){return Nn.bind(this)(e,n)}createAccount(e){return Cn.bind(this)(e)}grantAccess(e){return Ln.bind(this)(e)}updateUserAttributes(e){return qn.bind(this)(e)}getRealtimeGroups(e,n){return cn.bind(this)(e,n)}postRealtime(e,n,r){return on.bind(this)(e,n,r)}joinRealtime(e){return ze.bind(this)(e)}getProfile(e){return ut.bind(this)(e)}getFile(e,n){return ke.bind(this)(e,n)}secureRequest(e,n){return bn.bind(this)(e,n)}getFormResponse(){return Ut.bind(this)()}getRecords(e,n){return Ft.bind(this)(e,n)}getTables(e,n){return jt.bind(this)(e,n)}getIndexes(e,n){return Bt.bind(this)(e,n)}getTags(e,n){return Qt.bind(this)(e,n)}deleteRecords(e,n){return Ht.bind(this)(e,n)}resendSignupConfirmation(){return ft.bind(this)()}recoverAccount(e=false){return ht.bind(this)(e)}getUsers(e,n){return It.bind(this)(e,n)}disableAccount(){return mt.bind(this)()}lastVerifiedEmail(e){return Tt.bind(this)(e)}unsubscribeNewsletter(e){return kn.bind(this)(e)}subscribeNotification(e,n){return Vn.bind(this)({endpoint:e,keys:n})}unsubscribeNotification(e,n){return $n.bind(this)({endpoint:e,keys:n})}vapidPublicKey(){return jn.bind(this)()}pushNotification(e,n){return Bn.bind(this)(e,n)}getNewsletters(e,n){return vn.bind(this)(e,n)}getNewsletterSubscription(e,n){return Pn.bind(this)(e,n)}requestUsernameChange(e){return Pt.bind(this)(e)}grantPrivateRecordAccess(e){return Wt.bind(this)(e)}removePrivateRecordAccess(e){return zt.bind(this)(e)}listPrivateRecordAccess(e,n){return Jt.bind(this)(e,n)}requestPrivateRecordAccessKey(e){return Gt.bind(this)(e)}deleteFiles(e){return Ot.bind(this)(e)}uploadFiles(e,n){return Ie.bind(this)(e,n)}mock(e,n){return yn.bind(this)(e,n)}login(e){return Fe.bind(this)(e)}logout(e){return de.bind(this)(e)}signup(e,n){return pt.bind(this)(e,n)}resetPassword(e){return _t.bind(this)(e)}verifyEmail(e,n){return wt.bind(this)(e,n)}verifyPhoneNumber(e,n){return yt.bind(this)(e,n)}forgotPassword(e,n){return Et.bind(this)(e,n)}changePassword(e){return Rt.bind(this)(e)}updateProfile(e){return At.bind(this)(e)}postRecord(e,n,r){return $t.bind(this)(e,n,r)}getSubscriptions(e,n){return En.bind(this)(e,n)}subscribe(e){return Rn.bind(this)(e)}unsubscribe(e){return An.bind(this)(e)}blockSubscriber(e){return In.bind(this)(e)}unblockSubscriber(e){return Tn.bind(this)(e)}subscribeNewsletter(e){return Sn.bind(this)(e)}bulkPostRecords(e){return Vt.bind(this)(e)}};R([A()],y.prototype,"getFeed"),R([A()],y.prototype,"closeRTC"),R([A()],y.prototype,"connectRTC"),R([A()],y.prototype,"spellcast"),R([A()],y.prototype,"getspell"),R([A()],y.prototype,"dopamine"),R([A()],y.prototype,"getUniqueId"),R([A()],y.prototype,"resendInvitation"),R([A()],y.prototype,"cancelInvitation"),R([A()],y.prototype,"getInvitations"),R([A()],y.prototype,"openIdLogin"),R([A()],y.prototype,"loginWithToken"),R([A()],y.prototype,"clientSecretRequest"),R([A()],y.prototype,"clientSecretRequestHistory"),R([A()],y.prototype,"cancelClientSecretRequest"),R([A()],y.prototype,"consumeTicket"),R([A()],y.prototype,"getConsumedTickets"),R([A()],y.prototype,"getTickets"),R([A()],y.prototype,"getRealtimeUsers"),R([A()],y.prototype,"sendInquiry"),R([A()],y.prototype,"blockAccount"),R([A()],y.prototype,"unblockAccount"),R([A()],y.prototype,"deleteAccount"),R([A()],y.prototype,"inviteUser"),R([A()],y.prototype,"createAccount"),R([A()],y.prototype,"grantAccess"),R([A()],y.prototype,"updateUserAttributes"),R([A()],y.prototype,"getRealtimeGroups"),R([A()],y.prototype,"postRealtime"),R([A()],y.prototype,"joinRealtime"),R([A()],y.prototype,"getProfile"),R([A()],y.prototype,"getFile"),R([A()],y.prototype,"secureRequest"),R([A()],y.prototype,"getFormResponse"),R([A()],y.prototype,"getRecords"),R([A()],y.prototype,"getTables"),R([A()],y.prototype,"getIndexes"),R([A()],y.prototype,"getTags"),R([A()],y.prototype,"deleteRecords"),R([A()],y.prototype,"resendSignupConfirmation"),R([A()],y.prototype,"recoverAccount"),R([A()],y.prototype,"getUsers"),R([A()],y.prototype,"disableAccount"),R([A()],y.prototype,"lastVerifiedEmail"),R([A()],y.prototype,"unsubscribeNewsletter"),R([A()],y.prototype,"subscribeNotification"),R([A()],y.prototype,"unsubscribeNotification"),R([A()],y.prototype,"vapidPublicKey"),R([A()],y.prototype,"pushNotification"),R([A()],y.prototype,"getNewsletters"),R([A()],y.prototype,"getNewsletterSubscription"),R([A()],y.prototype,"requestUsernameChange"),R([A()],y.prototype,"grantPrivateRecordAccess"),R([A()],y.prototype,"removePrivateRecordAccess"),R([A()],y.prototype,"listPrivateRecordAccess"),R([A()],y.prototype,"requestPrivateRecordAccessKey"),R([A()],y.prototype,"deleteFiles"),R([A()],y.prototype,"uploadFiles"),R([A()],y.prototype,"mock"),R([A({preventMultipleCalls:true})],y.prototype,"login"),R([A()],y.prototype,"logout"),R([A({preventMultipleCalls:true})],y.prototype,"signup"),R([A({preventMultipleCalls:true})],y.prototype,"resetPassword"),R([A({preventMultipleCalls:true})],y.prototype,"verifyEmail"),R([A({preventMultipleCalls:true})],y.prototype,"verifyPhoneNumber"),R([A({preventMultipleCalls:true})],y.prototype,"forgotPassword"),R([A({preventMultipleCalls:true})],y.prototype,"changePassword"),R([A({preventMultipleCalls:true})],y.prototype,"updateProfile"),R([A()],y.prototype,"postRecord"),R([A()],y.prototype,"getSubscriptions"),R([A()],y.prototype,"subscribe"),R([A()],y.prototype,"unsubscribe"),R([A()],y.prototype,"blockSubscriber"),R([A()],y.prototype,"unblockSubscriber"),R([A()],y.prototype,"subscribeNewsletter");var Gr={};
233
+ export{y as Skapi,c as SkapiError,Gr as Types};//# sourceMappingURL=skapi.mjs.map
234
234
  //# sourceMappingURL=skapi.mjs.map