skapi-js 1.5.0-beta.11 → 1.5.0-beta.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/skapi.cjs CHANGED
@@ -1,4 +1,4 @@
1
- 'use strict';var amazonCognitoIdentityJs=require('amazon-cognito-identity-js'),rr=require('cocochex'),_r=require('qpass');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var rr__default=/*#__PURE__*/_interopDefault(rr);var _r__default=/*#__PURE__*/_interopDefault(_r);/**
1
+ 'use strict';var amazonCognitoIdentityJs=require('amazon-cognito-identity-js'),Zn=require('cocochex'),fr=require('qpass');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var Zn__default=/*#__PURE__*/_interopDefault(Zn);var fr__default=/*#__PURE__*/_interopDefault(fr);/**
2
2
  * @license
3
3
  Apache License
4
4
  Version 2.0, January 2004
@@ -203,7 +203,7 @@
203
203
  limitations under the License.
204
204
 
205
205
  */
206
- var $n=Object.defineProperty;var qn=Object.getOwnPropertyDescriptor;var Y=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var _=(n,e,t,i)=>{for(var r=qn(e,t),s=n.length-1,o;s>=0;s--)(o=n[s])&&(r=(o(e,t,r))||r);return r&&$n(e,t,r),r};var J=typeof globalThis<"u"?globalThis:void 0,he=J?.window;function jn(n){if(Buffer)return Buffer.from(n).toString("base64");let e="",t=new Uint8Array(n),i=32768;for(let r=0;r<t.length;r+=i){let s=t.subarray(r,r+i);e+=String.fromCharCode.apply(null,Array.from(s));}if(typeof btoa=="function")return btoa(e);throw new Error("No base64 encoder available in this environment.")}if(he)he.global=he,he.global._runningInNodeJS=false;else if(J&&(J.global=J,typeof J.window>"u")){class n{constructor(){this.result=null;this.error=null;this.onload=null;this.onloadend=null;this.onerror=null;}readAsDataURL(i){i.arrayBuffer().then(r=>{let s=jn(r),o=i.type||"application/octet-stream";this.result=`data:${o};base64,${s}`,this.onload&&this.onload({target:this}),this.onloadend&&this.onloadend({target:this});}).catch(r=>{this.error=r,this.onerror&&this.onerror({target:this});});}readAsArrayBuffer(i){i.arrayBuffer().then(r=>{this.result=r,this.onload&&this.onload({target:this}),this.onloadend&&this.onloadend({target:this});}).catch(r=>{this.error=r,this.onerror&&this.onerror({target:this});});}readAsText(i,r="utf-8"){i.text().then(s=>{this.result=s,this.onload&&this.onload({target:this}),this.onloadend&&this.onloadend({target:this});}).catch(s=>{this.error=s,this.onerror&&this.onerror({target:this});});}}J.FileReader=n;class e{constructor(){this.status=0;this.statusText="";this.readyState=0;this.responseText="";this.response=null;this.responseType="";this.responseURL="";this.timeout=0;this.withCredentials=false;this.onload=null;this.onerror=null;this.onabort=null;this.ontimeout=null;this.onprogress=null;this.onreadystatechange=null;this.upload={onprogress:null};this._method="GET";this._url="";this._headers={};this._aborted=false;}open(i,r){this._method=i,this._url=r,this.readyState=1;}setRequestHeader(i,r){this._headers[i]=r;}getResponseHeader(i){return null}abort(){this._aborted=true,this.onabort&&this.onabort({});}send(i){if(this._aborted)return;let r={method:this._method,headers:this._headers};i&&this._method!=="GET"&&this._method!=="HEAD"&&(r.body=i),fetch(this._url,r).then(async s=>{if(!this._aborted){if(this.status=s.status,this.statusText=s.statusText,this.responseURL=s.url,this.readyState=4,this.responseType==="blob")this.response=await s.blob();else if(this.responseType==="json")try{this.response=await s.json();}catch{this.response=null;}else this.responseType==="arraybuffer"?this.response=await s.arrayBuffer():(this.responseText=await s.text(),this.response=this.responseText);this.onload&&this.onload({});}}).catch(s=>{this._aborted||this.onerror&&this.onerror(s);});}}J.XMLHttpRequest=e,J.window={_runningInNodeJS:true,alert:t=>console.error("[Alert]",t),sessionStorage:{getItem:t=>null,setItem:(t,i)=>{},removeItem:t=>{}},localStorage:{getItem:t=>{let i=Y("fs"),r=Y("path");try{let s=r.resolve(process.cwd(),"states","localStorage",`${t}.skapi`);return i.existsSync(s)?i.readFileSync(s,"utf8"):null}catch{return null}},setItem:(t,i)=>{let r=Y("fs"),s=Y("path");try{let o=s.resolve(process.cwd(),"states","localStorage");r.existsSync(o)||r.mkdirSync(o,{recursive:!0});let c=s.resolve(o,`${t}.skapi`);r.writeFileSync(c,i,"utf8");}catch{}},removeItem:t=>{let i=Y("fs"),r=Y("path");try{let s=r.resolve(process.cwd(),"states","localStorage",`${t}.skapi`);i.existsSync(s)&&i.unlinkSync(s);}catch{}}},location:{href:"",origin:"",hostname:"",protocol:"",replace:t=>{}},navigator:{userAgent:`nodejs/${J?.process?.versions?.node||"unknown"}`,mediaDevices:{getUserMedia:async t=>{throw new Error("getUserMedia is not supported in Node.js environment.")}}},addEventListener:()=>{},removeEventListener:()=>{}};}var a=class extends Error{constructor(e,t){if(Array.isArray(e)&&e.length<=2){let i=e[1];if(e.length>2)for(let r=2;r<e.length&&typeof e[r]=="string";r++)i+=e[r];super((i||"Something went wrong.").trim()),this.name=t?.name||"SKAPI",this.code=t?.code||e[0]||"ERROR",t?.cause&&(this.cause=t.cause);}else super((e?.message||(typeof e=="string"?e:"Something went wrong.")).trim()),typeof e=="string"?(this.name=t?.name||"SKAPI",this.code=t?.code||"ERROR",t?.cause&&(this.cause=t.cause)):e instanceof Error?(this.cause=e,this.name=e.name,e.hasOwnProperty("code")&&(this.code=e.code)):typeof e=="object"&&e?.code&&e?.message&&(this.name=t?.name||"SKAPI",this.code=t?.code||"ERROR",this.cause=e?.cause);}};var ee="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",xe=BigInt(ee.length),Bn=2*1024*1024,Kn=["aud","cognito:username","event_id","exp","iat","iss","jti","origin_jti","secret_key","token_use"],Qe={auth_time:"log",sub:"user_id"},Qn=["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"],We=typeof TextEncoder<"u"?new TextEncoder:null,He=typeof TextDecoder<"u"?new TextDecoder:null;function ve(){if(typeof globalThis<"u")return globalThis.Buffer}function Wn(n){if(We)return We.encode(n);let e=unescape(encodeURIComponent(n)),t=new Uint8Array(e.length);for(let i=0;i<e.length;i++)t[i]=e.charCodeAt(i);return t}function Hn(n){if(He)return He.decode(n);let e="";for(let t=0;t<n.length;t++)e+=String.fromCharCode(n[t]);return decodeURIComponent(escape(e))}function nt(n){if(n instanceof Uint8Array)return n;if(typeof n=="string")return Wn(n);if(typeof ArrayBuffer<"u"&&n instanceof ArrayBuffer)return new Uint8Array(n);if(typeof ArrayBuffer<"u"&&ArrayBuffer.isView(n))return new Uint8Array(n.buffer,n.byteOffset,n.byteLength);if(Array.isArray(n))return Uint8Array.from(n);let e=ve();if(e)return new Uint8Array(e.from(n));throw new Error("No byte conversion available in this environment.")}function Jn(n){let e=0;for(let r of n)e+=r.length;let t=new Uint8Array(e),i=0;for(let r of n)t.set(r,i),i+=r.length;return t}var m=class m{static hash(e){typeof e!="string"&&(console.warn("coercing non-string value to empty string"),e="");let t=m.sb(e),i=1732584193,r=-271733879,s=-1732584194,o=271733878,c,u,d,f;for(let l=0;l<t.length;l+=16)c=i,u=r,d=s,f=o,i=m.ff(i,r,s,o,t[l],7,-680876936),o=m.ff(o,i,r,s,t[l+1],12,-389564586),s=m.ff(s,o,i,r,t[l+2],17,606105819),r=m.ff(r,s,o,i,t[l+3],22,-1044525330),i=m.ff(i,r,s,o,t[l+4],7,-176418897),o=m.ff(o,i,r,s,t[l+5],12,1200080426),s=m.ff(s,o,i,r,t[l+6],17,-1473231341),r=m.ff(r,s,o,i,t[l+7],22,-45705983),i=m.ff(i,r,s,o,t[l+8],7,1770035416),o=m.ff(o,i,r,s,t[l+9],12,-1958414417),s=m.ff(s,o,i,r,t[l+10],17,-42063),r=m.ff(r,s,o,i,t[l+11],22,-1990404162),i=m.ff(i,r,s,o,t[l+12],7,1804603682),o=m.ff(o,i,r,s,t[l+13],12,-40341101),s=m.ff(s,o,i,r,t[l+14],17,-1502002290),r=m.ff(r,s,o,i,t[l+15],22,1236535329),i=m.gg(i,r,s,o,t[l+1],5,-165796510),o=m.gg(o,i,r,s,t[l+6],9,-1069501632),s=m.gg(s,o,i,r,t[l+11],14,643717713),r=m.gg(r,s,o,i,t[l],20,-373897302),i=m.gg(i,r,s,o,t[l+5],5,-701558691),o=m.gg(o,i,r,s,t[l+10],9,38016083),s=m.gg(s,o,i,r,t[l+15],14,-660478335),r=m.gg(r,s,o,i,t[l+4],20,-405537848),i=m.gg(i,r,s,o,t[l+9],5,568446438),o=m.gg(o,i,r,s,t[l+14],9,-1019803690),s=m.gg(s,o,i,r,t[l+3],14,-187363961),r=m.gg(r,s,o,i,t[l+8],20,1163531501),i=m.gg(i,r,s,o,t[l+13],5,-1444681467),o=m.gg(o,i,r,s,t[l+2],9,-51403784),s=m.gg(s,o,i,r,t[l+7],14,1735328473),r=m.gg(r,s,o,i,t[l+12],20,-1926607734),i=m.hh(i,r,s,o,t[l+5],4,-378558),o=m.hh(o,i,r,s,t[l+8],11,-2022574463),s=m.hh(s,o,i,r,t[l+11],16,1839030562),r=m.hh(r,s,o,i,t[l+14],23,-35309556),i=m.hh(i,r,s,o,t[l+1],4,-1530992060),o=m.hh(o,i,r,s,t[l+4],11,1272893353),s=m.hh(s,o,i,r,t[l+7],16,-155497632),r=m.hh(r,s,o,i,t[l+10],23,-1094730640),i=m.hh(i,r,s,o,t[l+13],4,681279174),o=m.hh(o,i,r,s,t[l],11,-358537222),s=m.hh(s,o,i,r,t[l+3],16,-722521979),r=m.hh(r,s,o,i,t[l+6],23,76029189),i=m.hh(i,r,s,o,t[l+9],4,-640364487),o=m.hh(o,i,r,s,t[l+12],11,-421815835),s=m.hh(s,o,i,r,t[l+15],16,530742520),r=m.hh(r,s,o,i,t[l+2],23,-995338651),i=m.ii(i,r,s,o,t[l],6,-198630844),o=m.ii(o,i,r,s,t[l+7],10,1126891415),s=m.ii(s,o,i,r,t[l+14],15,-1416354905),r=m.ii(r,s,o,i,t[l+5],21,-57434055),i=m.ii(i,r,s,o,t[l+12],6,1700485571),o=m.ii(o,i,r,s,t[l+3],10,-1894986606),s=m.ii(s,o,i,r,t[l+10],15,-1051523),r=m.ii(r,s,o,i,t[l+1],21,-2054922799),i=m.ii(i,r,s,o,t[l+8],6,1873313359),o=m.ii(o,i,r,s,t[l+15],10,-30611744),s=m.ii(s,o,i,r,t[l+6],15,-1560198380),r=m.ii(r,s,o,i,t[l+13],21,1309151649),i=m.ii(i,r,s,o,t[l+4],6,-145523070),o=m.ii(o,i,r,s,t[l+11],10,-1120210379),s=m.ii(s,o,i,r,t[l+2],15,718787259),r=m.ii(r,s,o,i,t[l+9],21,-343485551),i=m.ad(i,c),r=m.ad(r,u),s=m.ad(s,d),o=m.ad(o,f);return m.rh(i)+m.rh(r)+m.rh(s)+m.rh(o)}static rh(e){let t="";for(let i=0;i<=3;i++)t+=m.alphabet.charAt(e>>i*8+4&15)+m.alphabet.charAt(e>>i*8&15);return t}static ad(e,t){let i=(e&65535)+(t&65535);return (e>>16)+(t>>16)+(i>>16)<<16|i&65535}static rl(e,t){return e<<t|e>>>32-t}static cm(e,t,i,r,s,o){return m.ad(m.rl(m.ad(m.ad(t,e),m.ad(r,o)),s),i)}static ff(e,t,i,r,s,o,c){return m.cm(t&i|~t&r,e,t,s,o,c)}static gg(e,t,i,r,s,o,c){return m.cm(t&r|i&~r,e,t,s,o,c)}static hh(e,t,i,r,s,o,c){return m.cm(t^i^r,e,t,s,o,c)}static ii(e,t,i,r,s,o,c){return m.cm(i^(t|~r),e,t,s,o,c)}static sb(e){let t,i=(e.length+8>>6)+1,r=new Array(i*16);for(t=0;t<i*16;t++)r[t]=0;for(t=0;t<e.length;t++)r[t>>2]|=e.charCodeAt(t)<<t%4*8;return r[t>>2]|=128<<t%4*8,r[i*16-2]=e.length*8,r}};m.alphabet="0123456789abcdef";var V=m;function rt(n){if(n===0)return ee[0];let e="";for(;n>0;)e=ee[n%62]+e,n=Math.floor(n/62);return e}function B(n){return n.split("").reverse().reduce((e,t,i)=>e+ee.indexOf(t)*62**i,0)}function oe(n=6){let e="",t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",i=t.length,r=0;for(;r<n;)e+=t.charAt(Math.floor(Math.random()*i)),r+=1;return e}function De(){return typeof window>"u"||!!window?._runningInNodeJS}function $(){return !De()&&typeof document<"u"&&typeof document.createElement=="function"}function pe(n){let e;try{e=JSON.stringify(n);}catch{throw new a("Invalid data type.",{code:"INVALID_REQUEST"})}if(new Blob([e]).size>Bn)throw new a("Data should not exceed 2MB",{code:"INVALID_REQUEST"})}function Je(n){return n===""||n==="on"||n==="true"}function ze(n){return n==="false"}function Ge(n,e,t){e.name&&t(n,e.name,e.value);}var me=$(),zn=typeof SubmitEvent<"u",Gn=typeof HTMLFormElement<"u";function D(n,e,t){let i={},r=[];function s(u,d,f){if(e?.ignoreEmpty&&f==="")return;if(e?.nullIfEmpty&&f===""&&(f=null),typeof t=="function"){let R=t(d,f);R!==void 0&&(f=R);}let l=d.split("[").map(R=>{let p=R.replace("]",""),A=Number(p);return !isNaN(A)&&!p.includes(".")?p=A:(p[0]==='"'&&p[p.length-1]==='"'||p[0]==="'"&&p[p.length-1]==="'")&&(p=p.replace(/"/g,"").replace(/'/g,"")),p}),h=u;if(typeof l[0]=="number")throw new a("Form key cannot start with an array index.",{code:"INVALID_REQUEST"});for(let R=0;R<l.length;R++){let p=l[R];R<l.length-1?(h[p]===void 0&&(typeof l[R+1]=="number"?h[p]=[]:h[p]={}),h=h[p]):h[p]===void 0?h[p]=f:Array.isArray(h[p])?h[p].push(f):h[p]=[h[p],f];}}function o(u,d,f){if(f instanceof File)u.push({name:d,file:f});else if(f instanceof FileList&&f&&f.length>0)for(let l=0;l<=f.length-1;l++){let h=f.item(l);h&&u.push({name:d,file:h});}}let c=u=>{u.name&&(u.type==="number"?u.value&&s(i,u.name,Number(u.value)):u.type==="checkbox"||u.type==="radio"?u.checked?u.type==="checkbox"&&u.value===""||Je(u.value)?s(i,u.name,true):ze(u.value)?s(i,u.name,false):u.value&&s(i,u.name,u.value):u.type==="checkbox"&&(Je(u.value)?s(i,u.name,false):ze(u.value)&&s(i,u.name,true)):u.type==="file"?u.files&&u.files.length>0&&o(r,u.name,u.files):s(i,u.name,u.value));};if(me&&(n instanceof HTMLInputElement||n instanceof HTMLSelectElement||n instanceof HTMLTextAreaElement))return c(n),pe(i),{data:i,files:r};if(me&&n instanceof FormData){for(let u of n.entries()){let d=u[0],f=u[1];if(f instanceof File||f instanceof FileList)o(r,d,f);else if(f instanceof Blob){let l=f;if(l.type==="application/json")try{let h=JSON.parse(l.text());s(i,d,h);}catch{s(i,d,l);}}else s(i,d,f);}return pe(i),{data:i,files:r}}if(me&&zn&&n instanceof SubmitEvent&&(n=n.target),me&&Gn&&n instanceof HTMLFormElement){let u=n.querySelectorAll("input"),d=n.querySelectorAll("select"),f=n.querySelectorAll("textarea");for(let l=0;l<d.length;l++)Ge(i,d[l],s);for(let l=0;l<f.length;l++)Ge(i,f[l],s);for(let l=0;l<u.length;l++)c(u[l]);return pe(i),{data:i,files:r}}return pe(n),{data:n,files:r}}function ae(n){let e={};for(let t in n){let i=n[t];if(!Kn.includes(t))if(Qe[t])e[Qe[t]]=i;else if(t.includes("custom:"))e[t.replace("custom:","")]=i;else if(t==="address"){let r=i;if(r&&typeof r=="object"&&Object.keys(r).length){if(r?.formatted)try{e[t]=JSON.parse(r.formatted);}catch{e[t]=r.formatted;}}else e[t]=r;}else e[t]=i;}for(let t of ["address_public","birthdate_public","email_public","gender_public","phone_number_public","access_group"])t.includes("_public")?e.hasOwnProperty(t.split("_")[0])?e[t]=e.hasOwnProperty(t)?!!Number(e[t]):false:delete e[t]:e[t]=e.hasOwnProperty(t)?Number(e[t]):0;for(let t of ["email","phone_number"])e.hasOwnProperty(t)?e[t+"_verified"]=e[t+"_verified"]===true:delete e[t+"_verified"];return e}function Ue(n){if(n=nr(n),n.split("-").length===7){let e=n.split("-"),t,i;try{t=tt[B(e[1][0])],i=e.slice(2).join("-");}catch{throw new Error("INVALID_PARAMETER: Service ID is invalid.")}if(!t)throw new Error("INVALID_PARAMETER: Service ID is invalid.");return {service:t+e[0]+e[1].slice(1),owner:i}}return {service:n,owner:""}}function it(n,e){let t=tt.indexOf(n.slice(0,4)),i=Qn[t],s=`${n.slice(4,-4)}-${i}${n.slice(-4)}-${e}`;return tr(s)}function Xe(n){let e=0n;for(let t of n){let i=ee.indexOf(t);if(i<0)throw new Error(`INVALID_PARAMETER: Invalid base62 character: ${t}`);e=e*xe+BigInt(i);}return e}function Ze(n,e=1){if(n<0n)throw new Error("INVALID_PARAMETER: Negative values are not supported.");if(n===0n)return "0".repeat(Math.max(1,e));let t="",i=n;for(;i>0n;){let r=Number(i%xe);t=ee[r]+t,i/=xe;}return t.length<e&&(t="0".repeat(e-t.length)+t),t}function Ye(n){if(n===0n)return Uint8Array.from([0]);let e=[],t=n;for(;t>0n;)e.push(Number(t&0xffn)),t>>=8n;return e.reverse(),Uint8Array.from(e)}function et(n){let e=0n;for(let t of n)e=(e<<8n)+BigInt(t);return e}function Xn(n){let e=String(n).replace(/-/g,"");if(!/^[0-9a-fA-F]{32}$/.test(e))throw new Error("INVALID_PARAMETER: Invalid UUID format.");let t=new Uint8Array(16);for(let i=0;i<16;i++)t[i]=parseInt(e.slice(i*2,i*2+2),16);return t}function Zn(n){let e=Array.from(nt(n),t=>t.toString(16).padStart(2,"0")).join("");return [e.slice(0,8),e.slice(8,12),e.slice(12,16),e.slice(16,20),e.slice(20)].join("-")}function Yn(n){let e=nt(n),t=ve();if(t)return t.from(e).toString("base64");let i="",r=32768;for(let s=0;s<e.length;s+=r){let o=e.subarray(s,s+r);i+=String.fromCharCode.apply(null,Array.from(o));}if(typeof btoa=="function")return btoa(i);throw new Error("No base64 encoder available in this environment.")}function er(n,e=false){let t=String(n).replace(/-/g,"+").replace(/_/g,"/"),i=t.length%4?"=".repeat(4-t.length%4):"",r=ve(),s;if(r)s=new Uint8Array(r.from(t+i,"base64"));else if(typeof atob=="function"){let o=atob(t+i);s=new Uint8Array(o.length);for(let c=0;c<o.length;c++)s[c]=o.charCodeAt(c);}else throw new Error("No base64 decoder available in this environment.");return e?JSON.parse(Hn(s)):s}function tr(n){let e=String(n).match(/^([0-9A-Za-z]+)-([0-9A-Za-z]+)-([0-9a-fA-F-]{36})$/);if(!e)throw new Error("INVALID_PARAMETER: Input must match <base62>-<base62>-<uuid>.");let[,t,i,r]=e,s=Xe(t),o=Xe(i),c=Ye(s),u=Ye(o),d=Xn(r);if(t.length>255||i.length>255||c.length>255||u.length>255)throw new Error("INVALID_PARAMETER: Input parts are too long to encode.");let f=Jn([Uint8Array.from([1,t.length,i.length,c.length,u.length]),c,u,d]);return `s1_${Yn(f).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}`}function nr(n){let e=String(n);if(!e.startsWith("s1_"))return e;let t=er(e.slice(3));if(t.length<21)throw new Error("INVALID_PARAMETER: Corrupt compressed token.");let i=t[0];if(i!==1)throw new Error(`INVALID_PARAMETER: Unsupported token version: ${i}`);let r=t[1],s=t[2],o=t[3],c=t[4],u=5,d=u+o,f=d+c;if(t.length!==f+16)throw new Error("INVALID_PARAMETER: Corrupt compressed token length.");let l=Ze(et(t.subarray(u,d)),r),h=Ze(et(t.subarray(d,f)),s),R=Zn(t.subarray(f,f+16));return `${l}-${h}-${R}`}function ir(n,e="User ID"){let t=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;if(n){if(typeof n!="string")throw new a(`${e} should be type: string.`,{code:"INVALID_PARAMETER"});if(!n.match(t))throw new a(`${e} is invalid.`,{code:"INVALID_PARAMETER"})}else throw new a(`${e} is empty.`,{code:"INVALID_PARAMETER"});return n}function sr(n){if(n&&(typeof n!="string"||n.charAt(0)!=="+"||isNaN(Number(n.substring(1)))))throw new a('"phone_number" is invalid. The format should be "+00123456789". Type: string.',{code:"INVALID_PARAMETER"});return n||""}function or(n){if(n){if(typeof n!="string")throw new a('"birthdate" is invalid. The format should be "yyyy-mm-dd". Type: string.',{code:"INVALID_PARAMETER"});{let e=new RegExp(/([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))/);if(n.length!==10||n.split("-").length!==3||!e.test(n))throw new a('"birthdate" is invalid. The format should be "yyyy-mm-dd". Type: string.',{code:"INVALID_PARAMETER"})}}return n||""}function ar(n){if(n){if(typeof n!="string")throw new a('"password" should be type: string.',{code:"INVALID_PARAMETER"});if(n.length<6)throw new a('"password" should be at least 6 characters.',{code:"INVALID_PARAMETER"});if(n.length>60)throw new a('"password" can be up to 60 characters max.',{code:"INVALID_PARAMETER"})}else throw new a('"password" is required.',{code:"INVALID_PARAMETER"});return n}function cr(n,e="email"){if(n){if(typeof n!="string")throw new a(`"${e}"should be type: string.`,{code:"INVALID_PARAMETER"});if(n.length<5)throw new a(`"${e}" should be at least 5 characters.`,{code:"INVALID_PARAMETER"});if(/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/.test(n)&&(n=n.trim(),n.split("@")[1].split(".").length>=2))return n.toLowerCase()}else throw new a(`"${e}" is required.`,{code:"INVALID_PARAMETER"});throw new a(`"${n}" is an invalid email.`,{code:"INVALID_PARAMETER"})}function lr(n){let e=typeof window<"u",t=(()=>{let r=e&&window.location.origin||null;return r&&r.slice(-1)==="/"&&(r=r.slice(0,-1)),r})(),i=r=>{if(typeof r=="string"){if(r==="*")return "*";{let s=r.trim();if(s[0]==="/"&&t){if(t.slice(0,5)==="file:")throw new a(`"${r}" is an invalid url. Relative URL does not work on local file system. Use full URL string.`,{code:"INVALID_PARAMETER"});s=t+s;}else if(s[0]==="."&&t){if(t.slice(0,5)==="file:")throw new a(`"${r}" is an invalid url. Relative URL does not work on local file system. Use full URL string.`,{code:"INVALID_PARAMETER"});let c=e?window.location.href.split("?")[0]:"";c.slice(-1)!=="/"&&(c+="/"),s=c+s.slice(1);}let o;try{o=new URL(s);}catch{throw new a(`"${r}" is an invalid url.`,{code:"INVALID_PARAMETER"})}if(o.protocol)return o.href}}throw new a(`"${r}" is an invalid url.`,{code:"INVALID_PARAMETER"})};return Array.isArray(n)?n.map(r=>i(r)):i(n)}function ur(n,e,t=[],i){let r=D(n,i),s=r.data;e.service="string",e.owner="string";let o={};for(let c in e)if(s&&typeof s=="object"&&!Array.isArray(s)&&s.hasOwnProperty(c))if(typeof s[c]=="function")o[c]=s[c];else try{o[c]=JSON.parse(JSON.stringify(s[c]));}catch{o[c]=s[c];}i?.precall&&i.precall({data:o,files:r?.files||[]});try{return rr__default.default(o,e,t)}catch(c){throw new a(c.message,{code:"INVALID_PARAMETER"})}}var g={UserId:ir,PhoneNumber:sr,Birthdate:or,Password:ar,Email:cr,Url:lr,Params:ur};var U=null;function Ne(n){let e={tkid:"ticket_id",cond:"condition",stmp:"timestamp",actn:"action",cnt:"count",ttl:"time_to_live",plch:"placeholder",hash:"hash",desc:"description",pmc:"limit_per_user"},t={};for(let i in n)if(i==="tkid"){let r=n[i].split("#");if(r.length===1){t.ticket_id=r[0];continue}t.ticket_id=r[1],t.consume_id=r[2],t.user_id=r[3];let s=r[2].slice(-4);if(t.is_test=s===":CHK",!n.stmp){let o=r[2].slice(0,-4);/^[0-9]+$/.test(o)?t.timestamp=parseInt(o,10):t.timestamp=B(r[2].slice(0,-4));}}else e[i]?t[e[i]]=n[i]:t[i]=n[i];return t}async function ot(n){if(!n.ticket_id)throw new a("Ticket ID is required.",{code:"INVALID_PARAMETER"});if(!n.method)throw new a('Method is required. Should be either "GET" or "POST"',{code:"INVALID_PARAMETER"});let e=n.ticket_id;await this.__connection;let t=await w.bind(this)(`https://${this.service.slice(0,4)}.${this.customApiDomain}/auth/consume/${this.service}/${this.owner}/${e}`,n?.data||{},{method:n.method,auth:!!n?.auth});return Ne(t)}async function at(n,e){await this.__connection;let t=await w.bind(this)("ticket",Object.assign({exec:"list"},n||{}),{auth:true,fetchOptions:e});return t.list=t.list.map(Ne),t}async function ct(n,e){await this.__connection;let t=await w.bind(this)("ticket",Object.assign({exec:"consumed"},n||{}),{auth:true,fetchOptions:e});return t.list=t.list.map(Ne),t}async function lt(n){return w.bind(this)("register-ticket",Object.assign({exec:"reg"},n),{auth:true})}async function ut(n){return w.bind(this)("register-ticket",Object.assign({exec:"unreg"},n),{auth:true})}async function ne(){if(await this.__connection,this.session){let n=Math.floor(Date.now()/1e3),t=this.session.getIdToken().getExpiration();if(t<n){this.log("request:requesting new token",null);try{await F.bind(this)().getSession({refreshToken:!0}),this.log("request:received new tokens",{exp:this.session?.idToken?.payload?.exp,currentTime:n,expiresIn:t-n,token:this.session?.accessToken?.jwtToken,refreshToken:this.session?.refreshToken?.token});}catch(i){throw this.log("request:new token error",i),new a("User login is required.",{code:"INVALID_REQUEST"})}}else this.log("request:tokens",{exp:this.session.idToken.payload.exp,currentTime:n,expiresIn:t-n,token:this.session.accessToken.jwtToken,refreshToken:this.session.refreshToken.token});return this.session?.idToken?.jwtToken}else throw this.log("request:no session",null),z.bind(this)(),new a("User login is required.",{code:"INVALID_REQUEST"})}function st(n,e){return new Promise((t,i)=>{e.refreshSession(n.getRefreshToken(),(r,s)=>{this.log("getSession:refreshSessionCallback",{refreshErr:r,refreshedSession:s}),r?(z.bind(this)(),i(r)):s.isValid()?t(s):(z.bind(this)(),i(new a("Invalid session.",{code:"INVALID_REQUEST"})));});})}function F(){if(!this.userPool)throw new a("User pool is missing",{code:"INVALID_REQUEST"});let n=()=>{let s=U.getSignInUserSession().getIdToken().payload||null,o=ae(s);return this.log("normalized user attribute",o),this.__user=o,o},e=async s=>new Promise((o,c)=>{this.log("getSession:option",s);let{refreshToken:u=false,skipUserUpdateEventTrigger:d=false}=s||{};if(u&&d&&(d=false),U=this.userPool.getCurrentUser(),!U){this.log("getSession:cognitoUser",U),z.bind(this)(),c(null);return}let f=l=>{let h=l.getIdToken().payload;if(this.log("getSession:respond:sessionAttribute",h),h["custom:service"]!==this.service)throw this.log("getSession:respond","invalid service, signing out"),z.bind(this)(),new a("Invalid session.",{code:"INVALID_REQUEST"});return this.session=l,n(),d||this._runOnUserUpdateListeners(this.user),this.session};U.getSession((l,h)=>{if(this.log("getSession:getSessionCallback",{err:l,session:h}),!h){z.bind(this)(),c(new a("Current session does not exist.",{code:"INVALID_REQUEST"}));return}if(l){st.bind(this)(h,U).then(E=>o(f(E))).catch(c);return}let R=Math.floor(Date.now()/1e3),p=h.getIdToken(),A=p.getExpiration(),k=A<R;if(this.log("getSession:currentTime",R),this.log("getSession:idTokenExp",A),this.log("getSession:isExpired",k),this.log("getSession:existingBearerToken",this.bearerToken),this.bearerToken=p.getJwtToken(),k||u||!h.isValid())st.bind(this)(h,U).then(E=>o(f(E))).catch(c);else try{o(f(h));}catch(E){c(E);}});}),t=(s,o)=>{let c=o||s.includes(this.service+"-")?s:this.service+"-"+V.hash(s);return {cognitoUser:new amazonCognitoIdentityJs.CognitoUser({Username:c,Pool:this.userPool}),cognitoUsername:c}};return {getSession:e,authenticateUser:(s,o,c=false,u=false)=>new Promise((d,f)=>{this.__request_signup_confirmation=null,this.__disabledAccount=null;let l=t(s,c),h=l.cognitoUsername,R=new amazonCognitoIdentityJs.AuthenticationDetails({Username:h,Password:o});l.cognitoUser.authenticateUser(R,{newPasswordRequired:(p,A)=>{this.__disabledAccount=null,this.__request_signup_confirmation=h,p["custom:signup_ticket"]==="PASS"||p["custom:signup_ticket"]==="MEMBER"||p["custom:signup_ticket"]==="OIDPASS"?l.cognitoUser.completeNewPasswordChallenge(o,{},{onSuccess:k=>{U=l.cognitoUser,e().then(E=>d(this.user));},onFailure:k=>{f(new a(k.message||"Failed to authenticate user.",{code:k.code}));}}):f(new a("User's signup confirmation is required.",{code:"SIGNUP_CONFIRMATION_NEEDED"}));},onSuccess:p=>e({skipUserUpdateEventTrigger:true}).then(A=>{this.__disabledAccount=null,this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user),d(this.user);}),onFailure:p=>{let A=[],{parsed:k,code:E}=_e(p),P=typeof p?.message=="string"?p.message:"";if(E==="NotAuthorizedException"?P.includes("User is disabled.")?(this.__disabledAccount=h,A=["This account is disabled.","USER_IS_DISABLED"]):u?A=["The account already exists.","ACCOUNT_EXISTS"]:A=["Incorrect username or password.","INCORRECT_USERNAME_OR_PASSWORD"]:E==="UserNotFoundException"?A=["Incorrect username or password.","INCORRECT_USERNAME_OR_PASSWORD"]:E==="UserNotConfirmedException"?(this.__request_signup_confirmation=h,A=["User's signup confirmation is required.","SIGNUP_CONFIRMATION_NEEDED"]):(E==="TooManyRequestsException"||E==="LimitExceededException")&&(A=["Too many attempts. Please try again later.","REQUEST_EXCEED"]),k.code==="SIGNUP_CONFIRMATION_NEEDED"&&(this.__request_signup_confirmation=h),A.length){let S=A[1],T=A[0];f(new a(T,{code:S,cause:p}));}else f(k);}});}),createCognitoUser:t,signup:(s,o,c)=>new Promise((u,d)=>{this.userPool.signUp(s,o,c,null,(f,l)=>{if(f){let{parsed:h,code:R}=_e(f),p=[];R==="UsernameExistsException"?p=["The account already exists.","EXISTS"]:R==="InvalidPasswordException"?p=["Invalid password. Password must be at least 6 characters.","INVALID_PARAMETER"]:R==="InvalidParameterException"?p=[h.message||"Invalid parameter.","INVALID_PARAMETER"]:R==="TooManyRequestsException"||R==="LimitExceededException"?p=["Too many attempts. Please try again later.","REQUEST_EXCEED"]:R==="CodeDeliveryFailureException"?p=["Failed to deliver verification code.","CODE_DELIVERY_FAILURE"]:R==="UserLambdaValidationException"&&(p=[h.message||"Signup validation failed.","INVALID_REQUEST"]),p.length?d(new a(p[0],{code:p[1],cause:f})):d(h);return}u(l);});})}}function _e(n){let e=typeof n?.code=="string"&&n.code.trim()?n.code.trim():"ERROR",i=((typeof n?.message=="string"?n.message:typeof n=="string"?n:"An error occurred.")||"An error occurred.").trim();i||(i="An error occurred.");let r=i.match(/#([A-Za-z0-9_]+)\s*:\s*([\s\S]+)/),s=r?.[1]?.trim()||e,o=r?.[2]?.trim()||i;return {parsed:new a(o,{code:s,cause:n}),code:e}}async function dt(n){await this.__authConnection;let e=n?.refreshToken||false;if(!e)return this.user;try{return await F.bind(this)().getSession(Object.assign({skipUserUpdateEventTrigger:!e,refreshToken:e},n)),this.user}catch{return null}}async function gt(n){await this.__connection,n=g.Params(n,{token:"string",id:"string",merge:s=>{if(s===void 0)return false;if(typeof s=="string")return [s];if(Array.isArray(s)){for(let o of s)if(typeof o!="string")throw new a('"merge" array items should be type: <string>.',{code:"INVALID_PARAMETER"})}if(typeof s!="boolean"&&!Array.isArray(s))throw new a('"merge" should be type: <boolean | string[]>.',{code:"INVALID_PARAMETER"});return s}});let e=await w.bind(this)("openid-logger",n),t=e.logger.split("#"),i=this.service+"-"+t[0],r=t[1];return {userProfile:await F.bind(this)().authenticateUser(i,r,true,true),openid:e.openid}}function mr(n){let e=typeof globalThis<"u"?globalThis:void 0;if(e?.Buffer)return e.Buffer.from(n,"base64").toString("utf8");if(typeof atob=="function"){let t=atob(n),i=new Uint8Array(t.length);for(let r=0;r<t.length;r++)i[r]=t.charCodeAt(r);return typeof TextDecoder<"u"?new TextDecoder().decode(i):t}throw new Error("No base64 decoder available in this environment")}function br(n){let e=n.split(".");if(e.length!==3)throw new Error("Invalid JWT format");let i=e[1].replace(/-/g,"+").replace(/_/g,"/"),r=mr(i);return JSON.parse(r)}async function ft(n){await this.__authConnection,this.log("loginWithToken:params",n),n=g.Params(n,{idToken:"string",accessToken:"string",refreshToken:"string"},["idToken"]);let e=br(n.idToken);if(this.log("loginWithToken:idTokenPayload",e),e["custom:service"]!==this.service)throw new a("Token does not belong to this service.",{code:"INVALID_REQUEST"});let t=Math.floor(Date.now()/1e3);if(e.exp&&e.exp<t)throw new a("Token has expired.",{code:"INVALID_REQUEST"});if(this.__user=ae(e),this.session=null,n.accessToken&&n.refreshToken)try{if(this.session=new amazonCognitoIdentityJs.CognitoUserSession({IdToken:new amazonCognitoIdentityJs.CognitoIdToken({IdToken:n.idToken}),AccessToken:new amazonCognitoIdentityJs.CognitoAccessToken({AccessToken:n.accessToken}),RefreshToken:new amazonCognitoIdentityJs.CognitoRefreshToken({RefreshToken:n.refreshToken})}),this.log("loginWithToken:session",this.session),this.log("loginWithToken:CognitoUser",amazonCognitoIdentityJs.CognitoUser),this.log("loginWithToken:userPool",this.userPool),amazonCognitoIdentityJs.CognitoUser&&this.userPool){this.log("loginWithToken:cognito:username",e["cognito:username"]);let i={Username:e["cognito:username"],Pool:this.userPool};this.log("loginWithToken:cognitoUserParams",i),U=new amazonCognitoIdentityJs.CognitoUser(i),U.setSignInUserSession(this.session),this.log("loginWithToken:cognitoUserRestored",{cognitoUserType:typeof U,cognitoUserKeys:Object.keys(U||{}),cognitoUser:U});}}catch(i){this.log("loginWithToken:err",i);try{this.log("loginWithToken:err:stringified",JSON.stringify(i));}catch{this.log("loginWithToken:err:stringifyFail",String(i));}try{let r=Object.keys(i||{}),s=Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(i||{}):[],o=Object.getOwnPropertyDescriptors?Object.getOwnPropertyDescriptors(i||{}):{};this.log("loginWithToken:createSessionError:allKeys",{keys:r,symbols:s,descriptors:o});}catch(r){this.log("loginWithToken:createSessionError:allKeysFail",String(r));}}return this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user),this.user}async function M(){return await this.__connection,this.__user?.service===this.service?this.__user?.owner===this.host:(await ce.bind(this)(),false)}async function z(n=false){let e=null;U&&(n?e=new Promise((i,r)=>{U.globalSignOut({onSuccess:s=>{this.log("globalSignOut:success",s),i(s);},onFailure:s=>{this.log("globalSignOut:error",s),r(s);}});}):U.signOut());let t={session:null,__startKeyHistory:{},__cached_requests:{},__user:null};e&&(e=await e);for(let i in t)this[i]=t[i];return this._runOnUserUpdateListeners(null),this._runOnLoginListeners(null),e}async function ce(n){await this.__connection;let{data:e}=D(n);return await z.bind(this)(e?.global),"SUCCESS: The user has been logged out."}async function ht(){if(!this.__request_signup_confirmation)throw new a("Least one login attempt is required.",{code:"INVALID_REQUEST"});return await w.bind(this)("confirm-signup",{username:this.__request_signup_confirmation})}async function pt(n=false){if(typeof n=="string")n=g.Url(n);else if(typeof n!="boolean")throw new a("Argument should be type: <boolean | string>.",{code:"INVALID_REQUEST"});if(!this.__disabledAccount)throw new a("Least one signin attempt of disabled account is required.",{code:"INVALID_REQUEST"});return await w.bind(this)("recover-account",{username:this.__disabledAccount,redirect:n}),"SUCCESS: Recovery e-mail has been sent."}async function Ce(n){let e=g.Params(n,{username:"string",email:"string",password:"string"},["password"]);if(await this.__authConnection,e.email)try{g.Email(e.email);}catch{e.username=e.email,delete e.email;}if(!e.username&&!e.email)throw new a('Least one of "username" or "email" is required.',{code:"INVALID_PARAMETER"});return await F.bind(this)().authenticateUser(e.username||e.email,e.password)}async function mt(n,e){await this.__authConnection;let t={username:"string",password:d=>g.Password(d),email:d=>g.Email(d),name:"string",address:d=>{if(!d)return "";if(typeof d=="string")return d;if(typeof d=="object")return JSON.stringify(d)},gender:"string",birthdate:d=>d?g.Birthdate(d):"",phone_number:d=>d?g.PhoneNumber(d):"",email_public:["boolean",()=>false],address_public:["boolean",()=>false],gender_public:["boolean",()=>false],birthdate_public:["boolean",()=>false],phone_number_public:["boolean",()=>false],access_group:"number",misc:"string",picture:d=>d?g.Url(d):"",profile:d=>d?g.Url(d):"",family_name:"string",given_name:"string",middle_name:"string",nickname:"string",website:d=>d?g.Url(d):""},i=g.Params(n||{},t,["email","password"]);await ce.bind(this)(),e=g.Params(e||{},{email_subscription:d=>{if(typeof d!="boolean")throw new a('"option.email_subscription" should be type: <boolean>.',{code:"INVALID_PARAMETER"});if(!e?.signup_confirmation)throw new a('"option.signup_confirmation" is required for email subscription.',{code:"INVALID_PARAMETER"});return d},signup_confirmation:d=>{let f=d;if(typeof d=="string")f=g.Url(d);else if(typeof d=="boolean")f=d;else throw new a('"option.signup_confirmation" should be type: <string | boolean>.',{code:"INVALID_PARAMETER"});if(f&&!i.email)throw new a('"email" is required for signup confirmation.',{code:"INVALID_PARAMETER"});return f},login:d=>{if(typeof d=="boolean"){if(e.signup_confirmation&&d)throw new a('"login" is not allowed when "option.signup_confirmation" is true.',{code:"INVALID_PARAMETER"});return d}throw new a('"option.login" should be type: boolean.',{code:"INVALID_PARAMETER"})}});let r=e?.login||false;if(i.signup_confirmation=e?.signup_confirmation||false,i.email_subscription=e?.email_subscription||false,i.email_public&&!i.signup_confirmation)throw new a('"option.signup_confirmation" should be true if "email_public" is set to true.',{code:"INVALID_PARAMETER"});i.service=this.service,i.owner=this.owner;let s=F.bind(this)().createCognitoUser(i.username||i.email);for(let d of ["email_public","address_public","gender_public","birthdate_public","phone_number_public"])i[d]=i[d]?"1":"0";i.access_group&&(i.access_group=i.access_group.toString());let o=(await w.bind(this)("signupkey",{username:s.cognitoUsername,signup_confirmation:typeof i.signup_confirmation=="boolean"?JSON.stringify(i.signup_confirmation):i.signup_confirmation,email_subscription:i.email_subscription})).split(":"),c=o.slice(1).join(":"),u=[new amazonCognitoIdentityJs.CognitoUserAttribute({Name:"custom:signup",Value:o[0]}),new amazonCognitoIdentityJs.CognitoUserAttribute({Name:"locale",Value:c.split("#")[1]}),new amazonCognitoIdentityJs.CognitoUserAttribute({Name:"custom:signup_ticket",Value:c})];for(let d in t){let f=["email_public","address_public","gender_public","birthdate_public","phone_number_public","misc","service","owner"];i[d]!==""&&(d==="username"||d==="password"||d==="access_group"||(f.includes(d)?u.push(new amazonCognitoIdentityJs.CognitoUserAttribute({Name:"custom:"+d,Value:i[d]})):u.push(new amazonCognitoIdentityJs.CognitoUserAttribute({Name:d,Value:i[d]}))));}return await F.bind(this)().signup(s.cognitoUsername,i.password,u),i.signup_confirmation?(U=s.cognitoUser,this.__request_signup_confirmation=s.cognitoUsername,"SUCCESS: The account has been created. User's signup confirmation is required."):r?Ce.bind(this)({email:i.username||i.email,password:i.password}):"SUCCESS: The account has been created."}async function bt(){await this.__connection;let n=await w.bind(this)("remove-account",{disable:this.__user.user_id},{auth:true});return await ce.bind(this)(),n}async function _t(n){await this.__connection;let e=g.Params(n,{email:r=>g.Email(r),code:["number","string"],new_password:r=>g.Password(r)},["email","code","new_password"]),t=e.code,i=e.new_password;return typeof t=="number"&&(t=t.toString()),new Promise(async(r,s)=>{F.bind(this)().createCognitoUser(e.email).cognitoUser.confirmPassword(t,i,{onSuccess:c=>{r("SUCCESS: New password has been set.");},onFailure:c=>{s(new a(c?.message||"Failed to reset password.",{code:c?.code||"ERROR",cause:c}));}});})}async function yt(n,e){await this.__connection;let t;if(!U)throw new a("The user has to be logged in.",{code:"INVALID_REQUEST"});if(n==="email"||n==="phone_number"){if(!this.__user.hasOwnProperty(n))throw new a(`No ${n==="email"?"e-mail":"phone number"} to verify`,{code:"INVALID_REQUEST"});if(this.__user?.[`${n}_verified`])return `SUCCESS: "${n}" is verified.`;t=(e?g.Params(e,{code:"string"}):{}).code||"";}else return;return new Promise((i,r)=>{let s={onSuccess:o=>{t?F.bind(this)().getSession({refreshToken:true}).then(()=>{this.__user&&(this.__user[n+"_verified"]=true),i(`SUCCESS: "${n}" is verified.`);}).catch(c=>{r(c);}):i("SUCCESS: Verification code has been sent.");},onFailure:o=>{r(new a(o.message||"Failed to request verification code.",{code:o?.code}));}};t?U?.verifyAttribute(n,t,s):(s.inputVerificationCode=null,U?.getAttributeVerificationCode(n,s));})}function wt(n){return yt.bind(this)("phone_number",n)}function Et(n){return yt.bind(this)("email",n)}async function Rt(n){await this.__connection;let e=g.Params(n,{email:t=>g.Email(t)},["email"]);return new Promise(async(t,i)=>{F.bind(this)().createCognitoUser(e.email).cognitoUser.forgotPassword({onSuccess:s=>{t("SUCCESS: Verification code has been sent.");},onFailure:s=>{let{parsed:o,code:c}=_e(s),u={UserNotFoundException:"NOT_EXISTS",InvalidParameterException:"INVALID_PARAMETER",NotAuthorizedException:"INVALID_REQUEST",LimitExceededException:"REQUEST_EXCEED",TooManyRequestsException:"REQUEST_EXCEED",CodeDeliveryFailureException:"CODE_DELIVERY_FAILURE"}[c]||o.code||c||"ERROR";i(new a(o.message,{code:u,cause:s}));}});})}async function At(n){if(await this.__connection,!this.session)throw new a("User login is required.",{code:"INVALID_REQUEST"});let e=g.Params(n,{current_password:"string",new_password:"string"});if(!e?.current_password)throw new a('"current_password" is required to change password.',{code:"INVALID_PARAMETER"});if(!e?.new_password)throw new a('"new_password" is required to change password.',{code:"INVALID_PARAMETER"});return g.Password(e.current_password),g.Password(e.new_password),new Promise((t,i)=>{U.changePassword(e.current_password,e.new_password,(r,s)=>{if(r){if(r?.code==="InvalidParameterException")i(new a("Invalid password parameter.",{code:"INVALID_PARAMETER"}));else if(r?.code==="NotAuthorizedException")i(new a("Incorrect password.",{code:"INVALID_REQUEST"}));else if(r?.code==="TooManyRequestsException"||r?.code==="LimitExceededException")i(new a("Too many attempts. Please try again later.",{code:"REQUEST_EXCEED"}));else {let{parsed:o}=_e(r);i(o);}return}t("SUCCESS: Password has been changed.");});})}async function It(n){if(await this.__connection,!this.session)throw new a("User login is required.",{code:"INVALID_REQUEST"});let e=g.Params(n||{},{user_id:r=>g.UserId(r),email:r=>g.Email(r),address:r=>{if(!r)return "";if(typeof r=="string")return r;if(typeof r=="object")return JSON.stringify(r)},name:"string",gender:"string",birthdate:r=>r?g.Birthdate(r):"",phone_number:r=>r?g.PhoneNumber(r):"",email_public:"boolean",phone_number_public:"boolean",address_public:"boolean",gender_public:"boolean",birthdate_public:"boolean",misc:"string",picture:r=>r?g.Url(r):"",profile:r=>r?g.Url(r):"",family_name:"string",given_name:"string",middle_name:"string",nickname:"string",website:r=>r?g.Url(r):""});if(e&&typeof e=="object"&&!Object.keys(e).length)return this.user;e.email&&(e.preferred_username=this.service+"-"+V.hash(e.email));let t=[["email_public","email_verified","User's e-mail should be verified to set"],["phone_number_public","phone_number_verified","User's phone number should be verified to set"]];if(this.__user){for(let r of t)if(e[r[0]]&&!this.__user[r[1]])throw new a(`${r[2]} "${r[0]}" to true.`,{code:"INVALID_REQUEST"})}let i=[];for(let r in e){if(e[r]===this.user[r]){i.push(r);continue}if(["email_public","phone_number_public","address_public","gender_public","birthdate_public","misc"].includes(r)){let o=e[r];typeof o=="boolean"&&(o=o?"1":"0"),e["custom:"+r]=o,i.push(r);}}for(let r of i)delete e[r];if(e.user_id)if(e.user_id===this.user.user_id)delete e.user_id;else return w.bind(this)("admin-edit-profile",{attributes:e},{auth:true});if(e&&typeof e=="object"&&Object.keys(e).length){let r=[];for(let s in e)r.push(new amazonCognitoIdentityJs.CognitoUserAttribute({Name:s,Value:e[s]}));return await new Promise((s,o)=>{U?.updateAttributes(r,(c,u)=>{c&&o([c?.code||c?.name,c?.message||"Failed to update user settings."]),s(u);});}),await F.bind(this)().getSession({refreshToken:true}),this.user}return this.user}async function Tt(n,e){n=D(n).data,n||(n={searchFor:"timestamp",condition:">",value:0},e||(e={}),e.ascending=false),await this.__connection;let t={user_id:r=>Array.isArray(r)?r.map(s=>g.UserId(s)):g.UserId(r),email:"string",phone_number:"string",locale:r=>{if(typeof r!="string"||typeof r=="string"&&r.length>5)throw new a('Value of "locale" should be a country code.',{code:"INVALID_PARAMETER"});return r},name:"string",address:"string",gender:"string",birthdate:r=>g.Birthdate(r),subscribers:"number",timestamp:"number",access_group:"number",approved:"string"},i=["searchFor","value"];if(n=g.Params(n,{searchFor:["user_id","name","email","phone_number","address","gender","birthdate","locale","subscribers","timestamp","access_group","approved"],condition:[">",">=","=","<","<=","gt","gte","eq","lt","lte",()=>"="],value:r=>{let s=t[n.searchFor];if(typeof s=="function")return s(r);if(typeof r!==s)throw new a(`Value does not match the type of "${n.searchFor}" index.`,{code:"INVALID_PARAMETER"});return r},range:r=>{let s=t[n.searchFor];if(typeof s=="function")return s(r);if(typeof r!==s)throw new a(`Range does not match the type of "${n.searchFor}" index.`,{code:"INVALID_PARAMETER"});return r}},i),n?.condition&&n?.condition!=="="&&n.hasOwnProperty("range"))throw new a("Conditions does not apply on range search.",{code:"INVALID_PARAMETER"});if(n.searchFor==="user_id"&&(n.condition!=="="||n.range))throw new a(`Conditions are not allowed on "${n.searchFor}"`,{code:"INVALID_PARAMETER"});if(typeof n?.value=="string"&&!n?.value)throw new a("Value should not be an empty string.",{code:"INVALID_PARAMETER"});if(typeof n?.searchFor=="string"&&!n?.searchFor)throw new a('"searchFor" should not be an empty string.',{code:"INVALID_PARAMETER"});return w.bind(this)("get-users",n,{auth:true,fetchOptions:e})}async function St(n){await this.__connection;let e=await w.bind(this)("last-verified-email",n,{auth:true});return e.includes("SUCCESS")?(await F.bind(this)().getSession({refreshToken:true}),this.user):e}async function Pt(n){return await this.__connection,n=g.Params(n,{username:g.Email,redirect:g.Url},["username"]),await w.bind(this)("request-username-change",n,{auth:true})}var re=null,xt=typeof SubmitEvent<"u",yr=typeof HTMLFormElement<"u",ue=$(),Le=0;function vt(n){if(!n)return null;let e=Number(n);if(Number.isFinite(e))return Math.max(0,e*1e3);let t=Date.parse(n);return Number.isNaN(t)?null:Math.max(0,t-Date.now())}function Oe(n,e){return e>0?n/e*100:0}var kt=n=>{let{auth:e,type:t,endpoints:i}=n,r=i[0],s=i[1];if(Le++,t==="admin"){let o=Object.entries(r).filter(([c,u])=>c.includes(e?"_private":"_public")&&c!=="get_users_private"&&c!=="service_public"&&typeof u=="string").map(([,c])=>c);if(!o.length)throw new a("No available admin gateways.",{code:"INVALID_REQUEST"});return o[Le%o.length]}if(t==="record"){let o=Object.entries(s).filter(([c,u])=>c.includes(e?"record_private":"record_public")&&typeof u=="string").map(([,c])=>c);if(!o.length)throw new a("No available record gateways.",{code:"INVALID_REQUEST"});return o[Le%o.length]}throw new a("Invalid gateway type.",{code:"INVALID_REQUEST"})};async function wr(n,e){let t=await Promise.all([this.admin_endpoint,this.record_endpoint]),i=t[0],r=t[1],s=n.split("?"),o=s.length>1?"?"+s[1]:"";switch(n=s[0],n){case "get-users":return i.get_users_private+n+o;case "service":return i.service_public+n+o;case "get-newsletters":case "get-public-newsletters":case "subscribe-newsletter":case "subscribe-public-newsletter":case "signupkey":case "admin-newsletter-request":case "admin-signup":case "confirm-signup":case "openid-logger":case "block-account":case "admin-edit-profile":case "remove-account":case "post-secure":case "recover-account":case "mock":case "grant-access":case "last-verified-email":case "ticket":case "register-ticket":case "get-newsletter-subscription":case "request-username-change":case "send-inquiry":case "register-newsletter-group":case "newsletter-group-endpoint":case "invitation-list":case "csr":return kt.bind(this)({auth:e,type:"admin",endpoints:t})+n+o;case "post-record":return (e?r.post_private:r.post_public)+n+o;case "get-records":return (e?r.get_private:r.get_public)+n+o;case "del-files":case "del-records":return r.del_private+n+o;case "store-subscription":case "get-vapid-public-key":case "push-notification":case "delete-subscription":case "subscription":case "get-subscription":case "get-table":case "get-tag":case "get-uniqueid":case "get-index":case "get-signed-url":case "grant-private-access":case "request-private-access-key":case "get-ws-group":case "check-schema":case "get-feed":case "castspell":case "dopamine":case "getspell":return kt.bind(this)({auth:e,type:"record",endpoints:t})+n+o;default:return g.Url(n)+o}}var le={};function Dt(){re&&(re.terminate(),re=null);}async function w(n,e=null,t,i){this.log("request",{url:n,data:e,options:t,_etc:i||{}}),t=t||{};let{auth:r=false,method:s="post",bypassAwaitConnection:o=false}=t;s=s.toUpperCase();let c=null,u=e?.service||this.service,d=e?.owner||this.owner,f=null,l=await wr.bind(this)(n,!!r);if(!o&&(c=await this.__connection,!c))throw new a("Invalid connection. The service could have been disabled, or has a restricted CORS.",{code:"INVALID_REQUEST"});r&&(f=await ne.bind(this)());let h={},{fetchMore:R=false,progress:p}=t?.fetchOptions||{};if(t?.fetchOptions&&Object.keys(t.fetchOptions).length){for(let x of ["limit","startKey","ascending"])t.fetchOptions.hasOwnProperty(x)&&(h[x]=t.fetchOptions[x]);h=g.Params(h,{limit:x=>{if(typeof x!="number")throw new a("Fetch limit should be a number.",{code:"INVALID_REQUEST"});if(x>1e3)throw new a("Fetch limit should be below 1000.",{code:"INVALID_REQUEST"});return x},startKey:x=>x,ascending:"boolean"});}let A=i?.ignoreService?{}:{service:u,owner:d};Object.assign(A,h),e=D(e).data,e?e&&typeof e=="object"&&(e=Object.assign(A,e)):e=A;let k=`${s}:${r?"auth":"public"}:${n}`,E=(()=>{if(e&&typeof e=="object"&&Object.keys(e).length&&!(ue&&e instanceof FormData)){let x=function(v){return typeof v=="object"&&v!==null?Object.keys(v).sort().reduce((N,O)=>(typeof v[O]=="object"&&v[O]!==null?N[O]=x(v[O]):N[O]=v[O],N),{}):v};return V.hash(k+"/"+JSON.stringify(x(e)))}return V.hash(k+"/"+u)})(),{requestKey:P,requestKeyWithStartKey:S}=Er.bind(this)({params:e,url:n,fetchMore:R,hashedParams:E});if(!P||P&&typeof P=="object")return P;if(this.log("requestKey",S),typeof S=="string"&&le[S]instanceof Promise)return this.log("request:returning pending",S),le[S];let T={Accept:"*/*"};if(Object.prototype.hasOwnProperty.call(t,"contentType")&&t.contentType!==void 0){let x=t.contentType===null?"application/x-www-form-urlencoded":t.contentType;x&&(T["Content-Type"]=x);}else T["Content-Type"]="application/json";f&&(T.Authorization=f);let q={public_identifier:this.__public_identifier,service:u,owner:d};T["Content-Meta"]=JSON.stringify(q);let j={headers:T};if(t?.responseType&&(j.responseType=t.responseType),s==="GET"){if(e){let x=[];if(ue&&e instanceof FormData?x=Array.from(e.entries()).map(([v,N])=>{let O=typeof N=="string"?N:N.name;return encodeURIComponent(v)+"="+encodeURIComponent(O)}):x=Object.keys(e).map(v=>{let N=e[v];return typeof N!="string"&&(N=JSON.stringify(N)),encodeURIComponent(v)+"="+encodeURIComponent(N)}),x.length){let v=l.includes("?")?l.endsWith("?")||l.endsWith("&")?"":"&":"?";l+=v+x.join("&");}}j.body=null;}else if(ue&&e instanceof FormData)j.body=e;else if(T["Content-Type"]==="application/x-www-form-urlencoded"&&e&&typeof e=="object"){let x=new URLSearchParams;for(let v of Object.keys(e)){let N=e[v];x.append(v,typeof N=="string"?N:JSON.stringify(N));}j.body=x.toString();}else typeof e=="string"?j.body=e:j.body=e?JSON.stringify(e):null;if(j.method=s,re===null){let x={batchSize:this.requestBatchSize,breakWhenError:false,onProgress:v=>{this.onBatchProcess.forEach(N=>N(v));}};re=new _r__default.default(x);}return this.log("request-opt",j),new Promise((x,v)=>{re.add([async()=>{let N=Ut.bind(this)(l,j,p);le[S]=N;try{let O=Rr.bind(this)({hashedParam:P,requestKeyWithStartKey:S,url:n,fetched:await N});return delete le[S],this.log("request:end",O),x(O),O}catch(O){throw delete le[S],this.log("request:err",O),v(O),O}}]);})}function Er(n){let{params:e={},url:t,fetchMore:i=false,hashedParams:r}=n||{};if(e.startKey){if(!(typeof e.startKey=="object"&&Object.keys(e.startKey).length)&&e.startKey!=="start"&&e.startKey!=="end")throw new a(`"${e.startKey}" is invalid startKey key.`,{code:"INVALID_PARAMETER"});e.startKey==="start"&&(i=false,delete e.startKey);}if(!i){if(this.__cached_requests?.[t]?.[r]&&delete this.__cached_requests[t][r],this.__startKeyHistory?.[t]?.[r]){if(Array.isArray(this.__startKeyHistory[t][r])&&this.__startKeyHistory[t][r].length)for(let u of this.__startKeyHistory[t][r]){let d=r+V.hash(u);this.__cached_requests?.[t]&&this.__cached_requests?.[t]?.[d]&&delete this.__cached_requests[t][d];}delete this.__startKeyHistory[t][r];}return {requestKeyWithStartKey:r,requestKey:r}}if(!Array.isArray(this.__startKeyHistory?.[t]?.[r]))return {requestKeyWithStartKey:r,requestKey:r};let s=this.__startKeyHistory[t][r],o=s[s.length-1],c=r;if(o){if(o==="end")return {requestKey:{list:[],startKey:"end",endOfList:true,startKeyHistory:s},requestKeyWithStartKey:c};c+=V.hash(o),e.startKey=JSON.parse(o);}return this.__cached_requests?.[t]?.[c]?{requestKey:this.__cached_requests[t][c],requestKeyWithStartKey:c}:{requestKeyWithStartKey:c,requestKey:r}}function Ut(n,e,t){return new Promise((i,r)=>{let s=new XMLHttpRequest;s.open(e.method||"GET",n);for(var o in e.headers||{})s.setRequestHeader(o,e.headers[o]);e.responseType&&(s.responseType=e.responseType),s.onload=()=>{if(s.status<400)if(e.responseType=="json"||e.responseType=="blob")i(s.response);else {let c=s.responseText;try{c=JSON.parse(c);}catch{}i(c);}else if(s.status===429){let c=s.getResponseHeader("Retry-After"),u=vt(c);u!==null?setTimeout(()=>{Ut(n,e,t).then(i,r);},u):r("Too many requests");}else {let c=s.status,u=["INVALID_CORS","INVALID_REQUEST","SERVICE_DISABLED","INVALID_PARAMETER","ERROR","EXISTS","NOT_EXISTS"],d=e.responseType=="blob"?s.response:s.responseText;try{d=JSON.parse(d);}catch{}if(typeof d=="string"){let f=d.split(":"),l=f.splice(0,1)[0].trim(),h=f.join(":").trim();r(new a(h||d,{code:u.includes(l)?l:"ERROR"}));}else if(typeof d=="object"&&d?.message){let f=d?.code||(c?c.toString():null)||"ERROR",l=d.message,h=d?.cause;typeof l=="string"&&(l=l.trim()),r(new a(l,{cause:h,code:f}));}else r(d);}},s.onerror=()=>r("Network error"),s.onabort=()=>r("Aborted"),s.ontimeout=()=>r("Timeout"),typeof t=="function"&&(s.onprogress=c=>{t({status:"download",progress:Oe(c.loaded,c.total),loaded:c.loaded,total:c.total,abort:()=>s.abort()});},s.upload&&(s.upload.onprogress=c=>{t({status:"upload",progress:Oe(c.loaded,c.total),loaded:c.loaded,total:c.total,abort:()=>s.abort()});})),s.send(e.body);})}function Rr(n){let{hashedParam:e,requestKeyWithStartKey:t,url:i,fetched:r}=n;if(!r?.startKey)return r;this.__startKeyHistory.hasOwnProperty(i)||(this.__startKeyHistory[i]={}),this.__startKeyHistory[i].hasOwnProperty(e)||(this.__startKeyHistory[i][e]=[]);let s=r.startKey==="end"?"end":JSON.stringify(r.startKey);return this.__startKeyHistory[i][e].includes(s)||this.__startKeyHistory[i][e].push(s),this.__cached_requests?.[i]||(this.__cached_requests[i]={}),this.__cached_requests[i][t]=r,Object.assign({startKeyHistory:this.__startKeyHistory[i][e]},r)}async function we(n,e){await this.__connection;let{record_id:t,service:i=this.service,progress:r}=e;if(!t)throw new a('"record_id" is required.',{code:"INVALID_PARAMETER"});if(xt&&n instanceof SubmitEvent&&(n=n.target),yr&&n instanceof HTMLFormElement&&(n=new FormData(n)),!ue||!(n instanceof FormData))throw new a('"fileList" should be a FormData or HTMLFormElement.',{code:"INVALID_PARAMETER"});let o={reserved_key:oe(),service:i,request:"post"};e?.record_id&&(o.id=e.record_id);let c,u=(R,p,A)=>new Promise((k,E)=>{c=new XMLHttpRequest,c.open("POST",R),c.onload=()=>{let P=c.responseText;try{P=JSON.parse(P);}catch{}if(c.status>=200&&c.status<300)k(P);else if(c.status===429){let S=c.getResponseHeader("Retry-After"),T=vt(S);T!==null?setTimeout(()=>{u(R,p,A).then(k,E);},T):E("Too many requests");}else E(P);},c.onerror=()=>E("Network error"),c.onabort=()=>E("Aborted"),c.ontimeout=()=>E("Timeout"),c.upload&&typeof A=="function"&&(c.upload.onprogress=A),c.send(p);});function d(R){let p="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";if(R===0)return p[0];let A="";for(;R>0;)A=p[R%62]+A,R=Math.floor(R/62);return A}let f=[],l=[],h=[];for(let[R,p]of n.entries()){if(!(p instanceof File))continue;let A=Object.assign({key:R+"/"+p.name,sizeKey:d(p.size),contentType:p.type||null},o),{fields:k=null,url:E,cdn:P}=await w.bind(this)("get-signed-url",A,{auth:!!this.__user});h.push(P);let S=new FormData;for(let T in k)S.append(T,k[T]);S.append("file",p);try{await u(E,S,typeof r=="function"?T=>r({status:"upload",progress:Oe(T.loaded,T.total),currentFile:p,completed:f,failed:l,loaded:T.loaded,total:T.total,abort:()=>c.abort()}):null),f.push(p);}catch{l.push(p);}}return {completed:f,failed:l,bin_endpoints:h}}var ye={};function y(n){let{preventMultipleCalls:e=false}=n||{};return function(t,i,r){let s=r.value;r.value=function(...o){let c=o[0],u=true,d=null,f="",l={},h=false;if(xt&&c instanceof SubmitEvent){c.preventDefault();let E=window.location.href;d=c.target;let P=new URL(d.action);f=P.href;let S=f?f.match(/(?<=\{).*?(?=\})/g):"";if(S)for(let T of S){if(!T)continue;let L=d.querySelector(`[name="${T}"]`);if(L)if(L.type==="file")for(let q=0;q<=L.files.length-1;q++)L.files[q]&&(l[T]||(l[T]=[]),l[T].push(new Promise((j,x)=>{let v=new FileReader;v.onload=function(){j(v.result);},v.readAsDataURL(L.files[q]),v.onerror=x;})));else f=f.replace(`{${T}}`,L.value);}d.getAttribute("action")===null?u=false:h=P.href===E;}let R=async E=>{if(f)for(let P in l)l[P].length&&(f=f.replace(`{${P}}`,(await Promise.all(l[P])).join(",")));return d&&u&&(window.sessionStorage.setItem(`${this.service}:${V.hash(f)}`,JSON.stringify(E)),h?window.location.replace(f):window.location.href=f),E},p,A=E=>{throw E instanceof a?E.name=i+"()":E=E instanceof Error?E:new a(E,{name:i+"()"}),E},k=async()=>{try{if(p=s.bind(this)(...o),p instanceof Promise){let E=await p;return R(E)}return R(p)}catch(E){throw A(E)}};if(e){let E=`${i}:${this?.__public_identifier||""}:${this?.service||""}:${this?.owner||""}`;return ye?.[E]||(ye[E]=k().finally(()=>{delete ye[E];})),ye[E]}return k()};}}async function Nt(){await this.__connection;let n=`${this.service}:${V.hash(window.location.href.split("?")[0])}`,e=window.sessionStorage.getItem(n);if(window.sessionStorage.removeItem(n),e!==null){try{e=JSON.parse(e);}catch{}return e}return null}var Ar=128,Ir=64,Tr=128,Sr=256,Pr="\u{10FFFF}",kr=/[\u0000-\u001F\u007F]|\u{10FFFF}/u,xr=/[\/!*#]/;function G(n,e,t={}){let{allowEmpty:i=false,maxLength:r,blockKeyDelimiters:s=false,disallowLeadingDollar:o=false,onlyAlphanumeric:c=false}=t;if(typeof n!="string")throw new a(`"${e}" should be type: <string>.`,{code:"INVALID_PARAMETER"});if(c&&/[^a-zA-Z0-9]/.test(n))throw new a(`"${e}" should only contain alphanumeric characters.`,{code:"INVALID_PARAMETER"});if(!i&&n.length===0)throw new a(`"${e}" is required.`,{code:"INVALID_PARAMETER"});if(r&&n.length>r)throw new a(`"${e}" should be <= ${r} characters.`,{code:"INVALID_PARAMETER"});if(kr.test(n)||n.includes(Pr))throw new a(`"${e}" cannot include control characters or unsupported sentinel characters.`,{code:"INVALID_PARAMETER"});if(s&&xr.test(n))throw new a(`"${e}" cannot include reserved delimiters: / ! * #`,{code:"INVALID_PARAMETER"});if(o&&n.startsWith("$"))throw new a(`"${e}" cannot start with "$".`,{code:"INVALID_PARAMETER"});return n}function Fe(n,e="table.name"){return G(n,e,{allowEmpty:false,maxLength:Ar,blockKeyDelimiters:true})}function Me(n,e="tag"){return G(n,e,{allowEmpty:false,maxLength:Ir,blockKeyDelimiters:true})}function de(n,e="index.name"){return G(n,e,{allowEmpty:false,maxLength:Tr,blockKeyDelimiters:true,disallowLeadingDollar:true})}function Ct(n,e="index.value"){return G(n,e,{allowEmpty:true,maxLength:Sr})}function Lt(n){if(!n.record_id&&!n.unique_id)return null;let e={};return n?.service&&(e.service=n.service),n?.owner&&(e.owner=n.owner),n?.record_id?e.record_id=G(n.record_id,"record_id",{allowEmpty:false,onlyAlphanumeric:true}):n?.unique_id&&(e.unique_id=n.unique_id),e}function Ve(n){if(n===void 0)return 0;if(typeof n=="number"){if(n>99||n<0)throw new a('"table.access_group" value should be within a range of 0 ~ 99.',{code:"INVALID_REQUEST"})}else if(typeof n=="string"){if(n={private:"private",public:0,authorized:1,admin:99}[n],n===void 0)throw new a('"table.access_group" is invalid.',{code:"INVALID_PARAMETER"})}else throw new a('"table.access_group" should be type: <number | string>.',{code:"INVALID_PARAMETER"});if(!this.__user&&n)throw new a("Unsigned users have no access to records with access group.",{code:"INVALID_REQUEST"});return n}var Ee=4503599627370496;function Re(n){if(typeof n=="number"){if(n>Ee||n<-Ee)throw new a(`Number value should be within range -${Ee} ~ +${Ee}`,{code:"INVALID_PARAMETER"});return n}if(typeof n=="boolean")return n;if(typeof n=="string")return Ct(n,"index.value");throw new a('"index.value" should be type: <number | boolean | string>.',{code:"INVALID_PARAMETER"})}function Ot(n,e){if(!e.index||!("value"in e.index))throw new a('"index.value" is required.',{code:"INVALID_PARAMETER"});if(e.index.name==="$record_id")throw new a(`Cannot do "index.range" on ${e.index.name}`,{code:"INVALID_PARAMETER"});if(typeof e.index.value!=typeof n)throw new a('"index.range" type should match the type of "index.value".',{code:"INVALID_PARAMETER"});return typeof n=="string"?Ct(n,"index.range"):n}var Ae={};async function ie(n,e){let t={user_id:"",record_id:"",updated:0,uploaded:0,readonly:false,table:{name:"",access_group:0,subscription:{is_subscription_record:false,upload_to_feed:false,notify_subscribers:false,feed_referencing_records:false,notify_referencing_records:false}},referenced_count:0,source:{referencing_limit:null,prevent_multiple_referencing:false,can_remove_referencing_records:false,only_granted_can_reference:false},ip:"",bin:{}},i=false;function r(o){let c=o=="**"?"private":parseInt(o);return c=c==0?"public":c==1?"authorized":c==99?"admin":c,c}let s={ip:o=>{let c=o.split("#"),u=c[0];c.length>1&&(t.unique_id=c[1]),u.slice(-1)==="R"?(t.readonly=true,u=u.slice(0,-1)):t.readonly=false,/^\d{1,3}-\d{1,3}-\d{1,3}-\d{1,3}$/.test(u)&&(u=u.split("-").join("."),i=true),t.ip=u;},rec:o=>{if(!o)return;t.record_id=o;let c=o.substring(0,o.length-9),u=B(c);t.uploaded=u;},usr:o=>{t.user_id=o;},tbl:o=>{if(o&&!t.table.name){let c=o.split("/");t.table.name=c[0],t.table.access_group=r(c[2]),c?.[3]&&(t.table.subscription.is_subscription_record=true);}},usr_tbl:o=>{let c=o.split("/");t.user_id||(t.user_id=c[0]),t.table.name||(t.table.name=c[1],t.table.access_group=r(c[3]),c?.[4]&&(t.table.subscription.is_subscription_record=true));},idx:o=>{if(!o)return;let c=o.split("!"),u=c.splice(0,1)[0],d=vr("!"+c.join("!"));t.index={name:u,value:d};},ref:o=>{o&&(t.reference=o.split("/")[0]);},tags:o=>{t.tags=o;},upd:o=>{t.updated=o;},acpt_mrf:o=>{t.source.prevent_multiple_referencing=!o;},ref_limt:o=>{t.source.referencing_limit=o;},rfd:o=>{t.referenced_count=o;},bin:async o=>{let c={},u=t?.reference||null;if(Array.isArray(o)){let d=await Promise.all(o.map(async f=>{try{let l=f.split("/").slice(3).join("/"),h=l.split("/");if(h.length<12)return null;let R=decodeURIComponent(h[h.length-1]),p=decodeURIComponent(h[10]),A=h[9],k=h[8],E=r(h[6]),P=f;if(E!=="public")try{P=await Ie.bind(this)(f,{dataType:"endpoint",_ref:u});}catch(T){console.error("Error getting signed url for private file:",T),P=f;}let S={access_group:E,filename:R,url:P,path:l,size:B(A),uploaded:B(k),getFile:(T,L)=>{let q={dataType:T||"download",progress:L,_ref:u,_update:S};return Ie.bind(this)(P,q)}};return {pathKey:p,obj:S}}catch{return null}}));for(let f of d)if(f){if(c[f.pathKey]){c[f.pathKey].push(f.obj);continue}c[f.pathKey]=[f.obj];}}t.bin=c;},prv_acs:o=>{for(let c in o)["notify_subscribers","upload_to_feed","feed_referencing_records","notify_referencing_records"].includes(c)?t.table.subscription[c]=o[c]:t.source[c]=o[c];},data:o=>{let c=o;o==="!D%{}"?c={}:o==="!L%[]"&&(c=[]),t.data=c;}};if(n.record_id)return n;for(let o in s)if(n.hasOwnProperty(o)){let c=s[o](n[o]);c instanceof Promise&&await c;}return i&&(t.user_id="anonymous:"+t.user_id),t}function vr(n){let e=n.substring(3);switch(n.substring(0,3)){case "!S%":return e;case "!N%":let i=e.split("."),r=Number(i[0])-4503599627370496;return i.length===1?r:parseFloat(r.toString()+"."+i[1]);case "!B%":return e==="1";case "!L%":case "!D%":try{return JSON.parse(e)}catch{throw new a("Value parse error.",{code:"PARSE_ERROR"})}default:return n}}async function Ft(n){let{endpoints:e}=n;if(typeof e=="string"&&(e=[e]),!Array.isArray(e))throw new a('"endpoints" should be type: array | string.',{code:"INVALID_PARAMETER"});let t=await w.bind(this)("del-files",{endpoints:e,storage:"records"},{auth:true,method:"post"}),i=[];for(let r in t)i.push(ie.bind(this)(t[r]));return Promise.all(i)}async function Ie(n,e){if(typeof n!="string")throw new a('"url" should be type: string.',{code:"INVALID_PARAMETER"});let t=n.split("?"),i=t.shift()||"",r=t.length?"?"+t.join("?"):"",s=g.Url(i);n=s+r;let o=false,c=s.split("/"),d=c[2].split("."),f=null;d.length===3&&d[1]==="skapi"&&(f=d[0],o=true);let l=c.slice(3),h=false;if(!o&&(l[0]==="auth"||l[0]==="publ"))try{g.UserId(l[2]),g.UserId(l[3]),h=l[0]=="auth",o=!0;}catch{throw new a("Invalid file url.",{code:"INVALID_PARAMETER"})}let R=f?null:l[1];if(e=g.Params(e,{expires:["number",()=>0],dataType:["base64","blob","endpoint","text","info",()=>"download"],progress:"function",_ref:[null,"string"],_update:E=>E}),e?.dataType==="info")return {url:n,filename:l[l.length-1],fileKey:l[l.length-2],access_group:l[6]==="**"?"private":l[6]==="01"?"authorized":l[6]==="00"?"public":parseInt(l[6]),uploader:l[3],record_id:l[4]==="records"?l[5]:"N/A",filesize:B(l[9]),uploaded:B(l[8])};let p=n.split("/").slice(-1)[0],A=e.expires;if(A){if(!o)throw new a("Expires option can only be used on skapi cdn endpoints.",{code:"INVALID_PARAMETER"});if(A<0)throw new a('"config.expires" should be > 0. (seconds)',{code:"INVALID_PARAMETER"});let E={request:f?"get-host":"get",id:f||l[5],key:n,expires:A};R&&(E.service=R),n=(await w.bind(this)("get-signed-url",E,{auth:true})).url;}else if(h){let E=Math.floor(Date.now()/1e3);if(!this.bearerToken&&(!this.session?.idToken?.payload?.exp||this.session.idToken.payload.exp<E)){this.log("getFile:requesting new token",null);try{await F.bind(this)().getSession({refreshToken:!0}),this.log("getFile:received new tokens",{exp:this.session?.idToken?.payload?.exp,currTime:E,expiresIn:this.session?.idToken?.payload?.exp-E,token:this.session?.accessToken?.jwtToken,refreshToken:this.session?.refreshToken?.token});}catch(L){throw this.log("getFile:new token error",L),new a("User login is required.",{code:"INVALID_REQUEST"})}}let P=this.bearerToken||this.session?.idToken?.jwtToken;if(!P||!this.user?.user_id)throw new a("User login is required.",{code:"INVALID_REQUEST"});n+=`${n.includes("?")?"&":"?"}t=${encodeURIComponent(P)}`;let S=l[6]==="**"?"**":parseInt(l[6]),T=this.user?.access_group??-1;if(this.user.user_id!==l[3]&&(S==="**"||T<S)){let L=l[5];if(this.__private_access_key[L]&&typeof this.__private_access_key[L]=="string")n+=`&p=${encodeURIComponent(this.__private_access_key[L])}`;else if(this.owner!==this.host)try{let q=await this.requestPrivateRecordAccessKey({record_id:L,reference_id:e?._ref});n+=`&p=${encodeURIComponent(q)}`;}catch{}}}if(e?.dataType==="endpoint")return e._update&&(e._update.url=n),n;if(e?.dataType==="download"){let E=document.createElement("a");return E.href=n,document.body.appendChild(E),E.setAttribute("download",p),E.target="_blank",E.click(),document.body.removeChild(E),null}return new Promise(async(E,P)=>{try{let S=await w.bind(this)(n,null,{method:"get",contentType:null,responseType:e?.dataType==="text"?"text":"blob",fetchOptions:{progress:e?.progress}},{ignoreService:!0});if(e?.dataType==="base64"){let T=new FileReader;T.onloadend=()=>E(T.result),T.readAsDataURL(S);}else E(S);}catch(S){P(S);}})}async function Mt(n,e=false){n=D(n,{ignoreEmpty:true}).data||{};let t="",i=Lt(n);if(i)n=i,t=n.record_id||n.unique_id,typeof t=="string"&&(typeof this.__private_access_key?.[t]=="string"&&(n.private_key=this.__private_access_key?.[t]||void 0),this.__my_unique_ids[t]&&(e?delete this.__my_unique_ids[t]:n.record_id=this.__my_unique_ids[t]));else {let r=await M.bind(this)(),s=n?.reference,o=false;typeof s=="object"&&Object.keys(s).length&&(s?.record_id||s?.unique_id?(t=s.record_id||s.unique_id,t&&typeof this.__private_access_key?.[t]=="string"&&(n.private_key=this.__private_access_key?.[t]||void 0),n.reference=t):s?.user_id&&(o=s.user_id===this.user?.user_id,n.reference=s.user_id)),typeof n?.table=="string"&&(n.table={name:n.table,access_group:0}),n.index&&n.index.hasOwnProperty("range")&&n.index.hasOwnProperty("condition")&&delete n.index.range;let c=u=>({table:{name:d=>Fe(d,"table.name"),access_group:Ve.bind(this),subscription:d=>g.UserId(d,'User ID in "subscription"')},reference:"string",index:{name:["$updated","$uploaded","$referenced_count","$user_id",d=>de(d,"index.name")],value:d=>{let f={$updated:"number",$uploaded:"number",$referenced_count:"number",$user_id:g.UserId};if(f.hasOwnProperty(u.index.name)){let l=f[u.index.name];if(typeof l=="function")return l(d);if(l!==typeof d)throw new a(`"index.value" should be type: ${l}.`,{code:"INVALID_PARAMETER"});return d}return typeof d=="string"&&!d?"":Re(d)},condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq"],range:d=>Ot(d,u)},tag:d=>{if(d==null)return d;if(typeof d=="string")return Me(d,"tag");throw new a('"tag" should be type: string.',{code:"INVALID_PARAMETER"})},private_key:"string"});n=g.Params(n||{},c(n),o||r?[]:["table"],{ignoreEmpty:true});}return {query:n,is_reference_fetch:t}}async function Vt(n,e){await this.__connection;let t=await Mt.bind(this)(n),i=t.is_reference_fetch,r=await w.bind(this)("get-records",t.query,{fetchOptions:e,auth:!!this.__user,method:this.__user?"post":"get"});i&&r?.reference_private_key&&typeof r.reference_private_key=="string"&&(this.__private_access_key[i]=r.reference_private_key);let s=[];for(let o in r.list)s.push(ie.bind(this)(r.list[o]));return r.list=await Promise.all(s),r}function $t(n){let e="",t=[],i=g.Params(n||{},{record_id:s=>G(s,"record_id",{allowEmpty:false,onlyAlphanumeric:true}),unique_id:"string",readonly:"boolean",table:{name:s=>Fe(s,"table.name"),subscription:{is_subscription_record:"boolean",upload_to_feed:"boolean",notify_subscribers:"boolean",feed_referencing_records:"boolean",notify_referencing_records:"boolean"},access_group:Ve.bind(this)},source:{referencing_limit:s=>{if(s===null)return null;if(typeof s=="number"){if(0>s)throw new a('"reference_limit" should be >= 0',{code:"INVALID_PARAMETER"});if(s>4503599627370546)throw new a('"reference_limit" should be <= 4503599627370546',{code:"INVALID_PARAMETER"});return s}throw new a('"reference_limit" should be type: <number | null>',{code:"INVALID_PARAMETER"})},prevent_multiple_referencing:"boolean",can_remove_referencing_records:"boolean",only_granted_can_reference:"boolean",allow_granted_to_grant_others:"boolean",referencing_index_restrictions:s=>{if(s===void 0)return;if(!s||Array.isArray(s)&&!s.length)return null;let o={name:u=>de(u,'"name" in "index_restrictions"'),value:u=>Re(u),condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne",()=>null],range:u=>{if(u!==null&&typeof s.value!=typeof u)throw new a('Index restriction "range" type should match the type of "value".',{code:"INVALID_PARAMETER"});if(!s.hasOwnProperty("value"))throw new a('Index restriction "value" is required.',{code:"INVALID_PARAMETER"});return u}};Array.isArray(s)||(s=[s]);let c=s.map(u=>g.Params(u,o,["name"]));if(c.length)for(let u of c)u.condition&&u.hasOwnProperty("range")&&delete u.range;return c}},reference:s=>{if(s===null)return {record_id:null};if(s){if(typeof s=="string")return e=s,this.__my_unique_ids[s]?this.__my_unique_ids[s]:s;if(typeof s!="object")throw new a('"reference" should be type: <string | object>.',{code:"INVALID_PARAMETER"});return g.Params(s,{unique_id:"string",record_id:o=>o==null?o:(e=o,typeof this.__private_access_key?.[o]=="string"&&(n.reference_private_key=this.__private_access_key[o]||void 0),G(o,"reference.record_id",{allowEmpty:false,onlyAlphanumeric:true}))})}},index:{name:s=>de(s,"index.name"),value:s=>Re(s)},tags:s=>{if(s==null)return s;if(typeof s=="string"&&(s=s.split(",").map(o=>o.trim())),!Array.isArray(s))throw new a('"tag" should be type: <string | string[]>.',{code:"INVALID_PARAMETER"});return s.map(o=>Me(o,"tag"))},remove_bin:s=>{if(!s)return null;let o=[];if(Array.isArray(s))for(let c of s)if(typeof c=="string")o.push(decodeURIComponent(c.split("?")[0]));else if(c.url&&c.size&&c.filename){let d=c.url.split("/").slice(0,3).join("/")+"/"+c.path;o.push(d);}else throw new a('"remove_bin" should be type: <string[] | BinaryFile[] | null>',{code:"INVALID_PARAMETER"});else throw new a('"remove_bin" should be type: <string[] | BinaryFile[] | null>',{code:"INVALID_PARAMETER"});return o},progress:"function",data:s=>s},[],{precall:s=>{let o=s?.data||{};if(!o?.record_id&&!o.table)throw new a('"table.name" is required.',{code:"INVALID_PARAMETER"});typeof o.table=="string"&&(o.table={name:o.table,access_group:0}),s.files&&(t=s.files);}}),r=n.progress||null;if(delete i.progress,!this.__user){let s=!!(i.table?.subscription?.is_subscription_record||i.table?.subscription?.upload_to_feed||i.table?.subscription?.notify_subscribers||i.table?.subscription?.feed_referencing_records||i.table?.subscription?.notify_referencing_records);if(i.record_id)throw new a("Public users cannot update existing records.",{code:"INVALID_REQUEST"});if(i.table.access_group!=="public"&&i.table.access_group!==0)throw new a("Public users can only post records to public tables.",{code:"INVALID_REQUEST"});if(s)throw new a("Public users cannot post subscription records.",{code:"INVALID_REQUEST"});if(i.remove_bin)throw new a("Public users cannot remove files from records.",{code:"INVALID_REQUEST"});if(i.unique_id)throw new a("Public users cannot set unique_id for records.",{code:"INVALID_REQUEST"})}return {config:i,progress:r,is_reference_post:e,files:t}}async function qt(n){if(await this.__connection,!Array.isArray(n)||!n.length)throw new a('"params" should be a non-empty array.',{code:"INVALID_PARAMETER"});!this.__user;let t=[],i,r,s=null,c={_is_bulk_:n.map((h,R)=>{if(!h||typeof h!="object"||Array.isArray(h))throw new a(`"params[${R}]" should be type: <object>.`,{code:"INVALID_PARAMETER"});let p=$t.bind(this)(h),A=p.config;if(p.is_reference_post&&t.push(p.is_reference_post),typeof A.progress=="function"&&s===null&&(s=A.progress),A.service!==void 0){if(i===void 0)i=A.service;else if(i!==A.service)throw new a('All bulk params should share the same "service" value.',{code:"INVALID_PARAMETER"})}if(A.owner!==void 0){if(r===void 0)r=A.owner;else if(r!==A.owner)throw new a('All bulk params should share the same "owner" value.',{code:"INVALID_PARAMETER"})}return delete A.progress,delete A.service,delete A.owner,A}),service:"",owner:""};i!==void 0&&(c.service=i),r!==void 0&&(c.owner=r);let u={auth:!!this.__user,method:"post"},d={};Object.keys(d).length&&Object.assign(u,{fetchOptions:d});let f=await w.bind(this)("post-record",c,u),l=await Promise.all(f.map(h=>ie.bind(this)(h,"called from postRecord")));for(let h=0;h<f.length;h++){let R=f[h],p=l[h];if(typeof R?.reference_private_key=="string")for(let A of t)this.__private_access_key[A]=R.reference_private_key;p?.unique_id&&(this.__my_unique_ids[p.unique_id]=p.record_id);}return l}async function jt(n,e,t){if(await this.__connection,!e)throw new a('"config" argument is required.',{code:"INVALID_PARAMETER"});let i=$t.bind(this)(e),r=i.config,s=i.progress,o=i.is_reference_post,c={auth:!!this.__user,method:"post"},u=[],d=D(n);t&&Array.isArray(t)&&t.length&&(u=u.concat(t)),d.files&&Array.isArray(d.files)&&d.files.length&&(u=u.concat(d.files));let f=null;f=Object.assign({data:d.data},r);let l={};typeof s=="function"&&(l.progress=s),Object.keys(l).length&&Object.assign(c,{fetchOptions:l});let h=await w.bind(this)("post-record",f,c);if($()&&u.length){let p=new FormData;for(let E of u)p.append(E.name,E.file,E.file.name);let A={record_id:h.rec,progress:s};r.hasOwnProperty("service")&&(A.service=r.service);let{bin_endpoints:k}=await we.bind(this)(p,A);h.bin?h.bin.push(...k):h.bin=k;}o&&typeof h?.reference_private_key=="string"&&(this.__private_access_key[o]=h.reference_private_key);let R=await ie.bind(this)(h,"called from postRecord");return R.unique_id&&(this.__my_unique_ids[R.unique_id]=R.record_id,$()&&window.sessionStorage.setItem(`${this.service}:uniqueids`,JSON.stringify(this.__my_unique_ids))),R}async function Bt(n,e){let t=await w.bind(this)("get-table",g.Params(n||{},{table:"string",condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}),Object.assign({auth:!!this.__user},{fetchOptions:e})),i={cnt_rec:"number_of_records",tbl:"table",srvc:"service"};if(Array.isArray(t?.list))for(let r of t.list)for(let s in i)r.hasOwnProperty(s)&&(r[i[s]]=r[s],delete r[s]);return t}async function Kt(n,e){if(!n?.table)throw new a('"table" is required.',{code:"INVALID_PARAMETER"});let t=g.Params(n||{},{table:"string",index:s=>de(s,"index.name"),order:{by:["average_number","total_number","number_count","average_bool","total_bool","bool_count","string_count","index_name","number_of_records"],value:["string","number","boolean"],condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}},["table"]);if(t.hasOwnProperty("order")){if(!t.order?.by)throw new a('"order.by" is required.',{code:"INVALID_PARAMETER"});if(t.order.hasOwnProperty("condition")&&!t.order.hasOwnProperty("value"))throw new a('"value" is required for "condition".',{code:"INVALID_PARAMETER"});if(t.hasOwnProperty("index")&&t.index.substring(t.index.length-1)!==".")throw new a('"index" should be a parent index name of the compound index when using "order.by"',{code:"INVALID_PARAMETER"})}let i=await w.bind(this)("get-index",t,Object.assign({auth:!!this.__user},{fetchOptions:e})),r={cnt_bool:"boolean_count",cnt_numb:"number_count",totl_numb:"total_number",totl_bool:"total_bool",avrg_numb:"average_number",avrg_bool:"average_bool",cnt_str:"string_count"};return Array.isArray(i?.list)&&(i.list=i.list.map(s=>{let o=s.idx.split("/"),c={table:o[1],index:o[2],number_of_records:s.cnt_rec};for(let u in r)Object.prototype.hasOwnProperty.call(s,u)&&(c[r[u]]=s[u]);return c})),i}async function Qt(n,e){let t=await w.bind(this)("get-tag",g.Params(n||{},{table:"string",tag:"string",condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}),Object.assign({auth:!!this.__user},{fetchOptions:e}));return Array.isArray(t?.list)&&(t.list=t.list.map(i=>{let r=i.tag.split("/");return {table:r[1],tag:r[0],number_of_records:i.cnt_rec}})),t}async function Wt(n,e){let t=await w.bind(this)("get-uniqueid",g.Params(n||{},{unique_id:"string",condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}),Object.assign({auth:!!this.__user},{fetchOptions:e}));if(Array.isArray(t?.list))for(let i in t.list){let r=t.list[i];t.list[i]={unique_id:r.unq,record_id:r.rec};}return t}async function Ht(n,e){await this.__connection;let t=await Mt.bind(this)(n,true),i=t.is_reference_fetch,r=await w.bind(this)("del-records",t.query,{auth:true,fetchOptions:e});return i&&typeof r?.reference_private_key=="string"&&(this.__private_access_key[i]=r.reference_private_key),r?.message||r}function Jt(n){return Zt.bind(this)({record_id:n.record_id,user_id:n.user_id,execute:"add"})}function zt(n){return Zt.bind(this)({record_id:n.record_id,user_id:n.user_id||null,execute:"remove"})}async function Gt(n,e){let t={record_id:n.record_id||void 0,user_id:n.user_id||void 0,execute:"list"};if(!t.record_id&&!t.user_id)throw new a("Either record_id or user_id must be provided.",{code:"INVALID_PARAMETER"});if(t.user_id)if(typeof t.user_id=="string")g.UserId(t.user_id),t.user_id=[t.user_id];else if(Array.isArray(t.user_id))for(let s of t.user_id)g.UserId(s);else throw new a("user_id should be type: <string | string[]>",{code:"INVALID_PARAMETER"});let i=s=>(s.rec_usr?(s.record_id=s.rec_usr.split("/")[0],s.user_id=s.rec_usr.split("/")[1]):s.usr_rec&&(s.user_id=s.usr_rec.split("/")[0],s.record_id=s.usr_rec.split("/")[1]),s),r=await w.bind(this)("grant-private-access",t,{auth:true,fetchOptions:e});return r.list=r.list.map(i),r}function Xt(n){let e=n.record_id,t=n.reference_id||void 0;if(!e)throw new a("Record ID is required.",{code:"INVALID_PARAMETER"});if(typeof e!="string")throw new a("Record ID should be type: <string | string[]>",{code:"INVALID_PARAMETER"});if(t&&typeof t!="string")throw new a("Reference ID should be type: <string>",{code:"INVALID_PARAMETER"});if(typeof this.__private_access_key[e]=="string")return Promise.resolve(this.__private_access_key[e]);if(Ae[e])return Ae[e];let i=w.bind(this)("request-private-access-key",{record_id:e,reference_id:t},{auth:true}).then(r=>{let s=typeof r=="string"?r:r?.private_key;if(typeof s!="string")throw new a("Invalid private access key response.",{code:"ERROR"});return this.__private_access_key[e]=s,s}).finally(()=>{delete Ae[e];});return Ae[e]=i,i}function Zt(n){n.execute;let t=g.Params(n,{record_id:"string",user_id:i=>{if(!i)throw new a("User ID is required.",{code:"INVALID_PARAMETER"});let r=i;if(typeof r=="string"&&(r=[r]),r.length>100)throw new a("Cannot process more than 100 users at once.",{code:"INVALID_REQUEST"});for(let s of r)g.UserId(s,'User ID in "user_id"');return r},execute:["add","remove"]},["execute","record_id","user_id"]);return t.user_id||(t.user_id=null),w.bind(this)("grant-private-access",t,{auth:true})}var I={},C={},K={},H={},W={},Te={},Se={};function Yt(n,e,t){n[e]||(n[e]=[]),n[e].push(t);}async function Pe(n,e,t){let i=[];if(n[e]){for(let r of n[e])if(r){let s=t(r);s instanceof Promise&&(s=await s),i.push(s);}delete n[e];}return i}async function qe(n,e){if(!this?.session?.accessToken?.jwtToken)throw new a("Access token is required.",{code:"INVALID_PARAMETER"});let t=await this.__socket;async function i(r,s,o){this.log("answerSdpOffer from",s),await I[s].setRemoteDescription(new RTCSessionDescription(r));let c=await I[s].createAnswer();await I[s].setLocalDescription(c),o.send(JSON.stringify({action:"rtc",uid:s,content:{sdpanswer:c},token:this.session.accessToken.jwtToken}));}I?.[e]?n?(await Pe(Se,e,r=>i.bind(this)(r,e,t)),await i.bind(this)(n,e,t)):await Pe(Se,e,r=>i.bind(this)(r,e,t)):n&&Yt(Se,e,n);}async function je(n,e){if(this.log("receiveIceCandidate",n),I?.[e]&&I[e]?.remoteDescription&&I[e]?.remoteDescription?.type){if(!n)return Pe(Te,e,t=>I[e].addIceCandidate(t));await Pe(Te,e,t=>I[e].addIceCandidate(t)),await I[e].addIceCandidate(n);}else Yt(Te,e,n);}async function Q(n){if(typeof window>"u"||window._runningInNodeJS)throw new a("WebRTC is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});g.Params(n,{cid:s=>{if(typeof s!="string")throw new a('"cid" should be type: <string>.',{code:"INVALID_PARAMETER"});if(s&&s.slice(0,4)!=="cid:")throw new a('"cid" should be a valid connection id.',{code:"INVALID_PARAMETER"});return s},close:"boolean"});let e=await this.__socket,{cid:t,close_all:i=false}=n||{};if(!i&&!t)throw new a('"cid" is required.',{code:"INVALID_PARAMETER"});let r=s=>{if(!s)throw new a('"cid" is required.',{code:"INVALID_PARAMETER"});if(delete Se[s],delete Te[s],C[s]&&Object.values(C[s]).forEach(o=>{o.readyState!=="closed"&&o.close();}),delete C[s],I?.[s]){I[s].connectionState!=="closed"&&(I[s].close(),e.send(JSON.stringify({action:"rtc",uid:s,content:{hungup:this.user.user_id},token:this.session.accessToken.jwtToken})));let o={type:"connectionstatechange",target:I[s],timestamp:new Date().toISOString(),state:I[s].connectionState,iceState:I[s].iceConnectionState,signalingState:I[s].signalingState};W[s]&&W[s](o),this.log("closeRTC",o);}delete W[s],delete H[s],delete K[s],delete I[s];};if(i)for(let s in I)r(s);else r(t);this.log("Cleaning up media stream..."),this.__mediaStream&&(this.__mediaStream.getTracks().forEach(s=>{s.stop();}),this.__mediaStream=null);}async function en(n){if(n instanceof MediaStream)return n;if(!n.video&&!n.audio){let e=new MediaStream,t=document.createElement("canvas");t.width=1,t.height=1;let r=t.captureStream().getVideoTracks()[0];return e.addTrack(r),e}return window.navigator.mediaDevices.getUserMedia(n)}async function tn(n,e){if(typeof window>"u"||window._runningInNodeJS)throw new a("WebRTC is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(typeof e!="function")throw new a("Callback is required.",{code:"INVALID_PARAMETER"});if(!this?.session?.accessToken?.jwtToken)throw new a("Access token is required.",{code:"INVALID_PARAMETER"});n=g.Params(n,{cid:o=>{if(typeof o!="string")throw new a('"cid" should be type: <string>.',{code:"INVALID_PARAMETER"});if(o&&o.slice(0,4)!=="cid:")throw new a('"cid" should be a valid connection id.',{code:"INVALID_PARAMETER"});return o},ice:["string",()=>"stun:stun.skapi.com:3468"],media:o=>o,channels:["text-chat","file-transfer","video-chat","voice-chat","gaming",{ordered:"boolean",maxPacketLifeTime:"number",maxRetransmits:"number",protocol:"string"},()=>[{ordered:true,maxPacketLifeTime:10,protocol:"default"}]]},["cid"]);let{cid:t,ice:i}=n;if(!(n?.media instanceof MediaStream)&&(n?.media?.video||n?.media?.audio)&&window.location.hostname!=="localhost"&&window.location.protocol!=="https:")throw new a("Media stream is only supported on either localhost or https.",{code:"INVALID_REQUEST"});let r=this.__socket?await this.__socket:this.__socket;if(!r)throw new a("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});if(r.readyState!==1)throw new a("Realtime connection is not ready.",{code:"INVALID_REQUEST"});let s={iceServers:[{urls:i}]};I?.[t]||(I[t]=new RTCPeerConnection(s)),n?.media&&(this.__mediaStream=await en(n.media),this.__mediaStream.getTracks().forEach(o=>{I[t].addTrack(o,this.__mediaStream);})),W[t]=e,C[t]||(C[t]={});for(let o=0;o<n.channels.length;o++){let c=n.channels[o];if(typeof c=="string")switch(c){case "text-chat":c={ordered:true,maxRetransmits:10,protocol:"text-chat"};break;case "file-transfer":c={ordered:false,maxPacketLifeTime:3e3,protocol:"file-transfer"};break;case "video-chat":c={ordered:true,maxRetransmits:10,protocol:"video-chat"};break;case "voice-chat":c={ordered:true,maxRetransmits:10,protocol:"voice-chat"};break;case "gaming":c={ordered:false,maxPacketLifeTime:100,protocol:"gaming"};break;default:c={ordered:true,maxRetransmits:10,protocol:"default"};break}let u=c.protocol||"default";if(Object.keys(C[t]).includes(u))throw new a(`Data channel with the protocol "${u}" already exists.`,{code:"INVALID_REQUEST"});let d=I[t].createDataChannel(u,c);C[t][u]=d;}for(let o in C[t]){let c=C[t][o];sn.bind(this)(t,c);}return rn.bind(this)(t,["onnegotiationneeded"]),await $e.bind(this)(t),{hangup:()=>K[t]&&K[t](false),connection:new Promise(o=>{K[t]=(c=>{if(this.log("receiver picked up the call",t),!c)return Q.bind(this)({cid:t}),null;I[t].onnegotiationneeded=()=>{this.log("onnegotiationneeded",`sending offer to "${t}".`),$e.bind(this)(t),W[t]&&W[t]({type:"negotiationneeded",target:I[t],timestamp:new Date().toISOString(),signalingState:I[t].signalingState,connectionState:I[t].iceConnectionState,gatheringState:I[t].iceGatheringState});},o({target:I[t],channels:C[t],hangup:()=>Q.bind(this)({cid:t}),media:this.__mediaStream});}).bind(this);})}}function nn(n){return async(e,t)=>{e=e||{},e=D(e).data;let i=n.sender_cid,r=await this.__socket;if(!H[i])return null;if(typeof t!="function")throw new a("Callback is required.",{code:"INVALID_PARAMETER"});if(!(e?.media instanceof MediaStream)&&(e?.media?.video||e?.media?.audio)&&window.location.hostname!=="localhost"&&window.location.protocol!=="https:")throw new a("Media stream is only supported on either localhost or https.",{code:"INVALID_REQUEST"});let{ice:s="stun:stun.skapi.com:3468"}=e;return I?.[i]||(I[i]=new RTCPeerConnection({iceServers:[{urls:s}]})),e?.media&&(this.__mediaStream=await en(e.media),this.__mediaStream.getTracks().forEach(o=>{I[i].addTrack(o,this.__mediaStream);})),delete H[i],W[i]=t,C[i]||(C[i]={}),I[i].ondatachannel=o=>{this.log("ondatachannel",`received data channel "${o.channel.label}".`);let c=o.channel;C[i][c.label]=c,sn.bind(this)(i,c);},rn.bind(this)(i,["onnegotiationneeded"]),await qe.bind(this)(null,i),await je.bind(this)(null,i),r.send(JSON.stringify({action:"rtc",uid:i,content:{pickup:this.user.user_id},token:this.session.accessToken.jwtToken})),{target:I[i],channels:C[i],hangup:()=>Q.bind(this)({cid:i}),media:this.__mediaStream}}}async function $e(n){if(!this?.session?.accessToken?.jwtToken)throw new a("Access token is required.",{code:"INVALID_PARAMETER"});this.log("sendOffer",n);let e=await this.__socket,t=await I[n].createOffer();await I[n].setLocalDescription(t);let i=I[n].localDescription;this.log("rtcSdpOffer to",i),e.send(JSON.stringify({action:"rtc",uid:n,content:{sdpoffer:i},token:this.session.accessToken.jwtToken}));}async function Dr(n,e){if(!this?.session?.accessToken?.jwtToken)throw new a("Access token is required.",{code:"INVALID_PARAMETER"});this.log("sendIceCandidate to",e);let t=await this.__socket;if(!n.candidate){this.log("candidate-end","all ice candidates have been sent");return}let i=W[e]||(()=>{}),r=n.candidate;this.log("ice gathering state set to",I[e].iceGatheringState),i({type:"icecandidate",target:I[e],timestamp:new Date().toISOString(),candidate:n.candidate.candidate,sdpMid:n.candidate.sdpMid,sdpMLineIndex:n.candidate.sdpMLineIndex,usernameFragment:n.candidate.usernameFragment,protocol:n.candidate.protocol,gatheringState:I[e].iceGatheringState,connectionState:I[e].iceConnectionState}),t.send(JSON.stringify({action:"rtc",uid:e,content:{candidate:r},token:this.session.accessToken.jwtToken}));}function rn(n,e){let t=new Set(e),i=W[n]||(o=>{}),r=I[n],s={ontrack:o=>{i({type:"track",target:r,timeStamp:o.timeStamp,streams:o.streams,track:o.track});},onicecandidate:o=>{Dr.bind(this)(o,n),o.candidate?i({type:"icecandidate",target:r,timestamp:new Date().toISOString(),candidate:o.candidate.candidate,sdpMid:o.candidate.sdpMid,sdpMLineIndex:o.candidate.sdpMLineIndex,usernameFragment:o.candidate.usernameFragment,protocol:o.candidate.protocol,gatheringState:r.iceGatheringState,connectionState:r.iceConnectionState}):i({type:"icecandidateend",target:r,timestamp:new Date().toISOString()});},onicecandidateerror:o=>{i({type:"icecandidateerror",target:r,timestamp:new Date().toISOString(),errorCode:o.errorCode,errorText:o.errorText,url:o.url,hostCandidate:o.hostCandidate,gatheringState:r.iceGatheringState,connectionState:r.iceConnectionState});},oniceconnectionstatechange:()=>{i({type:"iceconnectionstatechange",target:r,timestamp:new Date().toISOString(),state:r.iceConnectionState,gatheringState:r.iceGatheringState,signalingState:r.signalingState});},onicegatheringstatechange:()=>{i({type:"icegatheringstatechange",target:r,timestamp:new Date().toISOString(),state:r.iceGatheringState,connectionState:r.iceConnectionState,signalingState:r.signalingState});},onsignalingstatechange:()=>{i({type:"signalingstatechange",target:r,timestamp:new Date().toISOString(),state:r.signalingState,connectionState:r.iceConnectionState,gatheringState:r.iceGatheringState});},onnegotiationneeded:()=>{$e.bind(this)(n),i({type:"negotiationneeded",target:r,timestamp:new Date().toISOString(),signalingState:r.signalingState,connectionState:r.iceConnectionState,gatheringState:r.iceGatheringState});},onconnectionstatechange:()=>{i({type:"connectionstatechange",target:r,timestamp:new Date().toISOString(),state:r.connectionState,iceState:r.iceConnectionState,signalingState:r.signalingState});let o=r.connectionState;(o==="disconnected"||o==="failed"||o==="closed")&&Q.bind(this)({cid:n});}};for(let[o,c]of Object.entries(s))t.has(o)||(r[o]=c);}function sn(n,e,t){let i=new Set(t),r=W[n]||(o=>{}),s={onmessage:o=>{let c={type:o.type,target:e,timeStamp:o.timeStamp,data:o.data,lastEventId:o.lastEventId,origin:o.origin,readyState:e.readyState,bufferedAmount:e.bufferedAmount};this.log(`${e.label}: message`,o.data),r(c);},onerror:o=>{let c={type:o.type,target:e,timeStamp:o.timeStamp,error:o.error.message,errorCode:o.error.errorDetail,readyState:e.readyState,label:e.label};this.log(`${e.label}: error`,o.error.message),r(c);},onclose:o=>{let c={type:o.type,target:e,timeStamp:o.timeStamp,readyState:e.readyState,label:e.label,id:e.id};this.log(`${e.label}: closed`,null),r(c),C[n]&&(delete C[n][e.label],Object.keys(C[n]).length===0&&Q.bind(this)({cid:n}));},onbufferedamountlow:o=>{let c={target:e,bufferedAmount:e.bufferedAmount,bufferedAmountLowThreshold:e.bufferedAmountLowThreshold,type:o.type,timeStamp:o.timeStamp};this.log(`${e.label}: bufferedamountlow`,e.bufferedAmount),r(c);},onopen:o=>{this.log("dataChannel",`data channel: "${e.label}" is open and ready to send messages.`);let c={type:o.type,target:e,timeStamp:o.timeStamp,readyState:e.readyState,label:e.label,id:e.id,ordered:e.ordered,maxRetransmits:e.maxRetransmits,protocol:e.protocol};r(c);}};for(let[o,c]of Object.entries(s))i.has(o)||(e[o]=c);}var Z,X=null,ge=true,se=0;async function Ur(){if(typeof window>"u"||window._runningInNodeJS)throw new a("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.getProfile(),!this.session)throw new a("No access.",{code:"INVALID_REQUEST"});let n=await this.record_endpoint;return new WebSocket(n.websocket_private+"?token="+this.session.accessToken.jwtToken)}var Be=null;async function on(){if(typeof window>"u"||window._runningInNodeJS)throw new a("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});ge=true;let n=this.__socket?await this.__socket:this.__socket;Q.bind(this)({close_all:true}),Z&&Ke.bind(this)({group:null}),se=0,X&&(X.terminate(),X=null);try{n&&n.close();}catch{}return window.removeEventListener("visibilitychange",Be),this.__socket=null,null}async function ke(n,e=50,t){if(typeof window>"u"||window._runningInNodeJS)throw new a("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(typeof n!="function")throw new a("Callback must be a function.",{code:"INVALID_REQUEST"});if(t==="reconnect"){if(this.__socket instanceof Promise){let i=await this.__socket;if(i.readyState!==WebSocket.CLOSED&&i.readyState!==WebSocket.CLOSING)return this.__socket}}else if(ge&&(Be=()=>{!document.hidden&&!ge&&ke.bind(this)(n,0,"reconnect");},this.__socket instanceof Promise))return this.__socket;X&&(X.terminate(),X=null),this.__socket=new Promise(async i=>{await ne.bind(this)(),setTimeout(async()=>{let r=await Ur.bind(this)();r.onopen=()=>{ge=false,se=0,t!=="reconnect"&&window.addEventListener("visibilitychange",Be),this.log("realtime onopen","Connected to WebSocket server."),n({type:"success",message:"Connected to WebSocket server."}),Z&&r.send(JSON.stringify({action:"joinRoom",rid:Z,token:this.session.accessToken.jwtToken}));let s=`
206
+ var Nn=Object.defineProperty;var Cn=Object.getOwnPropertyDescriptor;var ee=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var w=(n,e,t,i)=>{for(var r=Cn(e,t),s=n.length-1,o;s>=0;s--)(o=n[s])&&(r=(o(e,t,r))||r);return r&&Nn(e,t,r),r};var J=typeof globalThis<"u"?globalThis:void 0,he=J?.window;function Ln(n){if(Buffer)return Buffer.from(n).toString("base64");let e="",t=new Uint8Array(n),i=32768;for(let r=0;r<t.length;r+=i){let s=t.subarray(r,r+i);e+=String.fromCharCode.apply(null,Array.from(s));}if(typeof btoa=="function")return btoa(e);throw new Error("No base64 encoder available in this environment.")}if(he)he.global=he,he.global._runningInNodeJS=false;else if(J&&(J.global=J,typeof J.window>"u")){class n{constructor(){this.result=null;this.error=null;this.onload=null;this.onloadend=null;this.onerror=null;}readAsDataURL(i){i.arrayBuffer().then(r=>{let s=Ln(r),o=i.type||"application/octet-stream";this.result=`data:${o};base64,${s}`,this.onload&&this.onload({target:this}),this.onloadend&&this.onloadend({target:this});}).catch(r=>{this.error=r,this.onerror&&this.onerror({target:this});});}readAsArrayBuffer(i){i.arrayBuffer().then(r=>{this.result=r,this.onload&&this.onload({target:this}),this.onloadend&&this.onloadend({target:this});}).catch(r=>{this.error=r,this.onerror&&this.onerror({target:this});});}readAsText(i,r="utf-8"){i.text().then(s=>{this.result=s,this.onload&&this.onload({target:this}),this.onloadend&&this.onloadend({target:this});}).catch(s=>{this.error=s,this.onerror&&this.onerror({target:this});});}}J.FileReader=n;class e{constructor(){this.status=0;this.statusText="";this.readyState=0;this.responseText="";this.response=null;this.responseType="";this.responseURL="";this.timeout=0;this.withCredentials=false;this.onload=null;this.onerror=null;this.onabort=null;this.ontimeout=null;this.onprogress=null;this.onreadystatechange=null;this.upload={onprogress:null};this._method="GET";this._url="";this._headers={};this._aborted=false;}open(i,r){this._method=i,this._url=r,this.readyState=1;}setRequestHeader(i,r){this._headers[i]=r;}getResponseHeader(i){return null}abort(){this._aborted=true,this.onabort&&this.onabort({});}send(i){if(this._aborted)return;let r={method:this._method,headers:this._headers};i&&this._method!=="GET"&&this._method!=="HEAD"&&(r.body=i),fetch(this._url,r).then(async s=>{if(!this._aborted){if(this.status=s.status,this.statusText=s.statusText,this.responseURL=s.url,this.readyState=4,this.responseType==="blob")this.response=await s.blob();else if(this.responseType==="json")try{this.response=await s.json();}catch{this.response=null;}else this.responseType==="arraybuffer"?this.response=await s.arrayBuffer():(this.responseText=await s.text(),this.response=this.responseText);this.onload&&this.onload({});}}).catch(s=>{this._aborted||this.onerror&&this.onerror(s);});}}J.XMLHttpRequest=e,J.window={_runningInNodeJS:true,alert:t=>console.error("[Alert]",t),sessionStorage:{getItem:t=>null,setItem:(t,i)=>{},removeItem:t=>{}},localStorage:{getItem:t=>{let i=ee("fs"),r=ee("path");try{let s=r.resolve(process.cwd(),"states","localStorage",`${t}.skapi`);return i.existsSync(s)?i.readFileSync(s,"utf8"):null}catch{return null}},setItem:(t,i)=>{let r=ee("fs"),s=ee("path");try{let o=s.resolve(process.cwd(),"states","localStorage");r.existsSync(o)||r.mkdirSync(o,{recursive:!0});let c=s.resolve(o,`${t}.skapi`);r.writeFileSync(c,i,"utf8");}catch{}},removeItem:t=>{let i=ee("fs"),r=ee("path");try{let s=r.resolve(process.cwd(),"states","localStorage",`${t}.skapi`);i.existsSync(s)&&i.unlinkSync(s);}catch{}}},location:{href:"",origin:"",hostname:"",protocol:"",replace:t=>{}},navigator:{userAgent:`nodejs/${J?.process?.versions?.node||"unknown"}`,mediaDevices:{getUserMedia:async t=>{throw new Error("getUserMedia is not supported in Node.js environment.")}}},addEventListener:()=>{},removeEventListener:()=>{}};}var a=class extends Error{constructor(e,t){if(Array.isArray(e)&&e.length<=2){let i=e[1];if(e.length>2)for(let r=2;r<e.length&&typeof e[r]=="string";r++)i+=e[r];super((i||"Something went wrong.").trim()),this.name=t?.name||"SKAPI",this.code=t?.code||e[0]||"ERROR",t?.cause&&(this.cause=t.cause);}else super((e?.message||(typeof e=="string"?e:"Something went wrong.")).trim()),typeof e=="string"?(this.name=t?.name||"SKAPI",this.code=t?.code||"ERROR",t?.cause&&(this.cause=t.cause)):e instanceof Error?(this.cause=e,this.name=e.name,e.hasOwnProperty("code")&&(this.code=e.code)):typeof e=="object"&&e?.code&&e?.message&&(this.name=t?.name||"SKAPI",this.code=t?.code||"ERROR",this.cause=e?.cause);}};var z="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",xe=BigInt(z.length),On=2*1024*1024,Fn=["aud","cognito:username","event_id","exp","iat","iss","jti","origin_jti","secret_key","token_use"],Ke={auth_time:"log",sub:"user_id"},Mn=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f","g","h","i","j","k","l"],ze=["us31","us72","ap51","ap22","ap41","eu71","ap21","us32","us71","af51","ap31","ap43","ap23","ap42","ca01","eu01","eu72","eu51","eu73","eu11","me51","sa31"],Qe=typeof TextEncoder<"u"?new TextEncoder:null;function Vn(){if(typeof globalThis<"u")return globalThis.Buffer}function $n(n){if(Qe)return Qe.encode(n);let e=unescape(encodeURIComponent(n)),t=new Uint8Array(e.length);for(let i=0;i<e.length;i++)t[i]=e.charCodeAt(i);return t}function qn(n){if(n instanceof Uint8Array)return n;if(typeof n=="string")return $n(n);if(typeof ArrayBuffer<"u"&&n instanceof ArrayBuffer)return new Uint8Array(n);if(typeof ArrayBuffer<"u"&&ArrayBuffer.isView(n))return new Uint8Array(n.buffer,n.byteOffset,n.byteLength);if(Array.isArray(n))return Uint8Array.from(n);let e=Vn();if(e)return new Uint8Array(e.from(n));throw new Error("No byte conversion available in this environment.")}var m=class m{static hash(e){typeof e!="string"&&(console.warn("coercing non-string value to empty string"),e="");let t=m.sb(e),i=1732584193,r=-271733879,s=-1732584194,o=271733878,c,l,d,h;for(let u=0;u<t.length;u+=16)c=i,l=r,d=s,h=o,i=m.ff(i,r,s,o,t[u],7,-680876936),o=m.ff(o,i,r,s,t[u+1],12,-389564586),s=m.ff(s,o,i,r,t[u+2],17,606105819),r=m.ff(r,s,o,i,t[u+3],22,-1044525330),i=m.ff(i,r,s,o,t[u+4],7,-176418897),o=m.ff(o,i,r,s,t[u+5],12,1200080426),s=m.ff(s,o,i,r,t[u+6],17,-1473231341),r=m.ff(r,s,o,i,t[u+7],22,-45705983),i=m.ff(i,r,s,o,t[u+8],7,1770035416),o=m.ff(o,i,r,s,t[u+9],12,-1958414417),s=m.ff(s,o,i,r,t[u+10],17,-42063),r=m.ff(r,s,o,i,t[u+11],22,-1990404162),i=m.ff(i,r,s,o,t[u+12],7,1804603682),o=m.ff(o,i,r,s,t[u+13],12,-40341101),s=m.ff(s,o,i,r,t[u+14],17,-1502002290),r=m.ff(r,s,o,i,t[u+15],22,1236535329),i=m.gg(i,r,s,o,t[u+1],5,-165796510),o=m.gg(o,i,r,s,t[u+6],9,-1069501632),s=m.gg(s,o,i,r,t[u+11],14,643717713),r=m.gg(r,s,o,i,t[u],20,-373897302),i=m.gg(i,r,s,o,t[u+5],5,-701558691),o=m.gg(o,i,r,s,t[u+10],9,38016083),s=m.gg(s,o,i,r,t[u+15],14,-660478335),r=m.gg(r,s,o,i,t[u+4],20,-405537848),i=m.gg(i,r,s,o,t[u+9],5,568446438),o=m.gg(o,i,r,s,t[u+14],9,-1019803690),s=m.gg(s,o,i,r,t[u+3],14,-187363961),r=m.gg(r,s,o,i,t[u+8],20,1163531501),i=m.gg(i,r,s,o,t[u+13],5,-1444681467),o=m.gg(o,i,r,s,t[u+2],9,-51403784),s=m.gg(s,o,i,r,t[u+7],14,1735328473),r=m.gg(r,s,o,i,t[u+12],20,-1926607734),i=m.hh(i,r,s,o,t[u+5],4,-378558),o=m.hh(o,i,r,s,t[u+8],11,-2022574463),s=m.hh(s,o,i,r,t[u+11],16,1839030562),r=m.hh(r,s,o,i,t[u+14],23,-35309556),i=m.hh(i,r,s,o,t[u+1],4,-1530992060),o=m.hh(o,i,r,s,t[u+4],11,1272893353),s=m.hh(s,o,i,r,t[u+7],16,-155497632),r=m.hh(r,s,o,i,t[u+10],23,-1094730640),i=m.hh(i,r,s,o,t[u+13],4,681279174),o=m.hh(o,i,r,s,t[u],11,-358537222),s=m.hh(s,o,i,r,t[u+3],16,-722521979),r=m.hh(r,s,o,i,t[u+6],23,76029189),i=m.hh(i,r,s,o,t[u+9],4,-640364487),o=m.hh(o,i,r,s,t[u+12],11,-421815835),s=m.hh(s,o,i,r,t[u+15],16,530742520),r=m.hh(r,s,o,i,t[u+2],23,-995338651),i=m.ii(i,r,s,o,t[u],6,-198630844),o=m.ii(o,i,r,s,t[u+7],10,1126891415),s=m.ii(s,o,i,r,t[u+14],15,-1416354905),r=m.ii(r,s,o,i,t[u+5],21,-57434055),i=m.ii(i,r,s,o,t[u+12],6,1700485571),o=m.ii(o,i,r,s,t[u+3],10,-1894986606),s=m.ii(s,o,i,r,t[u+10],15,-1051523),r=m.ii(r,s,o,i,t[u+1],21,-2054922799),i=m.ii(i,r,s,o,t[u+8],6,1873313359),o=m.ii(o,i,r,s,t[u+15],10,-30611744),s=m.ii(s,o,i,r,t[u+6],15,-1560198380),r=m.ii(r,s,o,i,t[u+13],21,1309151649),i=m.ii(i,r,s,o,t[u+4],6,-145523070),o=m.ii(o,i,r,s,t[u+11],10,-1120210379),s=m.ii(s,o,i,r,t[u+2],15,718787259),r=m.ii(r,s,o,i,t[u+9],21,-343485551),i=m.ad(i,c),r=m.ad(r,l),s=m.ad(s,d),o=m.ad(o,h);return m.rh(i)+m.rh(r)+m.rh(s)+m.rh(o)}static rh(e){let t="";for(let i=0;i<=3;i++)t+=m.alphabet.charAt(e>>i*8+4&15)+m.alphabet.charAt(e>>i*8&15);return t}static ad(e,t){let i=(e&65535)+(t&65535);return (e>>16)+(t>>16)+(i>>16)<<16|i&65535}static rl(e,t){return e<<t|e>>>32-t}static cm(e,t,i,r,s,o){return m.ad(m.rl(m.ad(m.ad(t,e),m.ad(r,o)),s),i)}static ff(e,t,i,r,s,o,c){return m.cm(t&i|~t&r,e,t,s,o,c)}static gg(e,t,i,r,s,o,c){return m.cm(t&r|i&~r,e,t,s,o,c)}static hh(e,t,i,r,s,o,c){return m.cm(t^i^r,e,t,s,o,c)}static ii(e,t,i,r,s,o,c){return m.cm(i^(t|~r),e,t,s,o,c)}static sb(e){let t,i=(e.length+8>>6)+1,r=new Array(i*16);for(t=0;t<i*16;t++)r[t]=0;for(t=0;t<e.length;t++)r[t>>2]|=e.charCodeAt(t)<<t%4*8;return r[t>>2]|=128<<t%4*8,r[i*16-2]=e.length*8,r}};m.alphabet="0123456789abcdef";var V=m;function Ge(n){if(n===0)return z[0];let e="";for(;n>0;)e=z[n%62]+e,n=Math.floor(n/62);return e}function B(n){return n.split("").reverse().reduce((e,t,i)=>e+z.indexOf(t)*62**i,0)}function oe(n=6){let e="",t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",i=t.length,r=0;for(;r<n;)e+=t.charAt(Math.floor(Math.random()*i)),r+=1;return e}function ve(){return typeof window>"u"||!!window?._runningInNodeJS}function $(){return !ve()&&typeof document<"u"&&typeof document.createElement=="function"}function pe(n){let e;try{e=JSON.stringify(n);}catch{throw new a("Invalid data type.",{code:"INVALID_REQUEST"})}if(new Blob([e]).size>On)throw new a("Data should not exceed 2MB",{code:"INVALID_REQUEST"})}function We(n){return n===""||n==="on"||n==="true"}function He(n){return n==="false"}function Je(n,e,t){e.name&&t(n,e.name,e.value);}var me=$(),jn=typeof SubmitEvent<"u",Bn=typeof HTMLFormElement<"u";function D(n,e,t){let i={},r=[];function s(l,d,h){if(e?.ignoreEmpty&&h==="")return;if(e?.nullIfEmpty&&h===""&&(h=null),typeof t=="function"){let A=t(d,h);A!==void 0&&(h=A);}let u=d.split("[").map(A=>{let f=A.replace("]",""),y=Number(f);return !isNaN(y)&&!f.includes(".")?f=y:(f[0]==='"'&&f[f.length-1]==='"'||f[0]==="'"&&f[f.length-1]==="'")&&(f=f.replace(/"/g,"").replace(/'/g,"")),f}),p=l;if(typeof u[0]=="number")throw new a("Form key cannot start with an array index.",{code:"INVALID_REQUEST"});for(let A=0;A<u.length;A++){let f=u[A];A<u.length-1?(p[f]===void 0&&(typeof u[A+1]=="number"?p[f]=[]:p[f]={}),p=p[f]):p[f]===void 0?p[f]=h:Array.isArray(p[f])?p[f].push(h):p[f]=[p[f],h];}}function o(l,d,h){if(h instanceof File)l.push({name:d,file:h});else if(h instanceof FileList&&h&&h.length>0)for(let u=0;u<=h.length-1;u++){let p=h.item(u);p&&l.push({name:d,file:p});}}let c=l=>{l.name&&(l.type==="number"?l.value&&s(i,l.name,Number(l.value)):l.type==="checkbox"||l.type==="radio"?l.checked?l.type==="checkbox"&&l.value===""||We(l.value)?s(i,l.name,true):He(l.value)?s(i,l.name,false):l.value&&s(i,l.name,l.value):l.type==="checkbox"&&(We(l.value)?s(i,l.name,false):He(l.value)&&s(i,l.name,true)):l.type==="file"?l.files&&l.files.length>0&&o(r,l.name,l.files):s(i,l.name,l.value));};if(me&&(n instanceof HTMLInputElement||n instanceof HTMLSelectElement||n instanceof HTMLTextAreaElement))return c(n),pe(i),{data:i,files:r};if(me&&n instanceof FormData){for(let l of n.entries()){let d=l[0],h=l[1];if(h instanceof File||h instanceof FileList)o(r,d,h);else if(h instanceof Blob){let u=h;if(u.type==="application/json")try{let p=JSON.parse(u.text());s(i,d,p);}catch{s(i,d,u);}}else s(i,d,h);}return pe(i),{data:i,files:r}}if(me&&jn&&n instanceof SubmitEvent&&(n=n.target),me&&Bn&&n instanceof HTMLFormElement){let l=n.querySelectorAll("input"),d=n.querySelectorAll("select"),h=n.querySelectorAll("textarea");for(let u=0;u<d.length;u++)Je(i,d[u],s);for(let u=0;u<h.length;u++)Je(i,h[u],s);for(let u=0;u<l.length;u++)c(l[u]);return pe(i),{data:i,files:r}}return pe(n),{data:n,files:r}}function ae(n){let e={};for(let t in n){let i=n[t];if(!Fn.includes(t))if(Ke[t])e[Ke[t]]=i;else if(t.includes("custom:"))e[t.replace("custom:","")]=i;else if(t==="address"){let r=i;if(r&&typeof r=="object"&&Object.keys(r).length){if(r?.formatted)try{e[t]=JSON.parse(r.formatted);}catch{e[t]=r.formatted;}}else e[t]=r;}else e[t]=i;}for(let t of ["address_public","birthdate_public","email_public","gender_public","phone_number_public","access_group"])t.includes("_public")?e.hasOwnProperty(t.split("_")[0])?e[t]=e.hasOwnProperty(t)?!!Number(e[t]):false:delete e[t]:e[t]=e.hasOwnProperty(t)?Number(e[t]):0;for(let t of ["email","phone_number"])e.hasOwnProperty(t)?e[t+"_verified"]=e[t+"_verified"]===true:delete e[t+"_verified"];return e}function De(n){if(n=Xn(n),n.split("-").length===7){let e=n.split("-"),t,i;try{t=ze[B(e[1][0])],i=e.slice(2).join("-");}catch{throw new Error("INVALID_PARAMETER: Service ID is invalid.")}if(!t)throw new Error("INVALID_PARAMETER: Service ID is invalid.");return {service:t+e[0]+e[1].slice(1),owner:i}}return {service:n,owner:""}}function Xe(n,e){let t=ze.indexOf(n.slice(0,4)),i=Mn[t],s=`${n.slice(4,-4)}-${i}${n.slice(-4)}-${e}`;return Gn(s)}function Kn(n){let e=0n;for(let t of n){let i=z.indexOf(t);if(i<0)throw new Error(`INVALID_PARAMETER: Invalid base62 character: ${t}`);e=e*xe+BigInt(i);}return e}function Qn(n,e=1){if(n<0n)throw new Error("INVALID_PARAMETER: Negative values are not supported.");if(n===0n)return "0".repeat(Math.max(1,e));let t="",i=n;for(;i>0n;){let r=Number(i%xe);t=z[r]+t,i/=xe;}return t.length<e&&(t="0".repeat(e-t.length)+t),t}function Wn(n){if(n===0n)return Uint8Array.from([0]);let e=[],t=n;for(;t>0n;)e.push(Number(t&0xffn)),t>>=8n;return e.reverse(),Uint8Array.from(e)}function Hn(n){let e=0n;for(let t of n)e=(e<<8n)+BigInt(t);return e}function Jn(n){let e=String(n).replace(/-/g,"");if(!/^[0-9a-fA-F]{32}$/.test(e))throw new Error("INVALID_PARAMETER: Invalid UUID format.");let t=new Uint8Array(16);for(let i=0;i<16;i++)t[i]=parseInt(e.slice(i*2,i*2+2),16);return t}function zn(n){let e=Array.from(qn(n),t=>t.toString(16).padStart(2,"0")).join("");return [e.slice(0,8),e.slice(8,12),e.slice(12,16),e.slice(16,20),e.slice(20)].join("-")}function Gn(n){let e=String(n);if(e.split("-").length===2)return e;let t=e.match(/^([0-9A-Za-z]+)-([0-9A-Za-z]+)-([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/);if(!t)throw new Error("INVALID_PARAMETER: Input must match <base62>-<base62>-<uuid>.");let[,i,r,s]=t;if(i.length<2)throw new Error("INVALID_PARAMETER: The first part must contain at least 2 characters.");if(r.length>=z.length)throw new Error("INVALID_PARAMETER: The middle section is too long to encode.");let o=i.slice(0,2),c=i.slice(2),l=r+o,d=z[r.length]+c+l,h=Jn(s),u=Qn(Hn(h));return `${d}-${u}`}function Xn(n){let e=String(n);if(e.split("-").length!==2)return e;let t=e.split("-");if(t.length!==2||!t[0]||!t[1])throw new Error("INVALID_PARAMETER: Corrupt compressed token.");let[i,r]=t,s=z.indexOf(i[0]);if(s<0)throw new Error("INVALID_PARAMETER: Corrupt compressed token.");let o=i.slice(1),c=s+2;if(o.length<c)throw new Error("INVALID_PARAMETER: Corrupt compressed token.");let l=o.slice(0,o.length-c),d=o.slice(o.length-c),h=d.slice(s),u=d.slice(0,s),p=h+l;if(!/^[0-9A-Za-z]+$/.test(p)||!/^[0-9A-Za-z]+$/.test(u))throw new Error("INVALID_PARAMETER: Corrupt compressed token.");let A=Kn(r),f=Wn(A);if(f.length>16)throw new Error("INVALID_PARAMETER: Corrupt compressed token.");let y=new Uint8Array(16);y.set(f,16-f.length);let P=zn(y);return `${p}-${u}-${P}`}function Yn(n,e="User ID"){let t=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;if(n){if(typeof n!="string")throw new a(`${e} should be type: string.`,{code:"INVALID_PARAMETER"});if(!n.match(t))throw new a(`${e} is invalid.`,{code:"INVALID_PARAMETER"})}else throw new a(`${e} is empty.`,{code:"INVALID_PARAMETER"});return n}function er(n){if(n&&(typeof n!="string"||n.charAt(0)!=="+"||isNaN(Number(n.substring(1)))))throw new a('"phone_number" is invalid. The format should be "+00123456789". Type: string.',{code:"INVALID_PARAMETER"});return n||""}function tr(n){if(n){if(typeof n!="string")throw new a('"birthdate" is invalid. The format should be "yyyy-mm-dd". Type: string.',{code:"INVALID_PARAMETER"});{let e=new RegExp(/([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))/);if(n.length!==10||n.split("-").length!==3||!e.test(n))throw new a('"birthdate" is invalid. The format should be "yyyy-mm-dd". Type: string.',{code:"INVALID_PARAMETER"})}}return n||""}function nr(n){if(n){if(typeof n!="string")throw new a('"password" should be type: string.',{code:"INVALID_PARAMETER"});if(n.length<6)throw new a('"password" should be at least 6 characters.',{code:"INVALID_PARAMETER"});if(n.length>60)throw new a('"password" can be up to 60 characters max.',{code:"INVALID_PARAMETER"})}else throw new a('"password" is required.',{code:"INVALID_PARAMETER"});return n}function rr(n,e="email"){if(n){if(typeof n!="string")throw new a(`"${e}"should be type: string.`,{code:"INVALID_PARAMETER"});if(n.length<5)throw new a(`"${e}" should be at least 5 characters.`,{code:"INVALID_PARAMETER"});if(/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/.test(n)&&(n=n.trim(),n.split("@")[1].split(".").length>=2))return n.toLowerCase()}else throw new a(`"${e}" is required.`,{code:"INVALID_PARAMETER"});throw new a(`"${n}" is an invalid email.`,{code:"INVALID_PARAMETER"})}function ir(n){let e=typeof window<"u",t=(()=>{let r=e&&window.location.origin||null;return r&&r.slice(-1)==="/"&&(r=r.slice(0,-1)),r})(),i=r=>{if(typeof r=="string"){if(r==="*")return "*";{let s=r.trim();if(s[0]==="/"&&t){if(t.slice(0,5)==="file:")throw new a(`"${r}" is an invalid url. Relative URL does not work on local file system. Use full URL string.`,{code:"INVALID_PARAMETER"});s=t+s;}else if(s[0]==="."&&t){if(t.slice(0,5)==="file:")throw new a(`"${r}" is an invalid url. Relative URL does not work on local file system. Use full URL string.`,{code:"INVALID_PARAMETER"});let c=e?window.location.href.split("?")[0]:"";c.slice(-1)!=="/"&&(c+="/"),s=c+s.slice(1);}let o;try{o=new URL(s);}catch{throw new a(`"${r}" is an invalid url.`,{code:"INVALID_PARAMETER"})}if(o.protocol)return o.href}}throw new a(`"${r}" is an invalid url.`,{code:"INVALID_PARAMETER"})};return Array.isArray(n)?n.map(r=>i(r)):i(n)}function sr(n,e,t=[],i){let r=D(n,i),s=r.data;e.service="string",e.owner="string";let o={};for(let c in e)if(s&&typeof s=="object"&&!Array.isArray(s)&&s.hasOwnProperty(c))if(typeof s[c]=="function")o[c]=s[c];else try{o[c]=JSON.parse(JSON.stringify(s[c]));}catch{o[c]=s[c];}i?.precall&&i.precall({data:o,files:r?.files||[]});try{return Zn__default.default(o,e,t)}catch(c){throw new a(c.message,{code:"INVALID_PARAMETER"})}}var g={UserId:Yn,PhoneNumber:er,Birthdate:tr,Password:nr,Email:rr,Url:ir,Params:sr};var U=null;function Ue(n){let e={tkid:"ticket_id",cond:"condition",stmp:"timestamp",actn:"action",cnt:"count",ttl:"time_to_live",plch:"placeholder",hash:"hash",desc:"description",pmc:"limit_per_user"},t={};for(let i in n)if(i==="tkid"){let r=n[i].split("#");if(r.length===1){t.ticket_id=r[0];continue}t.ticket_id=r[1],t.consume_id=r[2],t.user_id=r[3];let s=r[2].slice(-4);if(t.is_test=s===":CHK",!n.stmp){let o=r[2].slice(0,-4);/^[0-9]+$/.test(o)?t.timestamp=parseInt(o,10):t.timestamp=B(r[2].slice(0,-4));}}else e[i]?t[e[i]]=n[i]:t[i]=n[i];return t}async function Ye(n){if(!n.ticket_id)throw new a("Ticket ID is required.",{code:"INVALID_PARAMETER"});if(!n.method)throw new a('Method is required. Should be either "GET" or "POST"',{code:"INVALID_PARAMETER"});let e=n.ticket_id;await this.__connection;let t=await R.bind(this)(`https://${this.service.slice(0,4)}.${this.customApiDomain}/auth/consume/${this.service}/${this.owner}/${e}`,n?.data||{},{method:n.method,auth:!!n?.auth});return Ue(t)}async function et(n,e){await this.__connection;let t=await R.bind(this)("ticket",Object.assign({exec:"list"},n||{}),{auth:true,fetchOptions:e});return t.list=t.list.map(Ue),t}async function tt(n,e){await this.__connection;let t=await R.bind(this)("ticket",Object.assign({exec:"consumed"},n||{}),{auth:true,fetchOptions:e});return t.list=t.list.map(Ue),t}async function nt(n){return R.bind(this)("register-ticket",Object.assign({exec:"reg"},n),{auth:true})}async function rt(n){return R.bind(this)("register-ticket",Object.assign({exec:"unreg"},n),{auth:true})}async function ne(){if(await this.__connection,this.session){let n=Math.floor(Date.now()/1e3),t=this.session.getIdToken().getExpiration();if(t<n){this.log("request:requesting new token",null);try{await F.bind(this)().getSession({refreshToken:!0}),this.log("request:received new tokens",{exp:this.session?.idToken?.payload?.exp,currentTime:n,expiresIn:t-n,token:this.session?.accessToken?.jwtToken,refreshToken:this.session?.refreshToken?.token});}catch(i){throw this.log("request:new token error",i),new a("User login is required.",{code:"INVALID_REQUEST"})}}else this.log("request:tokens",{exp:this.session.idToken.payload.exp,currentTime:n,expiresIn:t-n,token:this.session.accessToken.jwtToken,refreshToken:this.session.refreshToken.token});return this.session?.idToken?.jwtToken}else throw this.log("request:no session",null),G.bind(this)(),new a("User login is required.",{code:"INVALID_REQUEST"})}function Ze(n,e){return new Promise((t,i)=>{e.refreshSession(n.getRefreshToken(),(r,s)=>{this.log("getSession:refreshSessionCallback",{refreshErr:r,refreshedSession:s}),r?(G.bind(this)(),i(r)):s.isValid()?t(s):(G.bind(this)(),i(new a("Invalid session.",{code:"INVALID_REQUEST"})));});})}function F(){if(!this.userPool)throw new a("User pool is missing",{code:"INVALID_REQUEST"});let n=()=>{let s=U.getSignInUserSession().getIdToken().payload||null,o=ae(s);return this.log("normalized user attribute",o),this.__user=o,o},e=async s=>new Promise((o,c)=>{this.log("getSession:option",s);let{refreshToken:l=false,skipUserUpdateEventTrigger:d=false}=s||{};if(l&&d&&(d=false),U=this.userPool.getCurrentUser(),!U){this.log("getSession:cognitoUser",U),G.bind(this)(),c(null);return}let h=u=>{let p=u.getIdToken().payload;if(this.log("getSession:respond:sessionAttribute",p),p["custom:service"]!==this.service)throw this.log("getSession:respond","invalid service, signing out"),G.bind(this)(),new a("Invalid session.",{code:"INVALID_REQUEST"});return this.session=u,n(),d||this._runOnUserUpdateListeners(this.user),this.session};U.getSession((u,p)=>{if(this.log("getSession:getSessionCallback",{err:u,session:p}),!p){G.bind(this)(),c(new a("Current session does not exist.",{code:"INVALID_REQUEST"}));return}if(u){Ze.bind(this)(p,U).then(_=>o(h(_))).catch(c);return}let A=Math.floor(Date.now()/1e3),f=p.getIdToken(),y=f.getExpiration(),P=y<A;if(this.log("getSession:currentTime",A),this.log("getSession:idTokenExp",y),this.log("getSession:isExpired",P),this.log("getSession:existingBearerToken",this.bearerToken),this.bearerToken=f.getJwtToken(),P||l||!p.isValid())Ze.bind(this)(p,U).then(_=>o(h(_))).catch(c);else try{o(h(p));}catch(_){c(_);}});}),t=(s,o)=>{let c=o||s.includes(this.service+"-")?s:this.service+"-"+V.hash(s);return {cognitoUser:new amazonCognitoIdentityJs.CognitoUser({Username:c,Pool:this.userPool}),cognitoUsername:c}};return {getSession:e,authenticateUser:(s,o,c=false,l=false)=>new Promise((d,h)=>{this.__request_signup_confirmation=null,this.__disabledAccount=null;let u=t(s,c),p=u.cognitoUsername,A=new amazonCognitoIdentityJs.AuthenticationDetails({Username:p,Password:o});u.cognitoUser.authenticateUser(A,{newPasswordRequired:(f,y)=>{this.__disabledAccount=null,this.__request_signup_confirmation=p,f["custom:signup_ticket"]==="PASS"||f["custom:signup_ticket"]==="MEMBER"||f["custom:signup_ticket"]==="OIDPASS"?u.cognitoUser.completeNewPasswordChallenge(o,{},{onSuccess:P=>{U=u.cognitoUser,e().then(_=>d(this.user));},onFailure:P=>{h(new a(P.message||"Failed to authenticate user.",{code:P.code}));}}):h(new a("User's signup confirmation is required.",{code:"SIGNUP_CONFIRMATION_NEEDED"}));},onSuccess:f=>e({skipUserUpdateEventTrigger:true}).then(y=>{this.__disabledAccount=null,this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user),d(this.user);}),onFailure:f=>{let y=[],{parsed:P,code:_}=be(f),k=typeof f?.message=="string"?f.message:"";if(_==="NotAuthorizedException"?k.includes("User is disabled.")?(this.__disabledAccount=p,y=["This account is disabled.","USER_IS_DISABLED"]):l?y=["The account already exists.","ACCOUNT_EXISTS"]:y=["Incorrect username or password.","INCORRECT_USERNAME_OR_PASSWORD"]:_==="UserNotFoundException"?y=["Incorrect username or password.","INCORRECT_USERNAME_OR_PASSWORD"]:_==="UserNotConfirmedException"?(this.__request_signup_confirmation=p,y=["User's signup confirmation is required.","SIGNUP_CONFIRMATION_NEEDED"]):(_==="TooManyRequestsException"||_==="LimitExceededException")&&(y=["Too many attempts. Please try again later.","REQUEST_EXCEED"]),P.code==="SIGNUP_CONFIRMATION_NEEDED"&&(this.__request_signup_confirmation=p),y.length){let S=y[1],T=y[0];h(new a(T,{code:S,cause:f}));}else h(P);}});}),createCognitoUser:t,signup:(s,o,c)=>new Promise((l,d)=>{this.userPool.signUp(s,o,c,null,(h,u)=>{if(h){let{parsed:p,code:A}=be(h),f=[];A==="UsernameExistsException"?f=["The account already exists.","EXISTS"]:A==="InvalidPasswordException"?f=["Invalid password. Password must be at least 6 characters.","INVALID_PARAMETER"]:A==="InvalidParameterException"?f=[p.message||"Invalid parameter.","INVALID_PARAMETER"]:A==="TooManyRequestsException"||A==="LimitExceededException"?f=["Too many attempts. Please try again later.","REQUEST_EXCEED"]:A==="CodeDeliveryFailureException"?f=["Failed to deliver verification code.","CODE_DELIVERY_FAILURE"]:A==="UserLambdaValidationException"&&(f=[p.message||"Signup validation failed.","INVALID_REQUEST"]),f.length?d(new a(f[0],{code:f[1],cause:h})):d(p);return}l(u);});})}}function be(n){let e=typeof n?.code=="string"&&n.code.trim()?n.code.trim():"ERROR",i=((typeof n?.message=="string"?n.message:typeof n=="string"?n:"An error occurred.")||"An error occurred.").trim();i||(i="An error occurred.");let r=i.match(/#([A-Za-z0-9_]+)\s*:\s*([\s\S]+)/),s=r?.[1]?.trim()||e,o=r?.[2]?.trim()||i;return {parsed:new a(o,{code:s,cause:n}),code:e}}async function it(n){await this.__authConnection;let e=n?.refreshToken||false;if(!e)return this.user;try{return await F.bind(this)().getSession(Object.assign({skipUserUpdateEventTrigger:!e,refreshToken:e},n)),this.user}catch{return null}}async function st(n){await this.__connection,n=g.Params(n,{token:"string",id:"string",merge:s=>{if(s===void 0)return false;if(typeof s=="string")return [s];if(Array.isArray(s)){for(let o of s)if(typeof o!="string")throw new a('"merge" array items should be type: <string>.',{code:"INVALID_PARAMETER"})}if(typeof s!="boolean"&&!Array.isArray(s))throw new a('"merge" should be type: <boolean | string[]>.',{code:"INVALID_PARAMETER"});return s}});let e=await R.bind(this)("openid-logger",n),t=e.logger.split("#"),i=this.service+"-"+t[0],r=t[1];return {userProfile:await F.bind(this)().authenticateUser(i,r,true,true),openid:e.openid}}function dr(n){let e=typeof globalThis<"u"?globalThis:void 0;if(e?.Buffer)return e.Buffer.from(n,"base64").toString("utf8");if(typeof atob=="function"){let t=atob(n),i=new Uint8Array(t.length);for(let r=0;r<t.length;r++)i[r]=t.charCodeAt(r);return typeof TextDecoder<"u"?new TextDecoder().decode(i):t}throw new Error("No base64 decoder available in this environment")}function gr(n){let e=n.split(".");if(e.length!==3)throw new Error("Invalid JWT format");let i=e[1].replace(/-/g,"+").replace(/_/g,"/"),r=dr(i);return JSON.parse(r)}async function ot(n){await this.__authConnection,this.log("loginWithToken:params",n),n=g.Params(n,{idToken:"string",accessToken:"string",refreshToken:"string"},["idToken"]);let e=gr(n.idToken);if(this.log("loginWithToken:idTokenPayload",e),e["custom:service"]!==this.service)throw new a("Token does not belong to this service.",{code:"INVALID_REQUEST"});let t=Math.floor(Date.now()/1e3);if(e.exp&&e.exp<t)throw new a("Token has expired.",{code:"INVALID_REQUEST"});if(this.__user=ae(e),this.session=null,n.accessToken&&n.refreshToken)try{if(this.session=new amazonCognitoIdentityJs.CognitoUserSession({IdToken:new amazonCognitoIdentityJs.CognitoIdToken({IdToken:n.idToken}),AccessToken:new amazonCognitoIdentityJs.CognitoAccessToken({AccessToken:n.accessToken}),RefreshToken:new amazonCognitoIdentityJs.CognitoRefreshToken({RefreshToken:n.refreshToken})}),this.log("loginWithToken:session",this.session),this.log("loginWithToken:CognitoUser",amazonCognitoIdentityJs.CognitoUser),this.log("loginWithToken:userPool",this.userPool),amazonCognitoIdentityJs.CognitoUser&&this.userPool){this.log("loginWithToken:cognito:username",e["cognito:username"]);let i={Username:e["cognito:username"],Pool:this.userPool};this.log("loginWithToken:cognitoUserParams",i),U=new amazonCognitoIdentityJs.CognitoUser(i),U.setSignInUserSession(this.session),this.log("loginWithToken:cognitoUserRestored",{cognitoUserType:typeof U,cognitoUserKeys:Object.keys(U||{}),cognitoUser:U});}}catch(i){this.log("loginWithToken:err",i);try{this.log("loginWithToken:err:stringified",JSON.stringify(i));}catch{this.log("loginWithToken:err:stringifyFail",String(i));}try{let r=Object.keys(i||{}),s=Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(i||{}):[],o=Object.getOwnPropertyDescriptors?Object.getOwnPropertyDescriptors(i||{}):{};this.log("loginWithToken:createSessionError:allKeys",{keys:r,symbols:s,descriptors:o});}catch(r){this.log("loginWithToken:createSessionError:allKeysFail",String(r));}}return this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user),this.user}async function M(){return await this.__connection,this.__user?.service===this.service?this.__user?.owner===this.host:(await ce.bind(this)(),false)}async function G(n=false){let e=null;U&&(n?e=new Promise((i,r)=>{U.globalSignOut({onSuccess:s=>{this.log("globalSignOut:success",s),i(s);},onFailure:s=>{this.log("globalSignOut:error",s),r(s);}});}):U.signOut());let t={session:null,__startKeyHistory:{},__cached_requests:{},__user:null};e&&(e=await e);for(let i in t)this[i]=t[i];return this._runOnUserUpdateListeners(null),this._runOnLoginListeners(null),e}async function ce(n){await this.__connection;let{data:e}=D(n);return await G.bind(this)(e?.global),"SUCCESS: The user has been logged out."}async function at(){if(!this.__request_signup_confirmation)throw new a("Least one login attempt is required.",{code:"INVALID_REQUEST"});return await R.bind(this)("confirm-signup",{username:this.__request_signup_confirmation})}async function ct(n=false){if(typeof n=="string")n=g.Url(n);else if(typeof n!="boolean")throw new a("Argument should be type: <boolean | string>.",{code:"INVALID_REQUEST"});if(!this.__disabledAccount)throw new a("Least one signin attempt of disabled account is required.",{code:"INVALID_REQUEST"});return await R.bind(this)("recover-account",{username:this.__disabledAccount,redirect:n}),"SUCCESS: Recovery e-mail has been sent."}async function Ne(n){let e=g.Params(n,{username:"string",email:"string",password:"string"},["password"]);if(await this.__authConnection,e.email)try{g.Email(e.email);}catch{e.username=e.email,delete e.email;}if(!e.username&&!e.email)throw new a('Least one of "username" or "email" is required.',{code:"INVALID_PARAMETER"});return await F.bind(this)().authenticateUser(e.username||e.email,e.password)}async function lt(n,e){await this.__authConnection;let t={username:"string",password:d=>g.Password(d),email:d=>g.Email(d),name:"string",address:d=>{if(!d)return "";if(typeof d=="string")return d;if(typeof d=="object")return JSON.stringify(d)},gender:"string",birthdate:d=>d?g.Birthdate(d):"",phone_number:d=>d?g.PhoneNumber(d):"",email_public:["boolean",()=>false],address_public:["boolean",()=>false],gender_public:["boolean",()=>false],birthdate_public:["boolean",()=>false],phone_number_public:["boolean",()=>false],access_group:"number",misc:"string",picture:d=>d?g.Url(d):"",profile:d=>d?g.Url(d):"",family_name:"string",given_name:"string",middle_name:"string",nickname:"string",website:d=>d?g.Url(d):""},i=g.Params(n||{},t,["email","password"]);await ce.bind(this)(),e=g.Params(e||{},{email_subscription:d=>{if(typeof d!="boolean")throw new a('"option.email_subscription" should be type: <boolean>.',{code:"INVALID_PARAMETER"});if(!e?.signup_confirmation)throw new a('"option.signup_confirmation" is required for email subscription.',{code:"INVALID_PARAMETER"});return d},signup_confirmation:d=>{let h=d;if(typeof d=="string")h=g.Url(d);else if(typeof d=="boolean")h=d;else throw new a('"option.signup_confirmation" should be type: <string | boolean>.',{code:"INVALID_PARAMETER"});if(h&&!i.email)throw new a('"email" is required for signup confirmation.',{code:"INVALID_PARAMETER"});return h},login:d=>{if(typeof d=="boolean"){if(e.signup_confirmation&&d)throw new a('"login" is not allowed when "option.signup_confirmation" is true.',{code:"INVALID_PARAMETER"});return d}throw new a('"option.login" should be type: boolean.',{code:"INVALID_PARAMETER"})}});let r=e?.login||false;if(i.signup_confirmation=e?.signup_confirmation||false,i.email_subscription=e?.email_subscription||false,i.email_public&&!i.signup_confirmation)throw new a('"option.signup_confirmation" should be true if "email_public" is set to true.',{code:"INVALID_PARAMETER"});i.service=this.service,i.owner=this.owner;let s=F.bind(this)().createCognitoUser(i.username||i.email);for(let d of ["email_public","address_public","gender_public","birthdate_public","phone_number_public"])i[d]=i[d]?"1":"0";i.access_group&&(i.access_group=i.access_group.toString());let o=(await R.bind(this)("signupkey",{username:s.cognitoUsername,signup_confirmation:typeof i.signup_confirmation=="boolean"?JSON.stringify(i.signup_confirmation):i.signup_confirmation,email_subscription:i.email_subscription})).split(":"),c=o.slice(1).join(":"),l=[new amazonCognitoIdentityJs.CognitoUserAttribute({Name:"custom:signup",Value:o[0]}),new amazonCognitoIdentityJs.CognitoUserAttribute({Name:"locale",Value:c.split("#")[1]}),new amazonCognitoIdentityJs.CognitoUserAttribute({Name:"custom:signup_ticket",Value:c})];for(let d in t){let h=["email_public","address_public","gender_public","birthdate_public","phone_number_public","misc","service","owner"];i[d]!==""&&(d==="username"||d==="password"||d==="access_group"||(h.includes(d)?l.push(new amazonCognitoIdentityJs.CognitoUserAttribute({Name:"custom:"+d,Value:i[d]})):l.push(new amazonCognitoIdentityJs.CognitoUserAttribute({Name:d,Value:i[d]}))));}return await F.bind(this)().signup(s.cognitoUsername,i.password,l),i.signup_confirmation?(U=s.cognitoUser,this.__request_signup_confirmation=s.cognitoUsername,"SUCCESS: The account has been created. User's signup confirmation is required."):r?Ne.bind(this)({email:i.username||i.email,password:i.password}):"SUCCESS: The account has been created."}async function ut(){await this.__connection;let n=await R.bind(this)("remove-account",{disable:this.__user.user_id},{auth:true});return await ce.bind(this)(),n}async function dt(n){await this.__connection;let e=g.Params(n,{email:r=>g.Email(r),code:["number","string"],new_password:r=>g.Password(r)},["email","code","new_password"]),t=e.code,i=e.new_password;return typeof t=="number"&&(t=t.toString()),new Promise(async(r,s)=>{F.bind(this)().createCognitoUser(e.email).cognitoUser.confirmPassword(t,i,{onSuccess:c=>{r("SUCCESS: New password has been set.");},onFailure:c=>{s(new a(c?.message||"Failed to reset password.",{code:c?.code||"ERROR",cause:c}));}});})}async function gt(n,e){await this.__connection;let t;if(!U)throw new a("The user has to be logged in.",{code:"INVALID_REQUEST"});if(n==="email"||n==="phone_number"){if(!this.__user.hasOwnProperty(n))throw new a(`No ${n==="email"?"e-mail":"phone number"} to verify`,{code:"INVALID_REQUEST"});if(this.__user?.[`${n}_verified`])return `SUCCESS: "${n}" is verified.`;t=(e?g.Params(e,{code:"string"}):{}).code||"";}else return;return new Promise((i,r)=>{let s={onSuccess:o=>{t?F.bind(this)().getSession({refreshToken:true}).then(()=>{this.__user&&(this.__user[n+"_verified"]=true),i(`SUCCESS: "${n}" is verified.`);}).catch(c=>{r(c);}):i("SUCCESS: Verification code has been sent.");},onFailure:o=>{r(new a(o.message||"Failed to request verification code.",{code:o?.code}));}};t?U?.verifyAttribute(n,t,s):(s.inputVerificationCode=null,U?.getAttributeVerificationCode(n,s));})}function ft(n){return gt.bind(this)("phone_number",n)}function ht(n){return gt.bind(this)("email",n)}async function pt(n){await this.__connection;let e=g.Params(n,{email:t=>g.Email(t)},["email"]);return new Promise(async(t,i)=>{F.bind(this)().createCognitoUser(e.email).cognitoUser.forgotPassword({onSuccess:s=>{t("SUCCESS: Verification code has been sent.");},onFailure:s=>{let{parsed:o,code:c}=be(s),l={UserNotFoundException:"NOT_EXISTS",InvalidParameterException:"INVALID_PARAMETER",NotAuthorizedException:"INVALID_REQUEST",LimitExceededException:"REQUEST_EXCEED",TooManyRequestsException:"REQUEST_EXCEED",CodeDeliveryFailureException:"CODE_DELIVERY_FAILURE"}[c]||o.code||c||"ERROR";i(new a(o.message,{code:l,cause:s}));}});})}async function mt(n){if(await this.__connection,!this.session)throw new a("User login is required.",{code:"INVALID_REQUEST"});let e=g.Params(n,{current_password:"string",new_password:"string"});if(!e?.current_password)throw new a('"current_password" is required to change password.',{code:"INVALID_PARAMETER"});if(!e?.new_password)throw new a('"new_password" is required to change password.',{code:"INVALID_PARAMETER"});return g.Password(e.current_password),g.Password(e.new_password),new Promise((t,i)=>{U.changePassword(e.current_password,e.new_password,(r,s)=>{if(r){if(r?.code==="InvalidParameterException")i(new a("Invalid password parameter.",{code:"INVALID_PARAMETER"}));else if(r?.code==="NotAuthorizedException")i(new a("Incorrect password.",{code:"INVALID_REQUEST"}));else if(r?.code==="TooManyRequestsException"||r?.code==="LimitExceededException")i(new a("Too many attempts. Please try again later.",{code:"REQUEST_EXCEED"}));else {let{parsed:o}=be(r);i(o);}return}t("SUCCESS: Password has been changed.");});})}async function _t(n){if(await this.__connection,!this.session)throw new a("User login is required.",{code:"INVALID_REQUEST"});let e=g.Params(n||{},{user_id:r=>g.UserId(r),email:r=>g.Email(r),address:r=>{if(!r)return "";if(typeof r=="string")return r;if(typeof r=="object")return JSON.stringify(r)},name:"string",gender:"string",birthdate:r=>r?g.Birthdate(r):"",phone_number:r=>r?g.PhoneNumber(r):"",email_public:"boolean",phone_number_public:"boolean",address_public:"boolean",gender_public:"boolean",birthdate_public:"boolean",misc:"string",picture:r=>r?g.Url(r):"",profile:r=>r?g.Url(r):"",family_name:"string",given_name:"string",middle_name:"string",nickname:"string",website:r=>r?g.Url(r):""});if(e&&typeof e=="object"&&!Object.keys(e).length)return this.user;e.email&&(e.preferred_username=this.service+"-"+V.hash(e.email));let t=[["email_public","email_verified","User's e-mail should be verified to set"],["phone_number_public","phone_number_verified","User's phone number should be verified to set"]];if(this.__user){for(let r of t)if(e[r[0]]&&!this.__user[r[1]])throw new a(`${r[2]} "${r[0]}" to true.`,{code:"INVALID_REQUEST"})}let i=[];for(let r in e){if(e[r]===this.user[r]){i.push(r);continue}if(["email_public","phone_number_public","address_public","gender_public","birthdate_public","misc"].includes(r)){let o=e[r];typeof o=="boolean"&&(o=o?"1":"0"),e["custom:"+r]=o,i.push(r);}}for(let r of i)delete e[r];if(e.user_id)if(e.user_id===this.user.user_id)delete e.user_id;else return R.bind(this)("admin-edit-profile",{attributes:e},{auth:true});if(e&&typeof e=="object"&&Object.keys(e).length){let r=[];for(let s in e)r.push(new amazonCognitoIdentityJs.CognitoUserAttribute({Name:s,Value:e[s]}));return await new Promise((s,o)=>{U?.updateAttributes(r,(c,l)=>{c&&o([c?.code||c?.name,c?.message||"Failed to update user settings."]),s(l);});}),await F.bind(this)().getSession({refreshToken:true}),this.user}return this.user}async function bt(n,e){n=D(n).data,n||(n={searchFor:"timestamp",condition:">",value:0},e||(e={}),e.ascending=false),await this.__connection;let t={user_id:r=>Array.isArray(r)?r.map(s=>g.UserId(s)):g.UserId(r),email:"string",phone_number:"string",locale:r=>{if(typeof r!="string"||typeof r=="string"&&r.length>5)throw new a('Value of "locale" should be a country code.',{code:"INVALID_PARAMETER"});return r},name:"string",address:"string",gender:"string",birthdate:r=>g.Birthdate(r),subscribers:"number",timestamp:"number",access_group:"number",approved:"string"},i=["searchFor","value"];if(n=g.Params(n,{searchFor:["user_id","name","email","phone_number","address","gender","birthdate","locale","subscribers","timestamp","access_group","approved"],condition:[">",">=","=","<","<=","gt","gte","eq","lt","lte",()=>"="],value:r=>{let s=t[n.searchFor];if(typeof s=="function")return s(r);if(typeof r!==s)throw new a(`Value does not match the type of "${n.searchFor}" index.`,{code:"INVALID_PARAMETER"});return r},range:r=>{let s=t[n.searchFor];if(typeof s=="function")return s(r);if(typeof r!==s)throw new a(`Range does not match the type of "${n.searchFor}" index.`,{code:"INVALID_PARAMETER"});return r}},i),n?.condition&&n?.condition!=="="&&n.hasOwnProperty("range"))throw new a("Conditions does not apply on range search.",{code:"INVALID_PARAMETER"});if(n.searchFor==="user_id"&&(n.condition!=="="||n.range))throw new a(`Conditions are not allowed on "${n.searchFor}"`,{code:"INVALID_PARAMETER"});if(typeof n?.value=="string"&&!n?.value)throw new a("Value should not be an empty string.",{code:"INVALID_PARAMETER"});if(typeof n?.searchFor=="string"&&!n?.searchFor)throw new a('"searchFor" should not be an empty string.',{code:"INVALID_PARAMETER"});return R.bind(this)("get-users",n,{auth:true,fetchOptions:e})}async function yt(n){await this.__connection;let e=await R.bind(this)("last-verified-email",n,{auth:true});return e.includes("SUCCESS")?(await F.bind(this)().getSession({refreshToken:true}),this.user):e}async function wt(n){return await this.__connection,n=g.Params(n,{username:g.Email,redirect:g.Url},["username"]),await R.bind(this)("request-username-change",n,{auth:true})}var re=null,Rt=typeof SubmitEvent<"u",hr=typeof HTMLFormElement<"u",ue=$(),Ce=0;function At(n){if(!n)return null;let e=Number(n);if(Number.isFinite(e))return Math.max(0,e*1e3);let t=Date.parse(n);return Number.isNaN(t)?null:Math.max(0,t-Date.now())}function Le(n,e){return e>0?n/e*100:0}var Et=n=>{let{auth:e,type:t,endpoints:i}=n,r=i[0],s=i[1];if(Ce++,t==="admin"){let o=Object.entries(r).filter(([c,l])=>c.includes(e?"_private":"_public")&&c!=="get_users_private"&&c!=="service_public"&&typeof l=="string").map(([,c])=>c);if(!o.length)throw new a("No available admin gateways.",{code:"INVALID_REQUEST"});return o[Ce%o.length]}if(t==="record"){let o=Object.entries(s).filter(([c,l])=>c.includes(e?"record_private":"record_public")&&typeof l=="string").map(([,c])=>c);if(!o.length)throw new a("No available record gateways.",{code:"INVALID_REQUEST"});return o[Ce%o.length]}throw new a("Invalid gateway type.",{code:"INVALID_REQUEST"})};async function pr(n,e){let t=await Promise.all([this.admin_endpoint,this.record_endpoint]),i=t[0],r=t[1],s=n.split("?"),o=s.length>1?"?"+s[1]:"";switch(n=s[0],n){case "get-users":return i.get_users_private+n+o;case "service":return i.service_public+n+o;case "get-newsletters":case "get-public-newsletters":case "subscribe-newsletter":case "subscribe-public-newsletter":case "signupkey":case "admin-newsletter-request":case "admin-signup":case "confirm-signup":case "openid-logger":case "block-account":case "admin-edit-profile":case "remove-account":case "post-secure":case "recover-account":case "mock":case "grant-access":case "last-verified-email":case "ticket":case "register-ticket":case "get-newsletter-subscription":case "request-username-change":case "send-inquiry":case "register-newsletter-group":case "newsletter-group-endpoint":case "invitation-list":case "csr":return Et.bind(this)({auth:e,type:"admin",endpoints:t})+n+o;case "post-record":return (e?r.post_private:r.post_public)+n+o;case "get-records":return (e?r.get_private:r.get_public)+n+o;case "del-files":case "del-records":return r.del_private+n+o;case "store-subscription":case "get-vapid-public-key":case "push-notification":case "delete-subscription":case "subscription":case "get-subscription":case "get-table":case "get-tag":case "get-uniqueid":case "get-index":case "get-signed-url":case "grant-private-access":case "request-private-access-key":case "get-ws-group":case "check-schema":case "get-feed":case "castspell":case "dopamine":case "getspell":return Et.bind(this)({auth:e,type:"record",endpoints:t})+n+o;default:return g.Url(n)+o}}var le={};function It(){re&&(re.terminate(),re=null);}async function R(n,e=null,t,i){this.log("request",{url:n,data:e,options:t,_etc:i||{}}),t=t||{};let{auth:r=false,method:s="post",bypassAwaitConnection:o=false}=t;s=s.toUpperCase();let c=null,l=e?.service||this.service,d=e?.owner||this.owner,h=null,u=await pr.bind(this)(n,!!r);if(!o&&(c=await this.__connection,!c))throw new a("Invalid connection. The service could have been disabled, or has a restricted CORS.",{code:"INVALID_REQUEST"});r&&(h=await ne.bind(this)());let p={},{fetchMore:A=false,progress:f}=t?.fetchOptions||{};if(t?.fetchOptions&&Object.keys(t.fetchOptions).length){for(let x of ["limit","startKey","ascending"])t.fetchOptions.hasOwnProperty(x)&&(p[x]=t.fetchOptions[x]);p=g.Params(p,{limit:x=>{if(typeof x!="number")throw new a("Fetch limit should be a number.",{code:"INVALID_REQUEST"});if(x>1e3)throw new a("Fetch limit should be below 1000.",{code:"INVALID_REQUEST"});return x},startKey:x=>x,ascending:"boolean"});}let y=i?.ignoreService?{}:{service:l,owner:d};Object.assign(y,p),e=D(e).data,e?e&&typeof e=="object"&&(e=Object.assign(y,e)):e=y;let P=`${s}:${r?"auth":"public"}:${n}`,_=(()=>{if(e&&typeof e=="object"&&Object.keys(e).length&&!(ue&&e instanceof FormData)){let x=function(v){return typeof v=="object"&&v!==null?Object.keys(v).sort().reduce((N,O)=>(typeof v[O]=="object"&&v[O]!==null?N[O]=x(v[O]):N[O]=v[O],N),{}):v};return V.hash(P+"/"+JSON.stringify(x(e)))}return V.hash(P+"/"+l)})(),{requestKey:k,requestKeyWithStartKey:S}=mr.bind(this)({params:e,url:n,fetchMore:A,hashedParams:_});if(!k||k&&typeof k=="object")return k;if(this.log("requestKey",S),typeof S=="string"&&le[S]instanceof Promise)return this.log("request:returning pending",S),le[S];let T={Accept:"*/*"};if(Object.prototype.hasOwnProperty.call(t,"contentType")&&t.contentType!==void 0){let x=t.contentType===null?"application/x-www-form-urlencoded":t.contentType;x&&(T["Content-Type"]=x);}else T["Content-Type"]="application/json";h&&(T.Authorization=h);let q={public_identifier:this.__public_identifier,service:l,owner:d};T["Content-Meta"]=JSON.stringify(q);let j={headers:T};if(t?.responseType&&(j.responseType=t.responseType),s==="GET"){if(e){let x=[];if(ue&&e instanceof FormData?x=Array.from(e.entries()).map(([v,N])=>{let O=typeof N=="string"?N:N.name;return encodeURIComponent(v)+"="+encodeURIComponent(O)}):x=Object.keys(e).map(v=>{let N=e[v];return typeof N!="string"&&(N=JSON.stringify(N)),encodeURIComponent(v)+"="+encodeURIComponent(N)}),x.length){let v=u.includes("?")?u.endsWith("?")||u.endsWith("&")?"":"&":"?";u+=v+x.join("&");}}j.body=null;}else if(ue&&e instanceof FormData)j.body=e;else if(T["Content-Type"]==="application/x-www-form-urlencoded"&&e&&typeof e=="object"){let x=new URLSearchParams;for(let v of Object.keys(e)){let N=e[v];x.append(v,typeof N=="string"?N:JSON.stringify(N));}j.body=x.toString();}else typeof e=="string"?j.body=e:j.body=e?JSON.stringify(e):null;if(j.method=s,re===null){let x={batchSize:this.requestBatchSize,breakWhenError:false,onProgress:v=>{this.onBatchProcess.forEach(N=>N(v));}};re=new fr__default.default(x);}return this.log("request-opt",j),new Promise((x,v)=>{re.add([async()=>{let N=Tt.bind(this)(u,j,f);le[S]=N;try{let O=_r.bind(this)({hashedParam:k,requestKeyWithStartKey:S,url:n,fetched:await N});return delete le[S],this.log("request:end",O),x(O),O}catch(O){throw delete le[S],this.log("request:err",O),v(O),O}}]);})}function mr(n){let{params:e={},url:t,fetchMore:i=false,hashedParams:r}=n||{};if(e.startKey){if(!(typeof e.startKey=="object"&&Object.keys(e.startKey).length)&&e.startKey!=="start"&&e.startKey!=="end")throw new a(`"${e.startKey}" is invalid startKey key.`,{code:"INVALID_PARAMETER"});e.startKey==="start"&&(i=false,delete e.startKey);}if(!i){if(this.__cached_requests?.[t]?.[r]&&delete this.__cached_requests[t][r],this.__startKeyHistory?.[t]?.[r]){if(Array.isArray(this.__startKeyHistory[t][r])&&this.__startKeyHistory[t][r].length)for(let l of this.__startKeyHistory[t][r]){let d=r+V.hash(l);this.__cached_requests?.[t]&&this.__cached_requests?.[t]?.[d]&&delete this.__cached_requests[t][d];}delete this.__startKeyHistory[t][r];}return {requestKeyWithStartKey:r,requestKey:r}}if(!Array.isArray(this.__startKeyHistory?.[t]?.[r]))return {requestKeyWithStartKey:r,requestKey:r};let s=this.__startKeyHistory[t][r],o=s[s.length-1],c=r;if(o){if(o==="end")return {requestKey:{list:[],startKey:"end",endOfList:true,startKeyHistory:s},requestKeyWithStartKey:c};c+=V.hash(o),e.startKey=JSON.parse(o);}return this.__cached_requests?.[t]?.[c]?{requestKey:this.__cached_requests[t][c],requestKeyWithStartKey:c}:{requestKeyWithStartKey:c,requestKey:r}}function Tt(n,e,t){return new Promise((i,r)=>{let s=new XMLHttpRequest;s.open(e.method||"GET",n);for(var o in e.headers||{})s.setRequestHeader(o,e.headers[o]);e.responseType&&(s.responseType=e.responseType),s.onload=()=>{if(s.status<400)if(e.responseType=="json"||e.responseType=="blob")i(s.response);else {let c=s.responseText;try{c=JSON.parse(c);}catch{}i(c);}else if(s.status===429){let c=s.getResponseHeader("Retry-After"),l=At(c);l!==null?setTimeout(()=>{Tt(n,e,t).then(i,r);},l):r("Too many requests");}else {let c=s.status,l=["INVALID_CORS","INVALID_REQUEST","SERVICE_DISABLED","INVALID_PARAMETER","ERROR","EXISTS","NOT_EXISTS"],d=e.responseType=="blob"?s.response:s.responseText;try{d=JSON.parse(d);}catch{}if(typeof d=="string"){let h=d.split(":"),u=h.splice(0,1)[0].trim(),p=h.join(":").trim();r(new a(p||d,{code:l.includes(u)?u:"ERROR"}));}else if(typeof d=="object"&&d?.message){let h=d?.code||(c?c.toString():null)||"ERROR",u=d.message,p=d?.cause;typeof u=="string"&&(u=u.trim()),r(new a(u,{cause:p,code:h}));}else r(d);}},s.onerror=()=>r("Network error"),s.onabort=()=>r("Aborted"),s.ontimeout=()=>r("Timeout"),typeof t=="function"&&(s.onprogress=c=>{t({status:"download",progress:Le(c.loaded,c.total),loaded:c.loaded,total:c.total,abort:()=>s.abort()});},s.upload&&(s.upload.onprogress=c=>{t({status:"upload",progress:Le(c.loaded,c.total),loaded:c.loaded,total:c.total,abort:()=>s.abort()});})),s.send(e.body);})}function _r(n){let{hashedParam:e,requestKeyWithStartKey:t,url:i,fetched:r}=n;if(!r?.startKey)return r;this.__startKeyHistory.hasOwnProperty(i)||(this.__startKeyHistory[i]={}),this.__startKeyHistory[i].hasOwnProperty(e)||(this.__startKeyHistory[i][e]=[]);let s=r.startKey==="end"?"end":JSON.stringify(r.startKey);return this.__startKeyHistory[i][e].includes(s)||this.__startKeyHistory[i][e].push(s),this.__cached_requests?.[i]||(this.__cached_requests[i]={}),this.__cached_requests[i][t]=r,Object.assign({startKeyHistory:this.__startKeyHistory[i][e]},r)}async function we(n,e){await this.__connection;let{record_id:t,service:i=this.service,progress:r}=e;if(!t)throw new a('"record_id" is required.',{code:"INVALID_PARAMETER"});if(Rt&&n instanceof SubmitEvent&&(n=n.target),hr&&n instanceof HTMLFormElement&&(n=new FormData(n)),!ue||!(n instanceof FormData))throw new a('"fileList" should be a FormData or HTMLFormElement.',{code:"INVALID_PARAMETER"});let o={reserved_key:oe(),service:i,request:"post"};e?.record_id&&(o.id=e.record_id);let c,l=(A,f,y)=>new Promise((P,_)=>{c=new XMLHttpRequest,c.open("POST",A),c.onload=()=>{let k=c.responseText;try{k=JSON.parse(k);}catch{}if(c.status>=200&&c.status<300)P(k);else if(c.status===429){let S=c.getResponseHeader("Retry-After"),T=At(S);T!==null?setTimeout(()=>{l(A,f,y).then(P,_);},T):_("Too many requests");}else _(k);},c.onerror=()=>_("Network error"),c.onabort=()=>_("Aborted"),c.ontimeout=()=>_("Timeout"),c.upload&&typeof y=="function"&&(c.upload.onprogress=y),c.send(f);});function d(A){let f="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";if(A===0)return f[0];let y="";for(;A>0;)y=f[A%62]+y,A=Math.floor(A/62);return y}let h=[],u=[],p=[];for(let[A,f]of n.entries()){if(!(f instanceof File))continue;let y=Object.assign({key:A+"/"+f.name,sizeKey:d(f.size),contentType:f.type||null},o),{fields:P=null,url:_,cdn:k}=await R.bind(this)("get-signed-url",y,{auth:!!this.__user});p.push(k);let S=new FormData;for(let T in P)S.append(T,P[T]);S.append("file",f);try{await l(_,S,typeof r=="function"?T=>r({status:"upload",progress:Le(T.loaded,T.total),currentFile:f,completed:h,failed:u,loaded:T.loaded,total:T.total,abort:()=>c.abort()}):null),h.push(f);}catch{u.push(f);}}return {completed:h,failed:u,bin_endpoints:p}}var ye={};function E(n){let{preventMultipleCalls:e=false}=n||{};return function(t,i,r){let s=r.value;r.value=function(...o){let c=o[0],l=true,d=null,h="",u={},p=false;if(Rt&&c instanceof SubmitEvent){c.preventDefault();let _=window.location.href;d=c.target;let k=new URL(d.action);h=k.href;let S=h?h.match(/(?<=\{).*?(?=\})/g):"";if(S)for(let T of S){if(!T)continue;let L=d.querySelector(`[name="${T}"]`);if(L)if(L.type==="file")for(let q=0;q<=L.files.length-1;q++)L.files[q]&&(u[T]||(u[T]=[]),u[T].push(new Promise((j,x)=>{let v=new FileReader;v.onload=function(){j(v.result);},v.readAsDataURL(L.files[q]),v.onerror=x;})));else h=h.replace(`{${T}}`,L.value);}d.getAttribute("action")===null?l=false:p=k.href===_;}let A=async _=>{if(h)for(let k in u)u[k].length&&(h=h.replace(`{${k}}`,(await Promise.all(u[k])).join(",")));return d&&l&&(window.sessionStorage.setItem(`${this.service}:${V.hash(h)}`,JSON.stringify(_)),p?window.location.replace(h):window.location.href=h),_},f,y=_=>{throw _ instanceof a?_.name=i+"()":_=_ instanceof Error?_:new a(_,{name:i+"()"}),_},P=async()=>{try{if(f=s.bind(this)(...o),f instanceof Promise){let _=await f;return A(_)}return A(f)}catch(_){throw y(_)}};if(e){let _=`${i}:${this?.__public_identifier||""}:${this?.service||""}:${this?.owner||""}`;return ye?.[_]||(ye[_]=P().finally(()=>{delete ye[_];})),ye[_]}return P()};}}async function Pt(){await this.__connection;let n=`${this.service}:${V.hash(window.location.href.split("?")[0])}`,e=window.sessionStorage.getItem(n);if(window.sessionStorage.removeItem(n),e!==null){try{e=JSON.parse(e);}catch{}return e}return null}var br=128,yr=64,wr=128,Er=256,Rr="\u{10FFFF}",Ar=/[\u0000-\u001F\u007F]|\u{10FFFF}/u,Ir=/[\/!*#]/;function X(n,e,t={}){let{allowEmpty:i=false,maxLength:r,blockKeyDelimiters:s=false,disallowLeadingDollar:o=false,onlyAlphanumeric:c=false}=t;if(typeof n!="string")throw new a(`"${e}" should be type: <string>.`,{code:"INVALID_PARAMETER"});if(c&&/[^a-zA-Z0-9]/.test(n))throw new a(`"${e}" should only contain alphanumeric characters.`,{code:"INVALID_PARAMETER"});if(!i&&n.length===0)throw new a(`"${e}" is required.`,{code:"INVALID_PARAMETER"});if(r&&n.length>r)throw new a(`"${e}" should be <= ${r} characters.`,{code:"INVALID_PARAMETER"});if(Ar.test(n)||n.includes(Rr))throw new a(`"${e}" cannot include control characters or unsupported sentinel characters.`,{code:"INVALID_PARAMETER"});if(s&&Ir.test(n))throw new a(`"${e}" cannot include reserved delimiters: / ! * #`,{code:"INVALID_PARAMETER"});if(o&&n.startsWith("$"))throw new a(`"${e}" cannot start with "$".`,{code:"INVALID_PARAMETER"});return n}function Oe(n,e="table.name"){return X(n,e,{allowEmpty:false,maxLength:br,blockKeyDelimiters:true})}function Fe(n,e="tag"){return X(n,e,{allowEmpty:false,maxLength:yr,blockKeyDelimiters:true})}function de(n,e="index.name"){return X(n,e,{allowEmpty:false,maxLength:wr,blockKeyDelimiters:true,disallowLeadingDollar:true})}function St(n,e="index.value"){return X(n,e,{allowEmpty:true,maxLength:Er})}function kt(n){if(!n.record_id&&!n.unique_id)return null;let e={};return n?.service&&(e.service=n.service),n?.owner&&(e.owner=n.owner),n?.record_id?e.record_id=X(n.record_id,"record_id",{allowEmpty:false,onlyAlphanumeric:true}):n?.unique_id&&(e.unique_id=n.unique_id),e}function Me(n){if(n===void 0)return 0;if(typeof n=="number"){if(n>99||n<0)throw new a('"table.access_group" value should be within a range of 0 ~ 99.',{code:"INVALID_REQUEST"})}else if(typeof n=="string"){if(n={private:"private",public:0,authorized:1,admin:99}[n],n===void 0)throw new a('"table.access_group" is invalid.',{code:"INVALID_PARAMETER"})}else throw new a('"table.access_group" should be type: <number | string>.',{code:"INVALID_PARAMETER"});if(!this.__user&&n)throw new a("Unsigned users have no access to records with access group.",{code:"INVALID_REQUEST"});return n}var Ee=4503599627370496;function Re(n){if(typeof n=="number"){if(n>Ee||n<-Ee)throw new a(`Number value should be within range -${Ee} ~ +${Ee}`,{code:"INVALID_PARAMETER"});return n}if(typeof n=="boolean")return n;if(typeof n=="string")return St(n,"index.value");throw new a('"index.value" should be type: <number | boolean | string>.',{code:"INVALID_PARAMETER"})}function xt(n,e){if(!e.index||!("value"in e.index))throw new a('"index.value" is required.',{code:"INVALID_PARAMETER"});if(e.index.name==="$record_id")throw new a(`Cannot do "index.range" on ${e.index.name}`,{code:"INVALID_PARAMETER"});if(typeof e.index.value!=typeof n)throw new a('"index.range" type should match the type of "index.value".',{code:"INVALID_PARAMETER"});return typeof n=="string"?St(n,"index.range"):n}var Ae={};async function ie(n,e){let t={user_id:"",record_id:"",updated:0,uploaded:0,readonly:false,table:{name:"",access_group:0,subscription:{is_subscription_record:false,upload_to_feed:false,notify_subscribers:false,feed_referencing_records:false,notify_referencing_records:false}},referenced_count:0,source:{referencing_limit:null,prevent_multiple_referencing:false,can_remove_referencing_records:false,only_granted_can_reference:false},ip:"",bin:{}},i=false;function r(o){let c=o=="**"?"private":parseInt(o);return c=c==0?"public":c==1?"authorized":c==99?"admin":c,c}let s={ip:o=>{let c=o.split("#"),l=c[0];c.length>1&&(t.unique_id=c[1]),l.slice(-1)==="R"?(t.readonly=true,l=l.slice(0,-1)):t.readonly=false,/^\d{1,3}-\d{1,3}-\d{1,3}-\d{1,3}$/.test(l)&&(l=l.split("-").join("."),i=true),t.ip=l;},rec:o=>{if(!o)return;t.record_id=o;let c=o.substring(0,o.length-9),l=B(c);t.uploaded=l;},usr:o=>{t.user_id=o;},tbl:o=>{if(o&&!t.table.name){let c=o.split("/");t.table.name=c[0],t.table.access_group=r(c[2]),c?.[3]&&(t.table.subscription.is_subscription_record=true);}},usr_tbl:o=>{let c=o.split("/");t.user_id||(t.user_id=c[0]),t.table.name||(t.table.name=c[1],t.table.access_group=r(c[3]),c?.[4]&&(t.table.subscription.is_subscription_record=true));},idx:o=>{if(!o)return;let c=o.split("!"),l=c.splice(0,1)[0],d=Tr("!"+c.join("!"));t.index={name:l,value:d};},ref:o=>{o&&(t.reference=o.split("/")[0]);},tags:o=>{t.tags=o;},upd:o=>{t.updated=o;},acpt_mrf:o=>{t.source.prevent_multiple_referencing=!o;},ref_limt:o=>{t.source.referencing_limit=o;},rfd:o=>{t.referenced_count=o;},bin:async o=>{let c={},l=t?.reference||null;if(Array.isArray(o)){let d=await Promise.all(o.map(async h=>{try{let u=h.split("/").slice(3).join("/"),p=u.split("/");if(p.length<12)return null;let A=decodeURIComponent(p[p.length-1]),f=decodeURIComponent(p[10]),y=p[9],P=p[8],_=r(p[6]),k=h;if(_!=="public")try{k=await Ie.bind(this)(h,{dataType:"endpoint",_ref:l});}catch(T){console.error("Error getting signed url for private file:",T),k=h;}let S={access_group:_,filename:A,url:k,path:u,size:B(y),uploaded:B(P),getFile:(T,L)=>{let q={dataType:T||"download",progress:L,_ref:l,_update:S};return Ie.bind(this)(k,q)}};return {pathKey:f,obj:S}}catch{return null}}));for(let h of d)if(h){if(c[h.pathKey]){c[h.pathKey].push(h.obj);continue}c[h.pathKey]=[h.obj];}}t.bin=c;},prv_acs:o=>{for(let c in o)["notify_subscribers","upload_to_feed","feed_referencing_records","notify_referencing_records"].includes(c)?t.table.subscription[c]=o[c]:t.source[c]=o[c];},data:o=>{let c=o;o==="!D%{}"?c={}:o==="!L%[]"&&(c=[]),t.data=c;}};if(n.record_id)return n;for(let o in s)if(n.hasOwnProperty(o)){let c=s[o](n[o]);c instanceof Promise&&await c;}return i&&(t.user_id="anonymous:"+t.user_id),t}function Tr(n){let e=n.substring(3);switch(n.substring(0,3)){case "!S%":return e;case "!N%":let i=e.split("."),r=Number(i[0])-4503599627370496;return i.length===1?r:parseFloat(r.toString()+"."+i[1]);case "!B%":return e==="1";case "!L%":case "!D%":try{return JSON.parse(e)}catch{throw new a("Value parse error.",{code:"PARSE_ERROR"})}default:return n}}async function vt(n){let{endpoints:e}=n;if(typeof e=="string"&&(e=[e]),!Array.isArray(e))throw new a('"endpoints" should be type: array | string.',{code:"INVALID_PARAMETER"});let t=await R.bind(this)("del-files",{endpoints:e,storage:"records"},{auth:true,method:"post"}),i=[];for(let r in t)i.push(ie.bind(this)(t[r]));return Promise.all(i)}async function Ie(n,e){if(typeof n!="string")throw new a('"url" should be type: string.',{code:"INVALID_PARAMETER"});let t=n.split("?"),i=t.shift()||"",r=t.length?"?"+t.join("?"):"",s=g.Url(i);n=s+r;let o=false,c=s.split("/"),d=c[2].split("."),h=null;d.length===3&&d[1]==="skapi"&&(h=d[0],o=true);let u=c.slice(3),p=false;if(!o&&(u[0]==="auth"||u[0]==="publ"))try{g.UserId(u[2]),g.UserId(u[3]),p=u[0]=="auth",o=!0;}catch{throw new a("Invalid file url.",{code:"INVALID_PARAMETER"})}let A=h?null:u[1];if(e=g.Params(e,{expires:["number",()=>0],dataType:["base64","blob","endpoint","text","info",()=>"download"],progress:"function",_ref:[null,"string"],_update:_=>_}),e?.dataType==="info")return {url:n,filename:u[u.length-1],fileKey:u[u.length-2],access_group:u[6]==="**"?"private":u[6]==="01"?"authorized":u[6]==="00"?"public":parseInt(u[6]),uploader:u[3],record_id:u[4]==="records"?u[5]:"N/A",filesize:B(u[9]),uploaded:B(u[8])};let f=n.split("/").slice(-1)[0],y=e.expires;if(y){if(!o)throw new a("Expires option can only be used on skapi cdn endpoints.",{code:"INVALID_PARAMETER"});if(y<0)throw new a('"config.expires" should be > 0. (seconds)',{code:"INVALID_PARAMETER"});let _={request:h?"get-host":"get",id:h||u[5],key:n,expires:y};A&&(_.service=A),n=(await R.bind(this)("get-signed-url",_,{auth:true})).url;}else if(p){let _=Math.floor(Date.now()/1e3);if(!this.bearerToken&&(!this.session?.idToken?.payload?.exp||this.session.idToken.payload.exp<_)){this.log("getFile:requesting new token",null);try{await F.bind(this)().getSession({refreshToken:!0}),this.log("getFile:received new tokens",{exp:this.session?.idToken?.payload?.exp,currTime:_,expiresIn:this.session?.idToken?.payload?.exp-_,token:this.session?.accessToken?.jwtToken,refreshToken:this.session?.refreshToken?.token});}catch(L){throw this.log("getFile:new token error",L),new a("User login is required.",{code:"INVALID_REQUEST"})}}let k=this.bearerToken||this.session?.idToken?.jwtToken;if(!k||!this.user?.user_id)throw new a("User login is required.",{code:"INVALID_REQUEST"});n+=`${n.includes("?")?"&":"?"}t=${encodeURIComponent(k)}`;let S=u[6]==="**"?"**":parseInt(u[6]),T=this.user?.access_group??-1;if(this.user.user_id!==u[3]&&(S==="**"||T<S)){let L=u[5];if(this.__private_access_key[L]&&typeof this.__private_access_key[L]=="string")n+=`&p=${encodeURIComponent(this.__private_access_key[L])}`;else if(this.owner!==this.host)try{let q=await this.requestPrivateRecordAccessKey({record_id:L,reference_id:e?._ref});n+=`&p=${encodeURIComponent(q)}`;}catch{}}}if(e?.dataType==="endpoint")return e._update&&(e._update.url=n),n;if(e?.dataType==="download"){let _=document.createElement("a");return _.href=n,document.body.appendChild(_),_.setAttribute("download",f),_.target="_blank",_.click(),document.body.removeChild(_),null}return new Promise(async(_,k)=>{try{let S=await R.bind(this)(n,null,{method:"get",contentType:null,responseType:e?.dataType==="text"?"text":"blob",fetchOptions:{progress:e?.progress}},{ignoreService:!0});if(e?.dataType==="base64"){let T=new FileReader;T.onloadend=()=>_(T.result),T.readAsDataURL(S);}else _(S);}catch(S){k(S);}})}async function Dt(n,e=false){n=D(n,{ignoreEmpty:true}).data||{};let t="",i=kt(n);if(i)n=i,t=n.record_id||n.unique_id,typeof t=="string"&&(typeof this.__private_access_key?.[t]=="string"&&(n.private_key=this.__private_access_key?.[t]||void 0),this.__my_unique_ids[t]&&(e?delete this.__my_unique_ids[t]:n.record_id=this.__my_unique_ids[t]));else {let r=await M.bind(this)(),s=n?.reference,o=false;typeof s=="object"&&Object.keys(s).length&&(s?.record_id||s?.unique_id?(t=s.record_id||s.unique_id,t&&typeof this.__private_access_key?.[t]=="string"&&(n.private_key=this.__private_access_key?.[t]||void 0),n.reference=t):s?.user_id&&(o=s.user_id===this.user?.user_id,n.reference=s.user_id)),typeof n?.table=="string"&&(n.table={name:n.table,access_group:0}),n.index&&n.index.hasOwnProperty("range")&&n.index.hasOwnProperty("condition")&&delete n.index.range;let c=l=>({table:{name:d=>Oe(d,"table.name"),access_group:Me.bind(this),subscription:d=>g.UserId(d,'User ID in "subscription"')},reference:"string",index:{name:["$updated","$uploaded","$referenced_count","$user_id",d=>de(d,"index.name")],value:d=>{let h={$updated:"number",$uploaded:"number",$referenced_count:"number",$user_id:g.UserId};if(h.hasOwnProperty(l.index.name)){let u=h[l.index.name];if(typeof u=="function")return u(d);if(u!==typeof d)throw new a(`"index.value" should be type: ${u}.`,{code:"INVALID_PARAMETER"});return d}return typeof d=="string"&&!d?"":Re(d)},condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq"],range:d=>xt(d,l)},tag:d=>{if(d==null)return d;if(typeof d=="string")return Fe(d,"tag");throw new a('"tag" should be type: string.',{code:"INVALID_PARAMETER"})},private_key:"string"});n=g.Params(n||{},c(n),o||r?[]:["table"],{ignoreEmpty:true});}return {query:n,is_reference_fetch:t}}async function Ut(n,e){await this.__connection;let t=await Dt.bind(this)(n),i=t.is_reference_fetch,r=await R.bind(this)("get-records",t.query,{fetchOptions:e,auth:!!this.__user,method:this.__user?"post":"get"});i&&r?.reference_private_key&&typeof r.reference_private_key=="string"&&(this.__private_access_key[i]=r.reference_private_key);let s=[];for(let o in r.list)s.push(ie.bind(this)(r.list[o]));return r.list=await Promise.all(s),r}function Nt(n){let e="",t=[],i=g.Params(n||{},{record_id:s=>X(s,"record_id",{allowEmpty:false,onlyAlphanumeric:true}),unique_id:"string",readonly:"boolean",table:{name:s=>Oe(s,"table.name"),subscription:{is_subscription_record:"boolean",upload_to_feed:"boolean",notify_subscribers:"boolean",feed_referencing_records:"boolean",notify_referencing_records:"boolean"},access_group:Me.bind(this)},source:{referencing_limit:s=>{if(s===null)return null;if(typeof s=="number"){if(0>s)throw new a('"reference_limit" should be >= 0',{code:"INVALID_PARAMETER"});if(s>4503599627370546)throw new a('"reference_limit" should be <= 4503599627370546',{code:"INVALID_PARAMETER"});return s}throw new a('"reference_limit" should be type: <number | null>',{code:"INVALID_PARAMETER"})},prevent_multiple_referencing:"boolean",can_remove_referencing_records:"boolean",only_granted_can_reference:"boolean",allow_granted_to_grant_others:"boolean",referencing_index_restrictions:s=>{if(s===void 0)return;if(!s||Array.isArray(s)&&!s.length)return null;let o={name:l=>de(l,'"name" in "index_restrictions"'),value:l=>Re(l),condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne",()=>null],range:l=>{if(l!==null&&typeof s.value!=typeof l)throw new a('Index restriction "range" type should match the type of "value".',{code:"INVALID_PARAMETER"});if(!s.hasOwnProperty("value"))throw new a('Index restriction "value" is required.',{code:"INVALID_PARAMETER"});return l}};Array.isArray(s)||(s=[s]);let c=s.map(l=>g.Params(l,o,["name"]));if(c.length)for(let l of c)l.condition&&l.hasOwnProperty("range")&&delete l.range;return c}},reference:s=>{if(s===null)return {record_id:null};if(s){if(typeof s=="string")return e=s,this.__my_unique_ids[s]?this.__my_unique_ids[s]:s;if(typeof s!="object")throw new a('"reference" should be type: <string | object>.',{code:"INVALID_PARAMETER"});return g.Params(s,{unique_id:"string",record_id:o=>o==null?o:(e=o,typeof this.__private_access_key?.[o]=="string"&&(n.reference_private_key=this.__private_access_key[o]||void 0),X(o,"reference.record_id",{allowEmpty:false,onlyAlphanumeric:true}))})}},index:{name:s=>de(s,"index.name"),value:s=>Re(s)},tags:s=>{if(s==null)return s;if(typeof s=="string"&&(s=s.split(",").map(o=>o.trim())),!Array.isArray(s))throw new a('"tag" should be type: <string | string[]>.',{code:"INVALID_PARAMETER"});return s.map(o=>Fe(o,"tag"))},remove_bin:s=>{if(!s)return null;let o=[];if(Array.isArray(s))for(let c of s)if(typeof c=="string")o.push(decodeURIComponent(c.split("?")[0]));else if(c.url&&c.size&&c.filename){let d=c.url.split("/").slice(0,3).join("/")+"/"+c.path;o.push(d);}else throw new a('"remove_bin" should be type: <string[] | BinaryFile[] | null>',{code:"INVALID_PARAMETER"});else throw new a('"remove_bin" should be type: <string[] | BinaryFile[] | null>',{code:"INVALID_PARAMETER"});return o},progress:"function",data:s=>s},[],{precall:s=>{let o=s?.data||{};if(!o?.record_id&&!o.table)throw new a('"table.name" is required.',{code:"INVALID_PARAMETER"});typeof o.table=="string"&&(o.table={name:o.table,access_group:0}),s.files&&(t=s.files);}}),r=n.progress||null;if(delete i.progress,!this.__user){let s=!!(i.table?.subscription?.is_subscription_record||i.table?.subscription?.upload_to_feed||i.table?.subscription?.notify_subscribers||i.table?.subscription?.feed_referencing_records||i.table?.subscription?.notify_referencing_records);if(i.record_id)throw new a("Public users cannot update existing records.",{code:"INVALID_REQUEST"});if(i.table.access_group!=="public"&&i.table.access_group!==0)throw new a("Public users can only post records to public tables.",{code:"INVALID_REQUEST"});if(s)throw new a("Public users cannot post subscription records.",{code:"INVALID_REQUEST"});if(i.remove_bin)throw new a("Public users cannot remove files from records.",{code:"INVALID_REQUEST"});if(i.unique_id)throw new a("Public users cannot set unique_id for records.",{code:"INVALID_REQUEST"})}return {config:i,progress:r,is_reference_post:e,files:t}}async function Ct(n){if(await this.__connection,!Array.isArray(n)||!n.length)throw new a('"params" should be a non-empty array.',{code:"INVALID_PARAMETER"});!this.__user;let t=[],i,r,s=null,c={_is_bulk_:n.map((p,A)=>{if(!p||typeof p!="object"||Array.isArray(p))throw new a(`"params[${A}]" should be type: <object>.`,{code:"INVALID_PARAMETER"});let f=Nt.bind(this)(p),y=f.config;if(f.is_reference_post&&t.push(f.is_reference_post),typeof y.progress=="function"&&s===null&&(s=y.progress),y.service!==void 0){if(i===void 0)i=y.service;else if(i!==y.service)throw new a('All bulk params should share the same "service" value.',{code:"INVALID_PARAMETER"})}if(y.owner!==void 0){if(r===void 0)r=y.owner;else if(r!==y.owner)throw new a('All bulk params should share the same "owner" value.',{code:"INVALID_PARAMETER"})}return delete y.progress,delete y.service,delete y.owner,y}),service:"",owner:""};i!==void 0&&(c.service=i),r!==void 0&&(c.owner=r);let l={auth:!!this.__user,method:"post"},d={};Object.keys(d).length&&Object.assign(l,{fetchOptions:d});let h=await R.bind(this)("post-record",c,l),u=await Promise.all(h.map(p=>ie.bind(this)(p,"called from postRecord")));for(let p=0;p<h.length;p++){let A=h[p],f=u[p];if(typeof A?.reference_private_key=="string")for(let y of t)this.__private_access_key[y]=A.reference_private_key;f?.unique_id&&(this.__my_unique_ids[f.unique_id]=f.record_id);}return u}async function Lt(n,e,t){if(await this.__connection,!e)throw new a('"config" argument is required.',{code:"INVALID_PARAMETER"});let i=Nt.bind(this)(e),r=i.config,s=i.progress,o=i.is_reference_post,c={auth:!!this.__user,method:"post"},l=[],d=D(n);t&&Array.isArray(t)&&t.length&&(l=l.concat(t)),d.files&&Array.isArray(d.files)&&d.files.length&&(l=l.concat(d.files));let h=null;h=Object.assign({data:d.data},r);let u={};typeof s=="function"&&(u.progress=s),Object.keys(u).length&&Object.assign(c,{fetchOptions:u});let p=await R.bind(this)("post-record",h,c);if($()&&l.length){let f=new FormData;for(let _ of l)f.append(_.name,_.file,_.file.name);let y={record_id:p.rec,progress:s};r.hasOwnProperty("service")&&(y.service=r.service);let{bin_endpoints:P}=await we.bind(this)(f,y);p.bin?p.bin.push(...P):p.bin=P;}o&&typeof p?.reference_private_key=="string"&&(this.__private_access_key[o]=p.reference_private_key);let A=await ie.bind(this)(p,"called from postRecord");return A.unique_id&&(this.__my_unique_ids[A.unique_id]=A.record_id,$()&&window.sessionStorage.setItem(`${this.service}:uniqueids`,JSON.stringify(this.__my_unique_ids))),A}async function Ot(n,e){let t=await R.bind(this)("get-table",g.Params(n||{},{table:"string",condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}),Object.assign({auth:!!this.__user},{fetchOptions:e})),i={cnt_rec:"number_of_records",tbl:"table",srvc:"service"};if(Array.isArray(t?.list))for(let r of t.list)for(let s in i)r.hasOwnProperty(s)&&(r[i[s]]=r[s],delete r[s]);return t}async function Ft(n,e){if(!n?.table)throw new a('"table" is required.',{code:"INVALID_PARAMETER"});let t=g.Params(n||{},{table:"string",index:s=>de(s,"index.name"),order:{by:["average_number","total_number","number_count","average_bool","total_bool","bool_count","string_count","index_name","number_of_records"],value:["string","number","boolean"],condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}},["table"]);if(t.hasOwnProperty("order")){if(!t.order?.by)throw new a('"order.by" is required.',{code:"INVALID_PARAMETER"});if(t.order.hasOwnProperty("condition")&&!t.order.hasOwnProperty("value"))throw new a('"value" is required for "condition".',{code:"INVALID_PARAMETER"});if(t.hasOwnProperty("index")&&t.index.substring(t.index.length-1)!==".")throw new a('"index" should be a parent index name of the compound index when using "order.by"',{code:"INVALID_PARAMETER"})}let i=await R.bind(this)("get-index",t,Object.assign({auth:!!this.__user},{fetchOptions:e})),r={cnt_bool:"boolean_count",cnt_numb:"number_count",totl_numb:"total_number",totl_bool:"total_bool",avrg_numb:"average_number",avrg_bool:"average_bool",cnt_str:"string_count"};return Array.isArray(i?.list)&&(i.list=i.list.map(s=>{let o=s.idx.split("/"),c={table:o[1],index:o[2],number_of_records:s.cnt_rec};for(let l in r)Object.prototype.hasOwnProperty.call(s,l)&&(c[r[l]]=s[l]);return c})),i}async function Mt(n,e){let t=await R.bind(this)("get-tag",g.Params(n||{},{table:"string",tag:"string",condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}),Object.assign({auth:!!this.__user},{fetchOptions:e}));return Array.isArray(t?.list)&&(t.list=t.list.map(i=>{let r=i.tag.split("/");return {table:r[1],tag:r[0],number_of_records:i.cnt_rec}})),t}async function Vt(n,e){let t=await R.bind(this)("get-uniqueid",g.Params(n||{},{unique_id:"string",condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}),Object.assign({auth:!!this.__user},{fetchOptions:e}));if(Array.isArray(t?.list))for(let i in t.list){let r=t.list[i];t.list[i]={unique_id:r.unq,record_id:r.rec};}return t}async function $t(n,e){await this.__connection;let t=await Dt.bind(this)(n,true),i=t.is_reference_fetch,r=await R.bind(this)("del-records",t.query,{auth:true,fetchOptions:e});return i&&typeof r?.reference_private_key=="string"&&(this.__private_access_key[i]=r.reference_private_key),r?.message||r}function qt(n){return Qt.bind(this)({record_id:n.record_id,user_id:n.user_id,execute:"add"})}function jt(n){return Qt.bind(this)({record_id:n.record_id,user_id:n.user_id||null,execute:"remove"})}async function Bt(n,e){let t={record_id:n.record_id||void 0,user_id:n.user_id||void 0,execute:"list"};if(!t.record_id&&!t.user_id)throw new a("Either record_id or user_id must be provided.",{code:"INVALID_PARAMETER"});if(t.user_id)if(typeof t.user_id=="string")g.UserId(t.user_id),t.user_id=[t.user_id];else if(Array.isArray(t.user_id))for(let s of t.user_id)g.UserId(s);else throw new a("user_id should be type: <string | string[]>",{code:"INVALID_PARAMETER"});let i=s=>(s.rec_usr?(s.record_id=s.rec_usr.split("/")[0],s.user_id=s.rec_usr.split("/")[1]):s.usr_rec&&(s.user_id=s.usr_rec.split("/")[0],s.record_id=s.usr_rec.split("/")[1]),s),r=await R.bind(this)("grant-private-access",t,{auth:true,fetchOptions:e});return r.list=r.list.map(i),r}function Kt(n){let e=n.record_id,t=n.reference_id||void 0;if(!e)throw new a("Record ID is required.",{code:"INVALID_PARAMETER"});if(typeof e!="string")throw new a("Record ID should be type: <string | string[]>",{code:"INVALID_PARAMETER"});if(t&&typeof t!="string")throw new a("Reference ID should be type: <string>",{code:"INVALID_PARAMETER"});if(typeof this.__private_access_key[e]=="string")return Promise.resolve(this.__private_access_key[e]);if(Ae[e])return Ae[e];let i=R.bind(this)("request-private-access-key",{record_id:e,reference_id:t},{auth:true}).then(r=>{let s=typeof r=="string"?r:r?.private_key;if(typeof s!="string")throw new a("Invalid private access key response.",{code:"ERROR"});return this.__private_access_key[e]=s,s}).finally(()=>{delete Ae[e];});return Ae[e]=i,i}function Qt(n){n.execute;let t=g.Params(n,{record_id:"string",user_id:i=>{if(!i)throw new a("User ID is required.",{code:"INVALID_PARAMETER"});let r=i;if(typeof r=="string"&&(r=[r]),r.length>100)throw new a("Cannot process more than 100 users at once.",{code:"INVALID_REQUEST"});for(let s of r)g.UserId(s,'User ID in "user_id"');return r},execute:["add","remove"]},["execute","record_id","user_id"]);return t.user_id||(t.user_id=null),R.bind(this)("grant-private-access",t,{auth:true})}var I={},C={},K={},H={},W={},Te={},Pe={};function Wt(n,e,t){n[e]||(n[e]=[]),n[e].push(t);}async function Se(n,e,t){let i=[];if(n[e]){for(let r of n[e])if(r){let s=t(r);s instanceof Promise&&(s=await s),i.push(s);}delete n[e];}return i}async function $e(n,e){if(!this?.session?.accessToken?.jwtToken)throw new a("Access token is required.",{code:"INVALID_PARAMETER"});let t=await this.__socket;async function i(r,s,o){this.log("answerSdpOffer from",s),await I[s].setRemoteDescription(new RTCSessionDescription(r));let c=await I[s].createAnswer();await I[s].setLocalDescription(c),o.send(JSON.stringify({action:"rtc",uid:s,content:{sdpanswer:c},token:this.session.accessToken.jwtToken}));}I?.[e]?n?(await Se(Pe,e,r=>i.bind(this)(r,e,t)),await i.bind(this)(n,e,t)):await Se(Pe,e,r=>i.bind(this)(r,e,t)):n&&Wt(Pe,e,n);}async function qe(n,e){if(this.log("receiveIceCandidate",n),I?.[e]&&I[e]?.remoteDescription&&I[e]?.remoteDescription?.type){if(!n)return Se(Te,e,t=>I[e].addIceCandidate(t));await Se(Te,e,t=>I[e].addIceCandidate(t)),await I[e].addIceCandidate(n);}else Wt(Te,e,n);}async function Q(n){if(typeof window>"u"||window._runningInNodeJS)throw new a("WebRTC is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});g.Params(n,{cid:s=>{if(typeof s!="string")throw new a('"cid" should be type: <string>.',{code:"INVALID_PARAMETER"});if(s&&s.slice(0,4)!=="cid:")throw new a('"cid" should be a valid connection id.',{code:"INVALID_PARAMETER"});return s},close:"boolean"});let e=await this.__socket,{cid:t,close_all:i=false}=n||{};if(!i&&!t)throw new a('"cid" is required.',{code:"INVALID_PARAMETER"});let r=s=>{if(!s)throw new a('"cid" is required.',{code:"INVALID_PARAMETER"});if(delete Pe[s],delete Te[s],C[s]&&Object.values(C[s]).forEach(o=>{o.readyState!=="closed"&&o.close();}),delete C[s],I?.[s]){I[s].connectionState!=="closed"&&(I[s].close(),e.send(JSON.stringify({action:"rtc",uid:s,content:{hungup:this.user.user_id},token:this.session.accessToken.jwtToken})));let o={type:"connectionstatechange",target:I[s],timestamp:new Date().toISOString(),state:I[s].connectionState,iceState:I[s].iceConnectionState,signalingState:I[s].signalingState};W[s]&&W[s](o),this.log("closeRTC",o);}delete W[s],delete H[s],delete K[s],delete I[s];};if(i)for(let s in I)r(s);else r(t);this.log("Cleaning up media stream..."),this.__mediaStream&&(this.__mediaStream.getTracks().forEach(s=>{s.stop();}),this.__mediaStream=null);}async function Ht(n){if(n instanceof MediaStream)return n;if(!n.video&&!n.audio){let e=new MediaStream,t=document.createElement("canvas");t.width=1,t.height=1;let r=t.captureStream().getVideoTracks()[0];return e.addTrack(r),e}return window.navigator.mediaDevices.getUserMedia(n)}async function Jt(n,e){if(typeof window>"u"||window._runningInNodeJS)throw new a("WebRTC is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(typeof e!="function")throw new a("Callback is required.",{code:"INVALID_PARAMETER"});if(!this?.session?.accessToken?.jwtToken)throw new a("Access token is required.",{code:"INVALID_PARAMETER"});n=g.Params(n,{cid:o=>{if(typeof o!="string")throw new a('"cid" should be type: <string>.',{code:"INVALID_PARAMETER"});if(o&&o.slice(0,4)!=="cid:")throw new a('"cid" should be a valid connection id.',{code:"INVALID_PARAMETER"});return o},ice:["string",()=>"stun:stun.skapi.com:3468"],media:o=>o,channels:["text-chat","file-transfer","video-chat","voice-chat","gaming",{ordered:"boolean",maxPacketLifeTime:"number",maxRetransmits:"number",protocol:"string"},()=>[{ordered:true,maxPacketLifeTime:10,protocol:"default"}]]},["cid"]);let{cid:t,ice:i}=n;if(!(n?.media instanceof MediaStream)&&(n?.media?.video||n?.media?.audio)&&window.location.hostname!=="localhost"&&window.location.protocol!=="https:")throw new a("Media stream is only supported on either localhost or https.",{code:"INVALID_REQUEST"});let r=this.__socket?await this.__socket:this.__socket;if(!r)throw new a("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});if(r.readyState!==1)throw new a("Realtime connection is not ready.",{code:"INVALID_REQUEST"});let s={iceServers:[{urls:i}]};I?.[t]||(I[t]=new RTCPeerConnection(s)),n?.media&&(this.__mediaStream=await Ht(n.media),this.__mediaStream.getTracks().forEach(o=>{I[t].addTrack(o,this.__mediaStream);})),W[t]=e,C[t]||(C[t]={});for(let o=0;o<n.channels.length;o++){let c=n.channels[o];if(typeof c=="string")switch(c){case "text-chat":c={ordered:true,maxRetransmits:10,protocol:"text-chat"};break;case "file-transfer":c={ordered:false,maxPacketLifeTime:3e3,protocol:"file-transfer"};break;case "video-chat":c={ordered:true,maxRetransmits:10,protocol:"video-chat"};break;case "voice-chat":c={ordered:true,maxRetransmits:10,protocol:"voice-chat"};break;case "gaming":c={ordered:false,maxPacketLifeTime:100,protocol:"gaming"};break;default:c={ordered:true,maxRetransmits:10,protocol:"default"};break}let l=c.protocol||"default";if(Object.keys(C[t]).includes(l))throw new a(`Data channel with the protocol "${l}" already exists.`,{code:"INVALID_REQUEST"});let d=I[t].createDataChannel(l,c);C[t][l]=d;}for(let o in C[t]){let c=C[t][o];Xt.bind(this)(t,c);}return Gt.bind(this)(t,["onnegotiationneeded"]),await Ve.bind(this)(t),{hangup:()=>K[t]&&K[t](false),connection:new Promise(o=>{K[t]=(c=>{if(this.log("receiver picked up the call",t),!c)return Q.bind(this)({cid:t}),null;I[t].onnegotiationneeded=()=>{this.log("onnegotiationneeded",`sending offer to "${t}".`),Ve.bind(this)(t),W[t]&&W[t]({type:"negotiationneeded",target:I[t],timestamp:new Date().toISOString(),signalingState:I[t].signalingState,connectionState:I[t].iceConnectionState,gatheringState:I[t].iceGatheringState});},o({target:I[t],channels:C[t],hangup:()=>Q.bind(this)({cid:t}),media:this.__mediaStream});}).bind(this);})}}function zt(n){return async(e,t)=>{e=e||{},e=D(e).data;let i=n.sender_cid,r=await this.__socket;if(!H[i])return null;if(typeof t!="function")throw new a("Callback is required.",{code:"INVALID_PARAMETER"});if(!(e?.media instanceof MediaStream)&&(e?.media?.video||e?.media?.audio)&&window.location.hostname!=="localhost"&&window.location.protocol!=="https:")throw new a("Media stream is only supported on either localhost or https.",{code:"INVALID_REQUEST"});let{ice:s="stun:stun.skapi.com:3468"}=e;return I?.[i]||(I[i]=new RTCPeerConnection({iceServers:[{urls:s}]})),e?.media&&(this.__mediaStream=await Ht(e.media),this.__mediaStream.getTracks().forEach(o=>{I[i].addTrack(o,this.__mediaStream);})),delete H[i],W[i]=t,C[i]||(C[i]={}),I[i].ondatachannel=o=>{this.log("ondatachannel",`received data channel "${o.channel.label}".`);let c=o.channel;C[i][c.label]=c,Xt.bind(this)(i,c);},Gt.bind(this)(i,["onnegotiationneeded"]),await $e.bind(this)(null,i),await qe.bind(this)(null,i),r.send(JSON.stringify({action:"rtc",uid:i,content:{pickup:this.user.user_id},token:this.session.accessToken.jwtToken})),{target:I[i],channels:C[i],hangup:()=>Q.bind(this)({cid:i}),media:this.__mediaStream}}}async function Ve(n){if(!this?.session?.accessToken?.jwtToken)throw new a("Access token is required.",{code:"INVALID_PARAMETER"});this.log("sendOffer",n);let e=await this.__socket,t=await I[n].createOffer();await I[n].setLocalDescription(t);let i=I[n].localDescription;this.log("rtcSdpOffer to",i),e.send(JSON.stringify({action:"rtc",uid:n,content:{sdpoffer:i},token:this.session.accessToken.jwtToken}));}async function Pr(n,e){if(!this?.session?.accessToken?.jwtToken)throw new a("Access token is required.",{code:"INVALID_PARAMETER"});this.log("sendIceCandidate to",e);let t=await this.__socket;if(!n.candidate){this.log("candidate-end","all ice candidates have been sent");return}let i=W[e]||(()=>{}),r=n.candidate;this.log("ice gathering state set to",I[e].iceGatheringState),i({type:"icecandidate",target:I[e],timestamp:new Date().toISOString(),candidate:n.candidate.candidate,sdpMid:n.candidate.sdpMid,sdpMLineIndex:n.candidate.sdpMLineIndex,usernameFragment:n.candidate.usernameFragment,protocol:n.candidate.protocol,gatheringState:I[e].iceGatheringState,connectionState:I[e].iceConnectionState}),t.send(JSON.stringify({action:"rtc",uid:e,content:{candidate:r},token:this.session.accessToken.jwtToken}));}function Gt(n,e){let t=new Set(e),i=W[n]||(o=>{}),r=I[n],s={ontrack:o=>{i({type:"track",target:r,timeStamp:o.timeStamp,streams:o.streams,track:o.track});},onicecandidate:o=>{Pr.bind(this)(o,n),o.candidate?i({type:"icecandidate",target:r,timestamp:new Date().toISOString(),candidate:o.candidate.candidate,sdpMid:o.candidate.sdpMid,sdpMLineIndex:o.candidate.sdpMLineIndex,usernameFragment:o.candidate.usernameFragment,protocol:o.candidate.protocol,gatheringState:r.iceGatheringState,connectionState:r.iceConnectionState}):i({type:"icecandidateend",target:r,timestamp:new Date().toISOString()});},onicecandidateerror:o=>{i({type:"icecandidateerror",target:r,timestamp:new Date().toISOString(),errorCode:o.errorCode,errorText:o.errorText,url:o.url,hostCandidate:o.hostCandidate,gatheringState:r.iceGatheringState,connectionState:r.iceConnectionState});},oniceconnectionstatechange:()=>{i({type:"iceconnectionstatechange",target:r,timestamp:new Date().toISOString(),state:r.iceConnectionState,gatheringState:r.iceGatheringState,signalingState:r.signalingState});},onicegatheringstatechange:()=>{i({type:"icegatheringstatechange",target:r,timestamp:new Date().toISOString(),state:r.iceGatheringState,connectionState:r.iceConnectionState,signalingState:r.signalingState});},onsignalingstatechange:()=>{i({type:"signalingstatechange",target:r,timestamp:new Date().toISOString(),state:r.signalingState,connectionState:r.iceConnectionState,gatheringState:r.iceGatheringState});},onnegotiationneeded:()=>{Ve.bind(this)(n),i({type:"negotiationneeded",target:r,timestamp:new Date().toISOString(),signalingState:r.signalingState,connectionState:r.iceConnectionState,gatheringState:r.iceGatheringState});},onconnectionstatechange:()=>{i({type:"connectionstatechange",target:r,timestamp:new Date().toISOString(),state:r.connectionState,iceState:r.iceConnectionState,signalingState:r.signalingState});let o=r.connectionState;(o==="disconnected"||o==="failed"||o==="closed")&&Q.bind(this)({cid:n});}};for(let[o,c]of Object.entries(s))t.has(o)||(r[o]=c);}function Xt(n,e,t){let i=new Set(t),r=W[n]||(o=>{}),s={onmessage:o=>{let c={type:o.type,target:e,timeStamp:o.timeStamp,data:o.data,lastEventId:o.lastEventId,origin:o.origin,readyState:e.readyState,bufferedAmount:e.bufferedAmount};this.log(`${e.label}: message`,o.data),r(c);},onerror:o=>{let c={type:o.type,target:e,timeStamp:o.timeStamp,error:o.error.message,errorCode:o.error.errorDetail,readyState:e.readyState,label:e.label};this.log(`${e.label}: error`,o.error.message),r(c);},onclose:o=>{let c={type:o.type,target:e,timeStamp:o.timeStamp,readyState:e.readyState,label:e.label,id:e.id};this.log(`${e.label}: closed`,null),r(c),C[n]&&(delete C[n][e.label],Object.keys(C[n]).length===0&&Q.bind(this)({cid:n}));},onbufferedamountlow:o=>{let c={target:e,bufferedAmount:e.bufferedAmount,bufferedAmountLowThreshold:e.bufferedAmountLowThreshold,type:o.type,timeStamp:o.timeStamp};this.log(`${e.label}: bufferedamountlow`,e.bufferedAmount),r(c);},onopen:o=>{this.log("dataChannel",`data channel: "${e.label}" is open and ready to send messages.`);let c={type:o.type,target:e,timeStamp:o.timeStamp,readyState:e.readyState,label:e.label,id:e.id,ordered:e.ordered,maxRetransmits:e.maxRetransmits,protocol:e.protocol};r(c);}};for(let[o,c]of Object.entries(s))i.has(o)||(e[o]=c);}var Y,Z=null,ge=true,se=0;async function Sr(){if(typeof window>"u"||window._runningInNodeJS)throw new a("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.getProfile(),!this.session)throw new a("No access.",{code:"INVALID_REQUEST"});let n=await this.record_endpoint;return new WebSocket(n.websocket_private+"?token="+this.session.accessToken.jwtToken)}var je=null;async function Zt(){if(typeof window>"u"||window._runningInNodeJS)throw new a("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});ge=true;let n=this.__socket?await this.__socket:this.__socket;Q.bind(this)({close_all:true}),Y&&Be.bind(this)({group:null}),se=0,Z&&(Z.terminate(),Z=null);try{n&&n.close();}catch{}return window.removeEventListener("visibilitychange",je),this.__socket=null,null}async function ke(n,e=50,t){if(typeof window>"u"||window._runningInNodeJS)throw new a("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(typeof n!="function")throw new a("Callback must be a function.",{code:"INVALID_REQUEST"});if(t==="reconnect"){if(this.__socket instanceof Promise){let i=await this.__socket;if(i.readyState!==WebSocket.CLOSED&&i.readyState!==WebSocket.CLOSING)return this.__socket}}else if(ge&&(je=()=>{!document.hidden&&!ge&&ke.bind(this)(n,0,"reconnect");},this.__socket instanceof Promise))return this.__socket;Z&&(Z.terminate(),Z=null),this.__socket=new Promise(async i=>{await ne.bind(this)(),setTimeout(async()=>{let r=await Sr.bind(this)();r.onopen=()=>{ge=false,se=0,t!=="reconnect"&&window.addEventListener("visibilitychange",je),this.log("realtime onopen","Connected to WebSocket server."),n({type:"success",message:"Connected to WebSocket server."}),Y&&r.send(JSON.stringify({action:"joinRoom",rid:Y,token:this.session.accessToken.jwtToken}));let s=`
207
207
  let interval = 15000; // Set interval time 15 seconds
208
208
 
209
209
  function runInterval() {
@@ -212,9 +212,9 @@ var $n=Object.defineProperty;var qn=Object.getOwnPropertyDescriptor;var Y=(n=>ty
212
212
  }
213
213
 
214
214
  runInterval(); // Start interval
215
- `,o=new Blob([s],{type:"application/javascript"});X=new Worker(URL.createObjectURL(o)),X.onmessage=c=>{r.readyState===1&&r.send(JSON.stringify({action:"keepAlive"}));},i(r);},r.onmessage=async s=>{let o="";try{o=JSON.parse(decodeURI(s.data)),this.log("socket onmessage",o);}catch{return}let c;switch(true){case !!o?.["#message"]:c="message";break;case !!o?.["#private"]:c="private";break;case !!o?.["#notice"]:c="notice";break;case !!o?.["#rtc"]:c="rtc";break;case !!o?.["#error"]:c="error";break}if(!c)return;let u={type:c,message:o?.["#rtc"]||o?.["#message"]||o?.["#private"]||o?.["#notice"]||o?.["#error"]||null,sender:o?.["#user_id"]||null,sender_cid:o?.["#scid"]?"cid:"+o["#scid"]:null,sender_rid:o?.["#srid"]||null,code:o?.["#code"]||null};if(c==="notice")n(u);else if(c==="rtc"){if(u.sender!==this.user.user_id){let d=u.message;if(d.hungup){K[u.sender_cid]&&(K[u.sender_cid](false),delete K[u.sender_cid]),H[u.sender_cid]&&delete H[u.sender_cid],I?.[u.sender_cid]&&Q.bind(this)({cid:u.sender_cid}),u.type="rtc:closed",n(u);return}if(d.candidate&&je.bind(this)(d.candidate,u.sender_cid),d.sdpoffer&&(qe.bind(this)(d.sdpoffer,u.sender_cid),H[u.sender_cid]||(H[u.sender_cid]=u.sender_cid,delete u.message,u.connectRTC=nn.bind(this)(u),u.type="rtc:incoming",u.hangup=(()=>{I[u.sender_cid]?Q.bind(this)({cid:u.sender_cid}):H[u.sender_cid]&&(delete H[u.sender_cid],r.send(JSON.stringify({action:"rtc",uid:u.sender_cid,content:{hungup:this.user.user_id},token:this.session.accessToken.jwtToken})));}).bind(this),n(u))),d.pickup&&K[u.sender_cid]&&(K[u.sender_cid](true),delete K[u.sender_cid]),d.sdpanswer&&I[u.sender_cid])if(I[u.sender_cid].signalingState==="have-local-offer")await I[u.sender_cid].setRemoteDescription(new RTCSessionDescription(d.sdpanswer));else throw new a("Invalid signaling state.",{code:"INVALID_REQUEST"})}}else n(u);},r.onclose=()=>{ge?(this.log("realtime onclose","WebSocket connection closed."),n({type:"close",message:"WebSocket connection closed."})):(this.log("realtime onclose","WebSocket unexpected close."),n({type:"error",message:"Skapi: WebSocket unexpected close."}),se++,se<3?(this.log("realtime onclose","Reconnecting to WebSocket server..."+se),n({type:"reconnect",message:"Reconnecting to WebSocket server..."+se}),ke.bind(this)(n,3e3,"reconnect")):(this.log("realtime onclose","Max reconnection attempts reached."),n({type:"error",message:"Skapi: Max reconnection attempts reached."})));},r.onerror=()=>{this.log("realtime onerror","WebSocket connection error."),n({type:"error",message:"Skapi: WebSocket connection error."});};},e);});}async function an(n,e,t){if(typeof window>"u"||window._runningInNodeJS)throw new a("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});let i=this.__socket?await this.__socket:this.__socket;if(!i)throw new a("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});if(!e)throw new a("No recipient.",{code:"INVALID_REQUEST"});await ne.bind(this)(),n=D(n).data;let r="";if(t&&(t=g.Params(t,{config:{always:"boolean"},title:"string",body:"string"},["title","body"]),r=JSON.stringify({title:t.title,body:t.body}),new Blob([r]).size>3072))throw new a("Notification size exceeds 3kb.",{code:"INVALID_PARAMETER"});if(i.readyState===1){try{g.UserId(e),i.send(JSON.stringify({action:"sendMessage",uid:e,content:n,notification:r,notificationConfig:t?.config||{},token:`IdT:${this.service}:${this.owner}:`+(this.bearerToken||this.session?.idToken?.jwtToken||"null")}));}catch(s){if(this.log("postRealtime:err",{err:s}),Z!==e)throw new a(`User has not joined to the recipient group. Run joinRealtime({ group: "${e}" })`,{code:"INVALID_REQUEST"});i.send(JSON.stringify({action:"broadcast",rid:e,content:n,notification:r,notificationConfig:t?.config||{},token:`IdT:${this.service}:${this.owner}:`+(this.bearerToken||this.session?.idToken?.jwtToken||"null")}));}return {type:"success",message:"Message sent."}}throw new a("Realtime connection is not open. Try reconnecting with connectRealtime().",{code:"INVALID_REQUEST"})}async function Ke(n){if(typeof window>"u"||window._runningInNodeJS)throw new a("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});let e=this.__socket?await this.__socket:this.__socket;if(!e)throw new a("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});await ne.bind(this)(),n=D(n,{nullIfEmpty:true}).data;let{group:t=null}=n;if(!t&&!Z)return {type:"success",message:"Left realtime message group."};if(t!==null&&typeof t!="string")throw new a('"group" must be a string | null.',{code:"INVALID_PARAMETER"});return e.send(JSON.stringify({action:"joinRoom",rid:t,token:this.session.accessToken.jwtToken})),Z=t,{type:"success",message:t?`Joined realtime message group: "${t}".`:"Left realtime message group."}}async function cn(n,e){n=g.Params(n,{user_id:i=>g.UserId(i,'User ID in "user_id"'),group:["string",()=>{if(!Z)throw new a('No group has been joined. Otherwise "group" is required.',{code:"INVALID_REQUEST"});return Z}]});let t=await w.bind(this)("get-ws-group",n,{fetchOptions:e,auth:true,method:"post"});return t.list=t.list.map(i=>({user_id:i.uid.split("#")[1],cid:"cid:"+i.cid})),t}async function ln(n,e){if(await this.__connection,n||(n={searchFor:"group",value:" ",condition:">"}),n=g.Params(n,{searchFor:["group","number_of_users",()=>"group"],value:["string","number",()=>n?.searchFor&&n?.searchFor==="number_of_users"?0:" "],condition:[">",">=","=","<","<=","!=","gt","gte","eq","lt","lte","ne"],range:["string","number"]}),n.condition||(n.value===" "||!n.value?n.condition=">":n.condition="="),n.range&&n.condition&&delete n.condition,n.searchFor==="number_of_users"&&typeof n.value!="number")throw new a('"value" must be a number.',{code:"INVALID_PARAMETER"});if(n.searchFor==="group"&&typeof n.value!="string")throw new a('"value" must be a string.',{code:"INVALID_PARAMETER"});if(n.hasOwnProperty("range")&&typeof n.range!=typeof n.value)throw new a(`"range" must be a ${typeof n.value}.`,{code:"INVALID_PARAMETER"});let t=await w.bind(this)("get-ws-group",n,{fetchOptions:e,auth:true,method:"post"});return t.list=t.list.map(i=>({group:i.rid.split("#")[1],number_of_users:i.cnt})),t}var Nr=typeof FormData<"u",Cr=typeof HTMLFormElement<"u",Lr=typeof SubmitEvent<"u";async function un(n){let e=false,t=r=>{for(let s in r)if(typeof r[s]=="string"&&r[s].includes("$CLIENT_SECRET")){e=true;break}};if(n=g.Params(n,{url:r=>{if(!r||typeof r!="string")throw new a('"url" should be type: <string>.',{code:"INVALID_PARAMETER"});return g.Url(r),r.includes("$CLIENT_SECRET")&&(e=true),r},clientSecretName:"string",method:r=>{if(r&&typeof r!="string")throw new a('"method" should be either "GET" or "POST" or "DELETE" or "PUT".',{code:"INVALID_PARAMETER"});let s=r.toLowerCase();if(s!=="get"&&s!=="post"&&s!=="delete"&&s!=="put")throw new a('"method" should be either "GET" or "POST" or "DELETE" or "PUT".',{code:"INVALID_PARAMETER"});return s},headers:r=>{if(r&&typeof r!="object")throw new a('"headers" should be type: <object>.',{code:"INVALID_PARAMETER"});return t(r),r},data:r=>{if(r&&typeof r!="object")throw new a('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return t(r),r},params:r=>{if(r&&typeof r!="object")throw new a('"params" should be type: <object>.',{code:"INVALID_PARAMETER"});return t(r),r}},["clientSecretName","method","url"]),!e)throw new a(`At least one parameter value should include "$CLIENT_SECRET" in ${n.method.toLowerCase()==="post"?'"data"':'"params"'} or "headers".`,{code:"INVALID_PARAMETER"});await this.__connection;let i=!!this.__user;return w.bind(this)("csr",n,{auth:i})}async function dn(n){await this.__connection;let e={name:"string",email:t=>(g.Email(t),t),subject:"string",message:"string"};return n=g.Params(n,e,["name","email","subject","message"]),await w.bind(this)("send-inquiry",n),"SUCCESS: Inquiry has been sent."}async function gn(n,e){if(await this.__connection,Nr&&n instanceof FormData||Cr&&n instanceof HTMLFormElement||Lr&&n instanceof SubmitEvent){if(!e)throw new a("Url string as a second argument is required when form is passed.",{code:"INVALID_PARAMETER"});let i=D(n);n={url:e,data:i.data,sync:true};}let t={url:i=>g.Url(i),data:i=>i,sync:["boolean",()=>true]};if(Array.isArray(n))for(let i of n)i=g.Params(i,t);else n=g.Params(n,t);return w.bind(this)("post-secure",n,{auth:true})}async function fn(n,e){await this.__connection;let{auth:t=false,method:i="POST",bypassAwaitConnection:r=false,responseType:s,contentType:o,progress:c}=e||{};if(e=Object.assign({auth:t,method:i,bypassAwaitConnection:r,responseType:s,contentType:o},{fetchOptions:{progress:c}}),typeof n!="object"&&(o==="application/json"||o===void 0))throw new a('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return w.bind(this)("mock",n,e)}async function hn(n,e){await this.__connection,n=g.Params(n||{},{access_group:i=>{if(i==="authorized"&&(i=1),i==="public"&&(i=0),typeof i!="number")throw new a('"access_group" should be type number.',{code:"INVALID_PARAMETER"});if(i<0)throw new a('"access_group" should be zero or a positive number.',{code:"INVALID_PARAMETER"});if(i>this.__user.access_group)throw new a("User has no access.",{code:"INVALID_REQUEST"});return i}});let t=await w.bind(this)("get-feed",n,{auth:true,fetchOptions:e});for(let i in t.list)t.list[i]=await ie.bind(this)(t.list[i]);return t}function fe(n){if(n===this.__user.user_id)throw new a(`"user_id" cannot be the user's own ID.`,{code:"INVALID_PARAMETER"});return g.UserId(n,'"user_id"')}async function pn(n,e){if(n=D(n,{ignoreEmpty:true}).data,n=g.Params(n,{subscriber:i=>g.UserId(i,'User ID in "subscriber"'),subscription:fe.bind(this),blocked:"boolean"}),!n.subscriber&&!n.subscription)throw new a('At least either "subscriber" or "subscription" should have a value.',{code:"INVALID_PARAMETER"});let t=await w.bind(this)("get-subscription",n,Object.assign({auth:true},{fetchOptions:e}));return t.list=t.list.map((i=>{let r={};if(i.sub){let s=i.sub.split("#");r.subscriber=s[2],r.subscription=s[0];}else r.subscriber=i.subscriber,r.subscription=i.subscription;return r.timestamp=i?.timestamp||i.stmp,r.blocked=i?.blocked||i.grp.substring(0,1)==="N",Object.assign(r,i.opt),r})),t}async function mn(n){await this.__connection,n=g.Params(n,{user_id:fe.bind(this),get_feed:["boolean",()=>false],get_notified:["boolean",()=>false],get_email:i=>{if(i&&!this.__user.email||!this.__user.email_verified)throw new a("User has no verified email address.",{code:"INVALID_REQUEST"});return !!i}},["user_id"]);let e=await w.bind(this)("subscription",{subscribe:n.user_id,option:{get_feed:n.get_feed,get_notified:n.get_notified,get_email:n.get_email||false}},{auth:true}),t={};if(e.sub){let i=e.sub.split("#");t.subscriber=i[2],t.subscription=i[0];}else t.subscriber=e.subscriber,t.subscription=e.subscription;return t.timestamp=e?.timestamp||e.stmp,t.blocked=e?.blocked||e.grp.substring(0,1)==="N",Object.assign(t,e.opt),t}async function bn(n){await this.__connection;let{user_id:e}=g.Params(n,{user_id:fe.bind(this)},["user_id"]);return await w.bind(this)("subscription",{unsubscribe:e},{auth:true})}async function _n(n){await this.__connection;let{user_id:e}=g.Params(n,{user_id:fe.bind(this)},["user_id"]);return await w.bind(this)("subscription",{block:e},{auth:true})}async function yn(n){await this.__connection;let{user_id:e}=g.Params(n,{user_id:fe.bind(this)},["user_id"]);return await w.bind(this)("subscription",{unblock:e},{auth:true})}async function wn(n,e){await this.__connection;let t=await M.bind(this)();n=g.Params(n,{user_id:o=>{if(o!==this.__user.user_id&&!t)throw new a("No access.",{code:"INVALID_REQUEST"});return o},group:o=>{if(o==="public"&&(o=0),o==="authorized"&&(o=1),typeof o!="number")throw new a('"group" should be type number | "public" | "authorized".',{code:"INVALID_PARAMETER"});return o}});let i=await w.bind(this)("get-newsletter-subscription",n,{auth:true,fetchOptions:e||null}),r=i?.list||i,s=[];Array.isArray(r)||(r=[]);for(let o of r){let c=o.subt.split("#"),u=true;c[0].charAt(0)==="@"&&(u=false,c[0]=c[0].substring(1));let d=parseInt(c[0]);s.push({timestamp:o.stmp,group:d,subscribed_email:c[1],active:u});}return i?.list?(i.list=s,i):s}async function En(n){await this.__connection;let e=g.Params(n||{},{email:t=>Array.isArray(t)&&t.length>0?t.length===1?g.Email(t[0]):t.map(i=>g.Email(i)):g.Email(t),group:["number","public","authorized","admin",t=>{if(typeof t!="string"||t.length>20||!/^[a-zA-Z0-9]+$/.test(t))throw new a('"group" should be an alphanumeric string without spaces and less than 20 characters.',{code:"INVALID_PARAMETER"});return t}],redirect:t=>g.Url(t)},this.__user?["group"]:["email","group"]);return w.bind(this)(`subscribe-${this.__user?"":"public-"}newsletter`,e,{auth:!!this.__user})}async function Rn(n){await this.__connection,n=g.Params(n,{group:["number","public","authorized","admin"]},["group"]);let e=Object.assign({action:"unsubscribe"},n);return w.bind(this)("subscribe-newsletter",e,{auth:true})}async function An(n,e){let t=await M.bind(this)(),i={message_id:"string",timestamp:"number",read:"number",complaint:"number",subject:"string",bounced:"number"};n||(e=Object.assign({ascending:false},e||{})),n=D(n).data,n=n||{searchFor:"timestamp",value:Date.now(),condition:"<",group:"public"},n=g.Params(n,{searchFor:["message_id","timestamp","subject","complaint","read","bounced"],value:u=>{if(typeof u!==i[n.searchFor])throw new a(`"value" type does not match the type of "${n.searchFor}" index.`,{code:"INVALID_PARAMETER"});if(typeof u=="string"&&!u)throw new a('"value" should not be empty string.',{code:"INVALID_PARAMETER"});return u},range:u=>{if(!n.hasOwnProperty("value")||typeof u!=typeof n.value)throw new a('"range" should match type of "value".',{code:"INVALID_PARAMETER"});return u},condition:[">",">=","=","<","<=","gt","gte","eq","lt","lte",()=>"="],group:u=>{if(u==="public")return 0;if(!this.session)throw new a("User should be logged in.",{code:"INVALID_REQUEST"});if(u==="authorized")return 1;if(typeof u=="number"){if(!t&&u>parseInt(this.user?.access_group||this.session?.idToken?.payload?.access_group))throw new a("User has no access.",{code:"INVALID_REQUEST"});return u}throw new a('"group" should be type: number | "public" | "authorized".',{code:"INVALID_PARAMETER"})}},["searchFor","value","group"]);let r=n.group===0?"get-public-newsletters":"get-newsletters",s=await w.bind(this)(r,n,Object.assign({method:"get",auth:r==="get-public-newsletters"?!!this.__user:true},{fetchOptions:e})),o={message_id:"mid",timestamp:"stmp",complaint:"cmpl",read:"read",subject:"subj",bounced:"bnce",url:"url",delivered:"delv"},c={message_id:"",timestamp:0,complaint:0,read:0,subject:"",bounced:"",url:"",delivered:0};return s.list=s.list.map(u=>{let d={};for(let f in o)d[f]=u[o[f]]||c[f];return d.bounced=String(d.bounced),d}),s}async function In(n){let e=g.Params(n,{user_id:i=>g.UserId(i,'"user_id"')},["user_id"]);if(e?.service&&e?.owner?e={service:e?.service,owner:e?.owner,block:e.user_id}:e={block:e.user_id},!await M.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}return await w.bind(this)("block-account",e,{auth:true})}async function Tn(n){let e=g.Params(n,{user_id:i=>g.UserId(i,'"user_id"')},["user_id"]);if(e?.service&&e?.owner?e={service:e?.service,owner:e?.owner,unblock:e.user_id}:e={unblock:e.user_id},!await M.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}return await w.bind(this)("block-account",e,{auth:true})}async function Sn(n){let e=g.Params(n,{user_id:i=>g.UserId(i,'"user_id"')},["user_id"]);if(e?.service&&e?.owner?e={service:e?.service,owner:e?.owner,delete:e.user_id}:e={delete:e.user_id},!await M.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}return await w.bind(this)("remove-account",e,{auth:true})}async function Pn(n,e){let t={email:s=>g.Email(s),password:s=>g.Password(s),name:"string",username:"string",gender:"string",address:s=>{if(!s)return "";if(typeof s=="string")return s;if(typeof s=="object")return JSON.stringify(s)},birthdate:s=>g.Birthdate(s),phone_number:s=>g.PhoneNumber(s),picture:s=>{if(s)return g.Url(s)},profile:s=>{if(s)return g.Url(s)},website:s=>{if(s)return g.Url(s)},nickname:"string",misc:"string",email_public:["boolean",()=>false],gender_public:["boolean",()=>false],address_public:["boolean",()=>false],birthdate_public:["boolean",()=>false],phone_number_public:["boolean",()=>false],openid_id:"string",access_group:s=>{try{typeof s=="string"&&(s=s==="admin"?99:parseInt(s));}catch{throw new a('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof s!="number"||s<1||s>100)throw new a('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"});return s}},i=g.Params(n,t,["email"]);if(e=g.Params(e,{confirmation_url:s=>{let o=s;if(typeof s=="string")o=g.Url(s);else throw new a('"options.confirmation_url" should be type: <string>.',{code:"INVALID_PARAMETER"});if(o&&!i.email)throw new a('"email" is required for signup confirmation.',{code:"INVALID_PARAMETER"});return o},email_subscription:s=>{if(typeof s!="boolean")throw new a('"options.email_subscription" should be type: <boolean>.',{code:"INVALID_PARAMETER"});if(!e?.confirmation_url)throw new a('"options.confirmation_url" is required for email subscription.',{code:"INVALID_PARAMETER"});return s},template:s=>{if(typeof s!="object"||!s.url||!s.subject)throw new a('"options.template" should be type: <object> with "url" and "subject".',{code:"INVALID_PARAMETER"});return {url:g.Url(s.url),subject:s.subject}}}),i.signup_confirmation=e?.confirmation_url||true,i.email_subscription=e?.email_subscription||false,i.template=e?.template||{},!await M.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}return await w.bind(this)("admin-signup",i,{auth:true})}async function kn(n){let e={email:r=>g.Email(r),password:r=>g.Password(r),openid_id:"string",name:"string",username:"string",gender:"string",address:r=>{if(!r)return "";if(typeof r=="string")return r;if(typeof r=="object")return JSON.stringify(r)},birthdate:r=>g.Birthdate(r),phone_number:r=>g.PhoneNumber(r),picture:r=>r?g.Url(r):"",profile:r=>r?g.Url(r):"",website:r=>r?g.Url(r):"",nickname:"string",misc:"string",email_public:["boolean",()=>false],gender_public:["boolean",()=>false],address_public:["boolean",()=>false],birthdate_public:["boolean",()=>false],phone_number_public:["boolean",()=>false],access_group:r=>{try{typeof r=="string"&&(r=parseInt(r));}catch{throw new a('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof r!="number"||r<1||r>100)throw new a('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"});return r}},t=g.Params(n,e,["email","password"]);if(!await M.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}return await w.bind(this)("admin-signup",t,{auth:true})}async function xn(n){if(n=g.Params(n,{user_id:t=>g.UserId(t,'"user_id"'),access_group:t=>{try{typeof t=="string"&&(t=parseInt(t));}catch{throw new a('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof t=="number"&&t>0&&t<100)return t;throw new a('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"})}},["user_id","access_group"]),!await M.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}return await w.bind(this)("grant-access",n,{auth:true})}async function vn(n,e){if(n=g.Params(n,{email:"string"}),!await M.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}let i=await w.bind(this)("invitation-list",Object.assign({mode:"search"},n),{fetchOptions:e,auth:true});return i.list=i.list.map(r=>ae(r.user)),i}async function Dn(n){if(n=g.Params(n,{email:t=>g.Email(t)},["email"]),!await M.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}return await w.bind(this)("invitation-list",Object.assign({mode:"cancel"},n),{auth:true})}async function Un(n){if(n=g.Params(n,{email:t=>g.Email(t)},["email"]),!await M.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}return await w.bind(this)("invitation-list",Object.assign({mode:"resend"},n),{auth:true})}async function Nn(n){if(typeof window>"u"||window._runningInNodeJS)throw new a("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.__connection,!n.endpoint)throw new a("Missing parameter: endpoint",{code:"INVALID_PARAMETER"});if(!n.keys||!n.keys.p256dh||!n.keys.auth)throw new a("Missing parameter: keys.p256dh or keys.auth",{code:"INVALID_PARAMETER"});return await w.bind(this)("store-subscription",{endpoint:n.endpoint,keys:n.keys},{auth:true}),"SUCCESS: Subscribed to receive notifications."}async function Cn(n){if(typeof window>"u"||window._runningInNodeJS)throw new a("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.__connection,!n.endpoint)throw new a("Missing parameter: endpoint",{code:"INVALID_PARAMETER"});if(!n.keys||!n.keys.p256dh||!n.keys.auth)throw new a("Missing parameter: keys.p256dh or keys.auth",{code:"INVALID_PARAMETER"});return await w.bind(this)("delete-subscription",{endpoint:n.endpoint,keys:n.keys},{auth:true}),"SUCCESS: Unsubscribed from notifications."}async function Ln(){if(typeof window>"u"||window._runningInNodeJS)throw new a("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});return await this.__connection,{VAPIDPublicKey:await w.bind(this)("get-vapid-public-key",null,{auth:true})}}async function On(n,e){if(typeof window>"u"||window._runningInNodeJS)throw new a("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});await this.__connection;let{title:t,body:i}=D(n||{},{nullIfEmpty:true}).data;if(!t)throw new a("Missing parameter: message title",{code:"INVALID_PARAMETER"});if(!i)throw new a("Missing parameter: message body",{code:"INVALID_PARAMETER"});let r={title:t,body:i};return e?(typeof e=="string"&&(e=[e]),r.user_ids=e):r.user_ids="all_users",await w.bind(this)("push-notification",r,{auth:true}),"SUCCESS: Notification sent."}async function Fn(n){await this.__connection,n=g.Params(n,{spell:"string",name:"string",magic:t=>t},["spell","name"]);await w.bind(this)("castspell",n);return `The spell "${n.spell}" has been cast.`}async function Mn(n){return await this.__connection,n=g.Params(n||{},{search:["spell","name",()=>"spell"],value:"string"}),await w.bind(this)("getspell",n)}async function Vn(n){await this.__connection,n=g.Params(n,{message:"string",name:"string"},["message","name"]);let e=await w.bind(this)("dopamine",n,{auth:true}),t=e?.previous_message?.message,i=e?.previous_message?.name;if($())t&&i&&window.alert(`${i} said: ${t}`),window.location.href=e.video;else return t&&i?`${i} said: ${t}
215
+ `,o=new Blob([s],{type:"application/javascript"});Z=new Worker(URL.createObjectURL(o)),Z.onmessage=c=>{r.readyState===1&&r.send(JSON.stringify({action:"keepAlive"}));},i(r);},r.onmessage=async s=>{let o="";try{o=JSON.parse(decodeURI(s.data)),this.log("socket onmessage",o);}catch{return}let c;switch(true){case !!o?.["#message"]:c="message";break;case !!o?.["#private"]:c="private";break;case !!o?.["#notice"]:c="notice";break;case !!o?.["#rtc"]:c="rtc";break;case !!o?.["#error"]:c="error";break}if(!c)return;let l={type:c,message:o?.["#rtc"]||o?.["#message"]||o?.["#private"]||o?.["#notice"]||o?.["#error"]||null,sender:o?.["#user_id"]||null,sender_cid:o?.["#scid"]?"cid:"+o["#scid"]:null,sender_rid:o?.["#srid"]||null,code:o?.["#code"]||null};if(c==="notice")n(l);else if(c==="rtc"){if(l.sender!==this.user.user_id){let d=l.message;if(d.hungup){K[l.sender_cid]&&(K[l.sender_cid](false),delete K[l.sender_cid]),H[l.sender_cid]&&delete H[l.sender_cid],I?.[l.sender_cid]&&Q.bind(this)({cid:l.sender_cid}),l.type="rtc:closed",n(l);return}if(d.candidate&&qe.bind(this)(d.candidate,l.sender_cid),d.sdpoffer&&($e.bind(this)(d.sdpoffer,l.sender_cid),H[l.sender_cid]||(H[l.sender_cid]=l.sender_cid,delete l.message,l.connectRTC=zt.bind(this)(l),l.type="rtc:incoming",l.hangup=(()=>{I[l.sender_cid]?Q.bind(this)({cid:l.sender_cid}):H[l.sender_cid]&&(delete H[l.sender_cid],r.send(JSON.stringify({action:"rtc",uid:l.sender_cid,content:{hungup:this.user.user_id},token:this.session.accessToken.jwtToken})));}).bind(this),n(l))),d.pickup&&K[l.sender_cid]&&(K[l.sender_cid](true),delete K[l.sender_cid]),d.sdpanswer&&I[l.sender_cid])if(I[l.sender_cid].signalingState==="have-local-offer")await I[l.sender_cid].setRemoteDescription(new RTCSessionDescription(d.sdpanswer));else throw new a("Invalid signaling state.",{code:"INVALID_REQUEST"})}}else n(l);},r.onclose=()=>{ge?(this.log("realtime onclose","WebSocket connection closed."),n({type:"close",message:"WebSocket connection closed."})):(this.log("realtime onclose","WebSocket unexpected close."),n({type:"error",message:"Skapi: WebSocket unexpected close."}),se++,se<3?(this.log("realtime onclose","Reconnecting to WebSocket server..."+se),n({type:"reconnect",message:"Reconnecting to WebSocket server..."+se}),ke.bind(this)(n,3e3,"reconnect")):(this.log("realtime onclose","Max reconnection attempts reached."),n({type:"error",message:"Skapi: Max reconnection attempts reached."})));},r.onerror=()=>{this.log("realtime onerror","WebSocket connection error."),n({type:"error",message:"Skapi: WebSocket connection error."});};},e);});}async function Yt(n,e,t){if(typeof window>"u"||window._runningInNodeJS)throw new a("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});let i=this.__socket?await this.__socket:this.__socket;if(!i)throw new a("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});if(!e)throw new a("No recipient.",{code:"INVALID_REQUEST"});await ne.bind(this)(),n=D(n).data;let r="";if(t&&(t=g.Params(t,{config:{always:"boolean"},title:"string",body:"string"},["title","body"]),r=JSON.stringify({title:t.title,body:t.body}),new Blob([r]).size>3072))throw new a("Notification size exceeds 3kb.",{code:"INVALID_PARAMETER"});if(i.readyState===1){try{g.UserId(e),i.send(JSON.stringify({action:"sendMessage",uid:e,content:n,notification:r,notificationConfig:t?.config||{},token:`IdT:${this.service}:${this.owner}:`+(this.bearerToken||this.session?.idToken?.jwtToken||"null")}));}catch(s){if(this.log("postRealtime:err",{err:s}),Y!==e)throw new a(`User has not joined to the recipient group. Run joinRealtime({ group: "${e}" })`,{code:"INVALID_REQUEST"});i.send(JSON.stringify({action:"broadcast",rid:e,content:n,notification:r,notificationConfig:t?.config||{},token:`IdT:${this.service}:${this.owner}:`+(this.bearerToken||this.session?.idToken?.jwtToken||"null")}));}return {type:"success",message:"Message sent."}}throw new a("Realtime connection is not open. Try reconnecting with connectRealtime().",{code:"INVALID_REQUEST"})}async function Be(n){if(typeof window>"u"||window._runningInNodeJS)throw new a("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});let e=this.__socket?await this.__socket:this.__socket;if(!e)throw new a("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});await ne.bind(this)(),n=D(n,{nullIfEmpty:true}).data;let{group:t=null}=n;if(!t&&!Y)return {type:"success",message:"Left realtime message group."};if(t!==null&&typeof t!="string")throw new a('"group" must be a string | null.',{code:"INVALID_PARAMETER"});return e.send(JSON.stringify({action:"joinRoom",rid:t,token:this.session.accessToken.jwtToken})),Y=t,{type:"success",message:t?`Joined realtime message group: "${t}".`:"Left realtime message group."}}async function en(n,e){n=g.Params(n,{user_id:i=>g.UserId(i,'User ID in "user_id"'),group:["string",()=>{if(!Y)throw new a('No group has been joined. Otherwise "group" is required.',{code:"INVALID_REQUEST"});return Y}]});let t=await R.bind(this)("get-ws-group",n,{fetchOptions:e,auth:true,method:"post"});return t.list=t.list.map(i=>({user_id:i.uid.split("#")[1],cid:"cid:"+i.cid})),t}async function tn(n,e){if(await this.__connection,n||(n={searchFor:"group",value:" ",condition:">"}),n=g.Params(n,{searchFor:["group","number_of_users",()=>"group"],value:["string","number",()=>n?.searchFor&&n?.searchFor==="number_of_users"?0:" "],condition:[">",">=","=","<","<=","!=","gt","gte","eq","lt","lte","ne"],range:["string","number"]}),n.condition||(n.value===" "||!n.value?n.condition=">":n.condition="="),n.range&&n.condition&&delete n.condition,n.searchFor==="number_of_users"&&typeof n.value!="number")throw new a('"value" must be a number.',{code:"INVALID_PARAMETER"});if(n.searchFor==="group"&&typeof n.value!="string")throw new a('"value" must be a string.',{code:"INVALID_PARAMETER"});if(n.hasOwnProperty("range")&&typeof n.range!=typeof n.value)throw new a(`"range" must be a ${typeof n.value}.`,{code:"INVALID_PARAMETER"});let t=await R.bind(this)("get-ws-group",n,{fetchOptions:e,auth:true,method:"post"});return t.list=t.list.map(i=>({group:i.rid.split("#")[1],number_of_users:i.cnt})),t}var kr=typeof FormData<"u",xr=typeof HTMLFormElement<"u",vr=typeof SubmitEvent<"u";async function nn(n){let e=false,t=r=>{for(let s in r)if(typeof r[s]=="string"&&r[s].includes("$CLIENT_SECRET")){e=true;break}};if(n=g.Params(n,{url:r=>{if(!r||typeof r!="string")throw new a('"url" should be type: <string>.',{code:"INVALID_PARAMETER"});return g.Url(r),r.includes("$CLIENT_SECRET")&&(e=true),r},clientSecretName:"string",method:r=>{if(r&&typeof r!="string")throw new a('"method" should be either "GET" or "POST" or "DELETE" or "PUT".',{code:"INVALID_PARAMETER"});let s=r.toLowerCase();if(s!=="get"&&s!=="post"&&s!=="delete"&&s!=="put")throw new a('"method" should be either "GET" or "POST" or "DELETE" or "PUT".',{code:"INVALID_PARAMETER"});return s},headers:r=>{if(r&&typeof r!="object")throw new a('"headers" should be type: <object>.',{code:"INVALID_PARAMETER"});return t(r),r},data:r=>{if(r&&typeof r!="object")throw new a('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return t(r),r},params:r=>{if(r&&typeof r!="object")throw new a('"params" should be type: <object>.',{code:"INVALID_PARAMETER"});return t(r),r}},["clientSecretName","method","url"]),!e)throw new a(`At least one parameter value should include "$CLIENT_SECRET" in ${n.method.toLowerCase()==="post"?'"data"':'"params"'} or "headers".`,{code:"INVALID_PARAMETER"});await this.__connection;let i=!!this.__user;return R.bind(this)("csr",n,{auth:i})}async function rn(n){await this.__connection;let e={name:"string",email:t=>(g.Email(t),t),subject:"string",message:"string"};return n=g.Params(n,e,["name","email","subject","message"]),await R.bind(this)("send-inquiry",n),"SUCCESS: Inquiry has been sent."}async function sn(n,e){if(await this.__connection,kr&&n instanceof FormData||xr&&n instanceof HTMLFormElement||vr&&n instanceof SubmitEvent){if(!e)throw new a("Url string as a second argument is required when form is passed.",{code:"INVALID_PARAMETER"});let i=D(n);n={url:e,data:i.data,sync:true};}let t={url:i=>g.Url(i),data:i=>i,sync:["boolean",()=>true]};if(Array.isArray(n))for(let i of n)i=g.Params(i,t);else n=g.Params(n,t);return R.bind(this)("post-secure",n,{auth:true})}async function on(n,e){await this.__connection;let{auth:t=false,method:i="POST",bypassAwaitConnection:r=false,responseType:s,contentType:o,progress:c}=e||{};if(e=Object.assign({auth:t,method:i,bypassAwaitConnection:r,responseType:s,contentType:o},{fetchOptions:{progress:c}}),typeof n!="object"&&(o==="application/json"||o===void 0))throw new a('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return R.bind(this)("mock",n,e)}async function an(n,e){await this.__connection,n=g.Params(n||{},{access_group:i=>{if(i==="authorized"&&(i=1),i==="public"&&(i=0),typeof i!="number")throw new a('"access_group" should be type number.',{code:"INVALID_PARAMETER"});if(i<0)throw new a('"access_group" should be zero or a positive number.',{code:"INVALID_PARAMETER"});if(i>this.__user.access_group)throw new a("User has no access.",{code:"INVALID_REQUEST"});return i}});let t=await R.bind(this)("get-feed",n,{auth:true,fetchOptions:e});for(let i in t.list)t.list[i]=await ie.bind(this)(t.list[i]);return t}function fe(n){if(n===this.__user.user_id)throw new a(`"user_id" cannot be the user's own ID.`,{code:"INVALID_PARAMETER"});return g.UserId(n,'"user_id"')}async function cn(n,e){if(n=D(n,{ignoreEmpty:true}).data,n=g.Params(n,{subscriber:i=>g.UserId(i,'User ID in "subscriber"'),subscription:fe.bind(this),blocked:"boolean"}),!n.subscriber&&!n.subscription)throw new a('At least either "subscriber" or "subscription" should have a value.',{code:"INVALID_PARAMETER"});let t=await R.bind(this)("get-subscription",n,Object.assign({auth:true},{fetchOptions:e}));return t.list=t.list.map((i=>{let r={};if(i.sub){let s=i.sub.split("#");r.subscriber=s[2],r.subscription=s[0];}else r.subscriber=i.subscriber,r.subscription=i.subscription;return r.timestamp=i?.timestamp||i.stmp,r.blocked=i?.blocked||i.grp.substring(0,1)==="N",Object.assign(r,i.opt),r})),t}async function ln(n){await this.__connection,n=g.Params(n,{user_id:fe.bind(this),get_feed:["boolean",()=>false],get_notified:["boolean",()=>false],get_email:i=>{if(i&&!this.__user.email||!this.__user.email_verified)throw new a("User has no verified email address.",{code:"INVALID_REQUEST"});return !!i}},["user_id"]);let e=await R.bind(this)("subscription",{subscribe:n.user_id,option:{get_feed:n.get_feed,get_notified:n.get_notified,get_email:n.get_email||false}},{auth:true}),t={};if(e.sub){let i=e.sub.split("#");t.subscriber=i[2],t.subscription=i[0];}else t.subscriber=e.subscriber,t.subscription=e.subscription;return t.timestamp=e?.timestamp||e.stmp,t.blocked=e?.blocked||e.grp.substring(0,1)==="N",Object.assign(t,e.opt),t}async function un(n){await this.__connection;let{user_id:e}=g.Params(n,{user_id:fe.bind(this)},["user_id"]);return await R.bind(this)("subscription",{unsubscribe:e},{auth:true})}async function dn(n){await this.__connection;let{user_id:e}=g.Params(n,{user_id:fe.bind(this)},["user_id"]);return await R.bind(this)("subscription",{block:e},{auth:true})}async function gn(n){await this.__connection;let{user_id:e}=g.Params(n,{user_id:fe.bind(this)},["user_id"]);return await R.bind(this)("subscription",{unblock:e},{auth:true})}async function fn(n,e){await this.__connection;let t=await M.bind(this)();n=g.Params(n,{user_id:o=>{if(o!==this.__user.user_id&&!t)throw new a("No access.",{code:"INVALID_REQUEST"});return o},group:o=>{if(o==="public"&&(o=0),o==="authorized"&&(o=1),typeof o!="number")throw new a('"group" should be type number | "public" | "authorized".',{code:"INVALID_PARAMETER"});return o}});let i=await R.bind(this)("get-newsletter-subscription",n,{auth:true,fetchOptions:e||null}),r=i?.list||i,s=[];Array.isArray(r)||(r=[]);for(let o of r){let c=o.subt.split("#"),l=true;c[0].charAt(0)==="@"&&(l=false,c[0]=c[0].substring(1));let d=parseInt(c[0]);s.push({timestamp:o.stmp,group:d,subscribed_email:c[1],active:l});}return i?.list?(i.list=s,i):s}async function hn(n){await this.__connection;let e=g.Params(n||{},{email:t=>Array.isArray(t)&&t.length>0?t.length===1?g.Email(t[0]):t.map(i=>g.Email(i)):g.Email(t),group:["number","public","authorized","admin",t=>{if(typeof t!="string"||t.length>20||!/^[a-zA-Z0-9]+$/.test(t))throw new a('"group" should be an alphanumeric string without spaces and less than 20 characters.',{code:"INVALID_PARAMETER"});return t}],redirect:t=>g.Url(t)},this.__user?["group"]:["email","group"]);return R.bind(this)(`subscribe-${this.__user?"":"public-"}newsletter`,e,{auth:!!this.__user})}async function pn(n){await this.__connection,n=g.Params(n,{group:["number","public","authorized","admin"]},["group"]);let e=Object.assign({action:"unsubscribe"},n);return R.bind(this)("subscribe-newsletter",e,{auth:true})}async function mn(n,e){let t=await M.bind(this)(),i={message_id:"string",timestamp:"number",read:"number",complaint:"number",subject:"string",bounced:"number"};n||(e=Object.assign({ascending:false},e||{})),n=D(n).data,n=n||{searchFor:"timestamp",value:Date.now(),condition:"<",group:"public"},n=g.Params(n,{searchFor:["message_id","timestamp","subject","complaint","read","bounced"],value:l=>{if(typeof l!==i[n.searchFor])throw new a(`"value" type does not match the type of "${n.searchFor}" index.`,{code:"INVALID_PARAMETER"});if(typeof l=="string"&&!l)throw new a('"value" should not be empty string.',{code:"INVALID_PARAMETER"});return l},range:l=>{if(!n.hasOwnProperty("value")||typeof l!=typeof n.value)throw new a('"range" should match type of "value".',{code:"INVALID_PARAMETER"});return l},condition:[">",">=","=","<","<=","gt","gte","eq","lt","lte",()=>"="],group:l=>{if(l==="public")return 0;if(!this.session)throw new a("User should be logged in.",{code:"INVALID_REQUEST"});if(l==="authorized")return 1;if(typeof l=="number"){if(!t&&l>parseInt(this.user?.access_group||this.session?.idToken?.payload?.access_group))throw new a("User has no access.",{code:"INVALID_REQUEST"});return l}throw new a('"group" should be type: number | "public" | "authorized".',{code:"INVALID_PARAMETER"})}},["searchFor","value","group"]);let r=n.group===0?"get-public-newsletters":"get-newsletters",s=await R.bind(this)(r,n,Object.assign({method:"get",auth:r==="get-public-newsletters"?!!this.__user:true},{fetchOptions:e})),o={message_id:"mid",timestamp:"stmp",complaint:"cmpl",read:"read",subject:"subj",bounced:"bnce",url:"url",delivered:"delv"},c={message_id:"",timestamp:0,complaint:0,read:0,subject:"",bounced:"",url:"",delivered:0};return s.list=s.list.map(l=>{let d={};for(let h in o)d[h]=l[o[h]]||c[h];return d.bounced=String(d.bounced),d}),s}async function _n(n){let e=g.Params(n,{user_id:i=>g.UserId(i,'"user_id"')},["user_id"]);if(e?.service&&e?.owner?e={service:e?.service,owner:e?.owner,block:e.user_id}:e={block:e.user_id},!await M.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}return await R.bind(this)("block-account",e,{auth:true})}async function bn(n){let e=g.Params(n,{user_id:i=>g.UserId(i,'"user_id"')},["user_id"]);if(e?.service&&e?.owner?e={service:e?.service,owner:e?.owner,unblock:e.user_id}:e={unblock:e.user_id},!await M.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}return await R.bind(this)("block-account",e,{auth:true})}async function yn(n){let e=g.Params(n,{user_id:i=>g.UserId(i,'"user_id"')},["user_id"]);if(e?.service&&e?.owner?e={service:e?.service,owner:e?.owner,delete:e.user_id}:e={delete:e.user_id},!await M.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}return await R.bind(this)("remove-account",e,{auth:true})}async function wn(n,e){let t={email:s=>g.Email(s),password:s=>g.Password(s),name:"string",username:"string",gender:"string",address:s=>{if(!s)return "";if(typeof s=="string")return s;if(typeof s=="object")return JSON.stringify(s)},birthdate:s=>g.Birthdate(s),phone_number:s=>g.PhoneNumber(s),picture:s=>{if(s)return g.Url(s)},profile:s=>{if(s)return g.Url(s)},website:s=>{if(s)return g.Url(s)},nickname:"string",misc:"string",email_public:["boolean",()=>false],gender_public:["boolean",()=>false],address_public:["boolean",()=>false],birthdate_public:["boolean",()=>false],phone_number_public:["boolean",()=>false],openid_id:"string",access_group:s=>{try{typeof s=="string"&&(s=s==="admin"?99:parseInt(s));}catch{throw new a('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof s!="number"||s<1||s>100)throw new a('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"});return s}},i=g.Params(n,t,["email"]);if(e=g.Params(e,{confirmation_url:s=>{let o=s;if(typeof s=="string")o=g.Url(s);else throw new a('"options.confirmation_url" should be type: <string>.',{code:"INVALID_PARAMETER"});if(o&&!i.email)throw new a('"email" is required for signup confirmation.',{code:"INVALID_PARAMETER"});return o},email_subscription:s=>{if(typeof s!="boolean")throw new a('"options.email_subscription" should be type: <boolean>.',{code:"INVALID_PARAMETER"});if(!e?.confirmation_url)throw new a('"options.confirmation_url" is required for email subscription.',{code:"INVALID_PARAMETER"});return s},template:s=>{if(typeof s!="object"||!s.url||!s.subject)throw new a('"options.template" should be type: <object> with "url" and "subject".',{code:"INVALID_PARAMETER"});return {url:g.Url(s.url),subject:s.subject}}}),i.signup_confirmation=e?.confirmation_url||true,i.email_subscription=e?.email_subscription||false,i.template=e?.template||{},!await M.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}return await R.bind(this)("admin-signup",i,{auth:true})}async function En(n){let e={email:r=>g.Email(r),password:r=>g.Password(r),openid_id:"string",name:"string",username:"string",gender:"string",address:r=>{if(!r)return "";if(typeof r=="string")return r;if(typeof r=="object")return JSON.stringify(r)},birthdate:r=>g.Birthdate(r),phone_number:r=>g.PhoneNumber(r),picture:r=>r?g.Url(r):"",profile:r=>r?g.Url(r):"",website:r=>r?g.Url(r):"",nickname:"string",misc:"string",email_public:["boolean",()=>false],gender_public:["boolean",()=>false],address_public:["boolean",()=>false],birthdate_public:["boolean",()=>false],phone_number_public:["boolean",()=>false],access_group:r=>{try{typeof r=="string"&&(r=parseInt(r));}catch{throw new a('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof r!="number"||r<1||r>100)throw new a('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"});return r}},t=g.Params(n,e,["email","password"]);if(!await M.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}return await R.bind(this)("admin-signup",t,{auth:true})}async function Rn(n){if(n=g.Params(n,{user_id:t=>g.UserId(t,'"user_id"'),access_group:t=>{try{typeof t=="string"&&(t=parseInt(t));}catch{throw new a('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof t=="number"&&t>0&&t<100)return t;throw new a('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"})}},["user_id","access_group"]),!await M.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}return await R.bind(this)("grant-access",n,{auth:true})}async function An(n,e){if(n=g.Params(n,{email:"string"}),!await M.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}let i=await R.bind(this)("invitation-list",Object.assign({mode:"search"},n),{fetchOptions:e,auth:true});return i.list=i.list.map(r=>ae(r.user)),i}async function In(n){if(n=g.Params(n,{email:t=>g.Email(t)},["email"]),!await M.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}return await R.bind(this)("invitation-list",Object.assign({mode:"cancel"},n),{auth:true})}async function Tn(n){if(n=g.Params(n,{email:t=>g.Email(t)},["email"]),!await M.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}return await R.bind(this)("invitation-list",Object.assign({mode:"resend"},n),{auth:true})}async function Pn(n){if(typeof window>"u"||window._runningInNodeJS)throw new a("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.__connection,!n.endpoint)throw new a("Missing parameter: endpoint",{code:"INVALID_PARAMETER"});if(!n.keys||!n.keys.p256dh||!n.keys.auth)throw new a("Missing parameter: keys.p256dh or keys.auth",{code:"INVALID_PARAMETER"});return await R.bind(this)("store-subscription",{endpoint:n.endpoint,keys:n.keys},{auth:true}),"SUCCESS: Subscribed to receive notifications."}async function Sn(n){if(typeof window>"u"||window._runningInNodeJS)throw new a("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.__connection,!n.endpoint)throw new a("Missing parameter: endpoint",{code:"INVALID_PARAMETER"});if(!n.keys||!n.keys.p256dh||!n.keys.auth)throw new a("Missing parameter: keys.p256dh or keys.auth",{code:"INVALID_PARAMETER"});return await R.bind(this)("delete-subscription",{endpoint:n.endpoint,keys:n.keys},{auth:true}),"SUCCESS: Unsubscribed from notifications."}async function kn(){if(typeof window>"u"||window._runningInNodeJS)throw new a("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});return await this.__connection,{VAPIDPublicKey:await R.bind(this)("get-vapid-public-key",null,{auth:true})}}async function xn(n,e){if(typeof window>"u"||window._runningInNodeJS)throw new a("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});await this.__connection;let{title:t,body:i}=D(n||{},{nullIfEmpty:true}).data;if(!t)throw new a("Missing parameter: message title",{code:"INVALID_PARAMETER"});if(!i)throw new a("Missing parameter: message body",{code:"INVALID_PARAMETER"});let r={title:t,body:i};return e?(typeof e=="string"&&(e=[e]),r.user_ids=e):r.user_ids="all_users",await R.bind(this)("push-notification",r,{auth:true}),"SUCCESS: Notification sent."}async function vn(n){await this.__connection,n=g.Params(n,{spell:"string",name:"string",magic:t=>t},["spell","name"]);await R.bind(this)("castspell",n);return `The spell "${n.spell}" has been cast.`}async function Dn(n){return await this.__connection,n=g.Params(n||{},{search:["spell","name",()=>"spell"],value:"string"}),await R.bind(this)("getspell",n)}async function Un(n){await this.__connection,n=g.Params(n,{message:"string",name:"string"},["message","name"]);let e=await R.bind(this)("dopamine",n,{auth:true}),t=e?.previous_message?.message,i=e?.previous_message?.name;if($())t&&i&&window.alert(`${i} said: ${t}`),window.location.href=e.video;else return t&&i?`${i} said: ${t}
216
216
  Watch the video here: ${e.video}`:`Your message has been uploaded for future generations to receive.
217
- Watch the video here: ${e.video}`}var b=class{constructor(e,t,i,r){this.__version="1.5.0-beta.11";this.session=null;this.connection=null;this.__my_unique_ids={};this.userPool=null;this.__socket=null;this.__mediaStream=null;this.host="skapi";this.hostDomain="skapi.com";this.target_cdn="d3e9syvbtso631";this.customApiDomain="skapi.dev";this.requestBatchSize=30;this.__disabledAccount=null;this.__cached_requests={};this.__startKeyHistory={};this.__request_signup_confirmation=null;this.__private_access_key={};this.__class_properties_has_been_cached=false;this.__user=null;this._userProfileListeners=[];this._onLoginListeners=[];this._onBatchProcessListeners=[];this.validate={userId(e){try{return g.UserId(e),!0}catch{return false}},url(e){try{return g.Url(e),!0}catch{return false}},phoneNumber(e){try{return g.PhoneNumber(e),!0}catch{return false}},birthdate(e){try{return g.Birthdate(e),!0}catch{return false}},email(e){try{return g.Email(e),!0}catch{return false}},params(e,t,i){return g.Params(e,t,i)}};this.util={MD5:V,generateRandom:oe,toBase62:rt,fromBase62:B,decodeServiceId:Ue,formatServiceId:it,extractFormData:D,terminatePendingRequests:Dt,request:(e,t,i)=>w.bind(this)(e,t,i,{ignoreService:true})};this.__network_logs=false;this.__endpoint_version="v1";this.__public_identifier="";this.bearerToken="";this.registerTicket=lt.bind(this);this.unregisterTicket=ut.bind(this);if(!e||typeof e!="string")throw this._alert("Service ID is required."),new a("Service ID is required.",{code:"INVALID_PARAMETER"});if(e.startsWith("s1_")||e.split("-").length===7)try{let l=Ue(e);i&&typeof i=="object"&&(r=i),t&&typeof t=="object"&&(i=t),t=l.owner,e=l.service;}catch{throw this._alert("Service ID is invalid."),new a("Service ID is invalid.",{code:"INVALID_PARAMETER"})}if(!t||typeof t!="string")throw this._alert("Owner ID is invalid."),new a("Owner ID is invalid.",{code:"INVALID_PARAMETER"});if(e.toLowerCase()==="service_id")throw this._alert('Replace "service_id" with your actual Service ID.'),new a("Service ID is required.",{code:"INVALID_PARAMETER"});if(t!==this.host)try{g.UserId(t,'"owner"');}catch{throw this._alert("Owner ID is invalid."),new a("Owner ID is invalid.",{code:"INVALID_PARAMETER"})}this.service=e,this.owner=t;let s=true;if(i&&(typeof i.autoLogin=="boolean"&&(s=i.autoLogin),typeof i.requestBatchSize=="number")){if(i.requestBatchSize<1)throw new a('"requestBatchSize" must be greater than 0.',{code:"INVALID_PARAMETER"});this.requestBatchSize=i.requestBatchSize;}i?.eventListener&&typeof i.eventListener=="object"&&(i.eventListener?.onLogin&&typeof i.eventListener.onLogin=="function"&&(this.onLogin=i.eventListener.onLogin),i.eventListener?.onUserUpdate&&typeof i.eventListener.onUserUpdate=="function"&&(this.onUserUpdate=i.eventListener.onUserUpdate),i.eventListener?.onBatchProcess&&typeof i.eventListener.onBatchProcess=="function"&&(this.onBatchProcess=i.eventListener.onBatchProcess)),this.target_cdn=r?.target_cdn||this.target_cdn,this.hostDomain=r?.hostDomain||this.hostDomain,this.customApiDomain=r?.customApiDomain||this.customApiDomain,this.__network_logs=!!r?.network_logs;let o=`https://${this.target_cdn}.cloudfront.net`,c=e.substring(0,4);this.admin_endpoint=fetch(`${o}/${c}/admin-${this.__endpoint_version}.json`).then(l=>l.blob()).then(l=>new Promise((h,R)=>{let p=new FileReader;p.onloadend=()=>h(p.result),p.onerror=R,p.readAsDataURL(l);})).then(l=>{try{return typeof l=="string"?JSON.parse(atob(l.split(",")[1])):null}catch{throw new a("Service does not exist. Create your service from skapi.com",{code:"NOT_EXISTS"})}}),this.record_endpoint=fetch(`${o}/${c}/record-${this.__endpoint_version}.json`).then(l=>l.blob()).then(l=>new Promise((h,R)=>{let p=new FileReader;p.onloadend=()=>h(p.result),p.onerror=R,p.readAsDataURL(l);})).then(l=>{try{return typeof l=="string"?JSON.parse(atob(l.split(",")[1])):null}catch{throw new a("Service does not exist. Create your service from skapi.com",{code:"NOT_EXISTS"})}});let u=$();if(u&&!window.sessionStorage)throw this._alert("This browser is not supported."),new Error("This browser is not supported.");let d=u?JSON.parse(window.sessionStorage.getItem(`${e}#${t}`)||"null"):null;if(this.log("constructor:restore",d),d?.connection){for(let l in d)this[l]=d[l];d.__public_identifier||(this.__public_identifier=`${this.service}:${this.owner}:${oe(16)}`);}this.__authConnection=(async()=>{let l=await this.admin_endpoint,h={UserPoolId:l.userpool_id,ClientId:l.userpool_client};De()&&(h.Storage=window.localStorage),this.userPool=new amazonCognitoIdentityJs.CognitoUserPool(h);try{this.user||await F.bind(this)().getSession({skipUserUpdateEventTrigger:!0}),this.user&&(!d?.connection&&!s?z.bind(this)():(this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user)));}catch{}})();let f=u?window.sessionStorage.getItem(`${this.service}:uniqueids`):null;if(f)try{this.__my_unique_ids=JSON.parse(f);}catch{this.__my_unique_ids={};}this.__connection=(async()=>{let l=null;await this.record_endpoint,d?.connection||(l=this._updateConnection());let h=()=>{if(this.__class_properties_has_been_cached)return;let R=()=>{let p={},A=["__startKeyHistory","__disabledAccount","__cached_requests","__request_signup_confirmation","__public_identifier","connection"];if(this.connection){for(let k of A)p[k]=this[k];u&&window.sessionStorage.setItem(`${e}#${t}`,JSON.stringify(p)),this.__class_properties_has_been_cached=true;}};return l instanceof Promise?l.then(()=>R()):R()};return u&&(window.addEventListener("beforeunload",()=>{this.closeRealtime(),h();}),window.addEventListener("visibilitychange",()=>{h();})),await l,await this.__authConnection,this.connection})(),this.__connection.then(l=>{((l?.group||0)<3||this.__network_logs)&&this.version();});}get user(){return this.__user&&Object.keys(this.__user).length?JSON.parse(JSON.stringify(this.__user)):null}set user(e){}get onLogin(){return this._onLoginListeners}set onLogin(e){typeof e=="function"&&this._onLoginListeners.push(e);}get onUserUpdate(){return this._userProfileListeners}set onUserUpdate(e){typeof e=="function"&&this._userProfileListeners.push(e);}_runOnUserUpdateListeners(e){for(let t of this._userProfileListeners)typeof t=="function"&&t(e);}_runOnLoginListeners(e){for(let t of this._onLoginListeners)typeof t=="function"&&t(e);}get onBatchProcess(){return this._onBatchProcessListeners}set onBatchProcess(e){typeof e=="function"&&this._onBatchProcessListeners.push(e);}_alert(e){$()&&typeof window.alert=="function"&&window.alert(e);}async getConnectionInfo(){let e=await this.__connection,t=e?.user_agent||($()&&typeof window.navigator?.userAgent=="string"?window.navigator.userAgent:`skapi-node/${globalThis?.process?.versions?.node||"unknown"}`);return {user_ip:e.ip,user_agent:t,user_location:e.locale,service_name:e.service_name,version:this.__version}}async _updateConnection(){try{this.connection=await w.bind(this)("service",{service:this.service,owner:this.owner},{bypassAwaitConnection:!0,method:"get"});}catch(e){throw this.log("connection fail",e),this._alert("Service is not available: "+(e.message||e.toString())),this.connection=null,e}return this.connection}async version(){if(await this.__connection,$()){let t=`Built with:
217
+ Watch the video here: ${e.video}`}var b=class{constructor(e,t,i,r){this.__version="1.5.0-beta.13";this.session=null;this.connection=null;this.__my_unique_ids={};this.userPool=null;this.__socket=null;this.__mediaStream=null;this.host="skapi";this.hostDomain="skapi.com";this.target_cdn="d3e9syvbtso631";this.customApiDomain="skapi.dev";this.requestBatchSize=30;this.__disabledAccount=null;this.__cached_requests={};this.__startKeyHistory={};this.__request_signup_confirmation=null;this.__private_access_key={};this.__class_properties_has_been_cached=false;this.__user=null;this._userProfileListeners=[];this._onLoginListeners=[];this._onBatchProcessListeners=[];this.validate={userId(e){try{return g.UserId(e),!0}catch{return false}},url(e){try{return g.Url(e),!0}catch{return false}},phoneNumber(e){try{return g.PhoneNumber(e),!0}catch{return false}},birthdate(e){try{return g.Birthdate(e),!0}catch{return false}},email(e){try{return g.Email(e),!0}catch{return false}},params(e,t,i){return g.Params(e,t,i)}};this.util={MD5:V,generateRandom:oe,toBase62:Ge,fromBase62:B,decodeServiceId:De,formatServiceId:Xe,extractFormData:D,terminatePendingRequests:It,request:(e,t,i)=>R.bind(this)(e,t,i,{ignoreService:true})};this.__network_logs=false;this.__endpoint_version="v1";this.__public_identifier="";this.bearerToken="";this.registerTicket=nt.bind(this);this.unregisterTicket=rt.bind(this);if(!e||typeof e!="string")throw this._alert("Service ID is required."),new a("Service ID is required.",{code:"INVALID_PARAMETER"});let s=e.split("-").length;if(s===2||s===7)try{let f=De(e);i&&typeof i=="object"&&(r=i),t&&typeof t=="object"&&(i=t),t=f.owner,e=f.service;}catch{throw this._alert("Service ID is invalid."),new a("Service ID is invalid.",{code:"INVALID_PARAMETER"})}if(!t||typeof t!="string")throw this._alert("Owner ID is invalid."),new a("Owner ID is invalid.",{code:"INVALID_PARAMETER"});if(e.toLowerCase()==="service_id")throw this._alert('Replace "service_id" with your actual Service ID.'),new a("Service ID is required.",{code:"INVALID_PARAMETER"});if(t!==this.host)try{g.UserId(t,'"owner"');}catch{throw this._alert("Owner ID is invalid."),new a("Owner ID is invalid.",{code:"INVALID_PARAMETER"})}this.service=e,this.owner=t;let l=true;if(i&&(typeof i.autoLogin=="boolean"&&(l=i.autoLogin),typeof i.requestBatchSize=="number")){if(i.requestBatchSize<1)throw new a('"requestBatchSize" must be greater than 0.',{code:"INVALID_PARAMETER"});this.requestBatchSize=i.requestBatchSize;}i?.eventListener&&typeof i.eventListener=="object"&&(i.eventListener?.onLogin&&typeof i.eventListener.onLogin=="function"&&(this.onLogin=i.eventListener.onLogin),i.eventListener?.onUserUpdate&&typeof i.eventListener.onUserUpdate=="function"&&(this.onUserUpdate=i.eventListener.onUserUpdate),i.eventListener?.onBatchProcess&&typeof i.eventListener.onBatchProcess=="function"&&(this.onBatchProcess=i.eventListener.onBatchProcess)),this.target_cdn=r?.target_cdn||this.target_cdn,this.hostDomain=r?.hostDomain||this.hostDomain,this.customApiDomain=r?.customApiDomain||this.customApiDomain,this.__network_logs=!!r?.network_logs;let d=`https://${this.target_cdn}.cloudfront.net`,h=e.substring(0,4);this.admin_endpoint=fetch(`${d}/${h}/admin-${this.__endpoint_version}.json`).then(f=>f.blob()).then(f=>new Promise((y,P)=>{let _=new FileReader;_.onloadend=()=>y(_.result),_.onerror=P,_.readAsDataURL(f);})).then(f=>{try{return typeof f=="string"?JSON.parse(atob(f.split(",")[1])):null}catch{throw new a("Service does not exist. Create your service from skapi.com",{code:"NOT_EXISTS"})}}),this.record_endpoint=fetch(`${d}/${h}/record-${this.__endpoint_version}.json`).then(f=>f.blob()).then(f=>new Promise((y,P)=>{let _=new FileReader;_.onloadend=()=>y(_.result),_.onerror=P,_.readAsDataURL(f);})).then(f=>{try{return typeof f=="string"?JSON.parse(atob(f.split(",")[1])):null}catch{throw new a("Service does not exist. Create your service from skapi.com",{code:"NOT_EXISTS"})}});let u=$();if(u&&!window.sessionStorage)throw this._alert("This browser is not supported."),new Error("This browser is not supported.");let p=u?JSON.parse(window.sessionStorage.getItem(`${e}#${t}`)||"null"):null;if(this.log("constructor:restore",p),p?.connection){for(let f in p)this[f]=p[f];p.__public_identifier||(this.__public_identifier=`${this.service}:${this.owner}:${oe(16)}`);}this.__authConnection=(async()=>{let f=await this.admin_endpoint,y={UserPoolId:f.userpool_id,ClientId:f.userpool_client};ve()&&(y.Storage=window.localStorage),this.userPool=new amazonCognitoIdentityJs.CognitoUserPool(y);try{this.user||await F.bind(this)().getSession({skipUserUpdateEventTrigger:!0}),this.user&&(!p?.connection&&!l?G.bind(this)():(this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user)));}catch{}})();let A=u?window.sessionStorage.getItem(`${this.service}:uniqueids`):null;if(A)try{this.__my_unique_ids=JSON.parse(A);}catch{this.__my_unique_ids={};}this.__connection=(async()=>{let f=null;await this.record_endpoint,p?.connection||(f=this._updateConnection());let y=()=>{if(this.__class_properties_has_been_cached)return;let P=()=>{let _={},k=["__startKeyHistory","__disabledAccount","__cached_requests","__request_signup_confirmation","__public_identifier","connection"];if(this.connection){for(let S of k)_[S]=this[S];u&&window.sessionStorage.setItem(`${e}#${t}`,JSON.stringify(_)),this.__class_properties_has_been_cached=true;}};return f instanceof Promise?f.then(()=>P()):P()};return u&&(window.addEventListener("beforeunload",()=>{this.closeRealtime(),y();}),window.addEventListener("visibilitychange",()=>{y();})),await f,await this.__authConnection,this.connection})(),this.__connection.then(f=>{((f?.group||0)<3||this.__network_logs)&&this.version();});}get user(){return this.__user&&Object.keys(this.__user).length?JSON.parse(JSON.stringify(this.__user)):null}set user(e){}get onLogin(){return this._onLoginListeners}set onLogin(e){typeof e=="function"&&this._onLoginListeners.push(e);}get onUserUpdate(){return this._userProfileListeners}set onUserUpdate(e){typeof e=="function"&&this._userProfileListeners.push(e);}_runOnUserUpdateListeners(e){for(let t of this._userProfileListeners)typeof t=="function"&&t(e);}_runOnLoginListeners(e){for(let t of this._onLoginListeners)typeof t=="function"&&t(e);}get onBatchProcess(){return this._onBatchProcessListeners}set onBatchProcess(e){typeof e=="function"&&this._onBatchProcessListeners.push(e);}_alert(e){$()&&typeof window.alert=="function"&&window.alert(e);}async getConnectionInfo(){let e=await this.__connection,t=e?.user_agent||($()&&typeof window.navigator?.userAgent=="string"?window.navigator.userAgent:`skapi-node/${globalThis?.process?.versions?.node||"unknown"}`);return {user_ip:e.ip,user_agent:t,user_location:e.locale,service_name:e.service_name,version:this.__version}}async _updateConnection(){try{this.connection=await R.bind(this)("service",{service:this.service,owner:this.owner},{bypassAwaitConnection:!0,method:"get"});}catch(e){throw this.log("connection fail",e),this._alert("Service is not available: "+(e.message||e.toString())),this.connection=null,e}return this.connection}async version(){if(await this.__connection,$()){let t=`Built with:
218
218
  %c\r
219
219
  $$\\ $$\\ \r
220
220
  $$ | \\__|\r
@@ -229,6 +229,6 @@ $$$$$$$ |$$ | \\$$\\\\$$$$$$$ |$$$$$$$ |$$ |\r
229
229
  \\__| \r
230
230
  Version: ${this.__version}
231
231
 
232
- Full Documentation: https://docs.skapi.com/skapi.md`;console.log(t,"font-family: monospace; color:blue;"),this.connection.group===1&&console.log("%cSKAPI: THE SERVICE IS IN TRIAL MODE.","font-family: monospace; color:red;");}return this.__version}log(e,t){if(this.__network_logs){if(typeof t=="object")try{t=JSON.parse(JSON.stringify(t));}catch{t=String(t);}else typeof t=="string"&&t.length>100&&(t=t.substring(0,100)+"...");console.log(`%c${e}:`,"color: blue;",t);}}getFeed(e,t){return hn.bind(this)(e,t)}closeRTC(e){return Q.bind(this)(e)}connectRTC(e,t){return tn.bind(this)(e,t)}connectRealtime(e){return ke.bind(this)(e)}spellcast(e){return Fn.bind(this)(e)}getspell(e){return Mn.bind(this)(e)}dopamine(e){return Vn.bind(this)(e)}getUniqueId(e,t){return Wt.bind(this)(e,t)}resendInvitation(e){return Un.bind(this)(e)}cancelInvitation(e){return Dn.bind(this)(e)}getInvitations(e,t){return vn.bind(this)(e,t)}openIdLogin(e){return gt.bind(this)(e)}loginWithToken(e){return ft.bind(this)(e)}clientSecretRequest(e){return un.bind(this)(e)}consumeTicket(e){return ot.bind(this)(e)}getConsumedTickets(e,t){return ct.bind(this)(e,t)}getTickets(e,t){return at.bind(this)(e,t)}closeRealtime(){return on.bind(this)()}getRealtimeUsers(e,t){return cn.bind(this)(e,t)}sendInquiry(e){return dn.bind(this)(e)}blockAccount(e){return In.bind(this)(e)}unblockAccount(e){return Tn.bind(this)(e)}deleteAccount(e){return Sn.bind(this)(e)}inviteUser(e,t){return Pn.bind(this)(e,t)}createAccount(e){return kn.bind(this)(e)}grantAccess(e){return xn.bind(this)(e)}getRealtimeGroups(e,t){return ln.bind(this)(e,t)}postRealtime(e,t,i){return an.bind(this)(e,t,i)}joinRealtime(e){return Ke.bind(this)(e)}getProfile(e){return dt.bind(this)(e)}getFile(e,t){return Ie.bind(this)(e,t)}secureRequest(e,t){return gn.bind(this)(e,t)}getFormResponse(){return Nt.bind(this)()}getRecords(e,t){return Vt.bind(this)(e,t)}getTables(e,t){return Bt.bind(this)(e,t)}getIndexes(e,t){return Kt.bind(this)(e,t)}getTags(e,t){return Qt.bind(this)(e,t)}deleteRecords(e,t){return Ht.bind(this)(e,t)}resendSignupConfirmation(){return ht.bind(this)()}recoverAccount(e=false){return pt.bind(this)(e)}getUsers(e,t){return Tt.bind(this)(e,t)}disableAccount(){return bt.bind(this)()}lastVerifiedEmail(e){return St.bind(this)(e)}unsubscribeNewsletter(e){return Rn.bind(this)(e)}subscribeNotification(e,t){return Nn.bind(this)({endpoint:e,keys:t})}unsubscribeNotification(e,t){return Cn.bind(this)({endpoint:e,keys:t})}vapidPublicKey(){return Ln.bind(this)()}pushNotification(e,t){return On.bind(this)(e,t)}getNewsletters(e,t){return An.bind(this)(e,t)}getNewsletterSubscription(e,t){return wn.bind(this)(e,t)}requestUsernameChange(e){return Pt.bind(this)(e)}grantPrivateRecordAccess(e){return Jt.bind(this)(e)}removePrivateRecordAccess(e){return zt.bind(this)(e)}listPrivateRecordAccess(e){return Gt.bind(this)(e)}requestPrivateRecordAccessKey(e){return Xt.bind(this)(e)}deleteFiles(e){return Ft.bind(this)(e)}uploadFiles(e,t){return we.bind(this)(e,t)}mock(e,t){return fn.bind(this)(e,t)}login(e){return Ce.bind(this)(e)}logout(e){return ce.bind(this)(e)}signup(e,t){return mt.bind(this)(e,t)}resetPassword(e){return _t.bind(this)(e)}verifyEmail(e){return Et.bind(this)(e)}verifyPhoneNumber(e){return wt.bind(this)(e)}forgotPassword(e){return Rt.bind(this)(e)}changePassword(e){return At.bind(this)(e)}updateProfile(e){return It.bind(this)(e)}postRecord(e,t,i){return jt.bind(this)(e,t,i)}getSubscriptions(e,t){return pn.bind(this)(e,t)}subscribe(e){return mn.bind(this)(e)}unsubscribe(e){return bn.bind(this)(e)}blockSubscriber(e){return _n.bind(this)(e)}unblockSubscriber(e){return yn.bind(this)(e)}subscribeNewsletter(e){return En.bind(this)(e)}bulkPostRecords(e){return qt.bind(this)(e)}};_([y()],b.prototype,"getFeed"),_([y()],b.prototype,"closeRTC"),_([y()],b.prototype,"connectRTC"),_([y()],b.prototype,"spellcast"),_([y()],b.prototype,"getspell"),_([y()],b.prototype,"dopamine"),_([y()],b.prototype,"getUniqueId"),_([y()],b.prototype,"resendInvitation"),_([y()],b.prototype,"cancelInvitation"),_([y()],b.prototype,"getInvitations"),_([y()],b.prototype,"openIdLogin"),_([y()],b.prototype,"loginWithToken"),_([y()],b.prototype,"clientSecretRequest"),_([y()],b.prototype,"consumeTicket"),_([y()],b.prototype,"getConsumedTickets"),_([y()],b.prototype,"getTickets"),_([y()],b.prototype,"getRealtimeUsers"),_([y()],b.prototype,"sendInquiry"),_([y()],b.prototype,"blockAccount"),_([y()],b.prototype,"unblockAccount"),_([y()],b.prototype,"deleteAccount"),_([y()],b.prototype,"inviteUser"),_([y()],b.prototype,"createAccount"),_([y()],b.prototype,"grantAccess"),_([y()],b.prototype,"getRealtimeGroups"),_([y()],b.prototype,"postRealtime"),_([y()],b.prototype,"joinRealtime"),_([y()],b.prototype,"getProfile"),_([y()],b.prototype,"getFile"),_([y()],b.prototype,"secureRequest"),_([y()],b.prototype,"getFormResponse"),_([y()],b.prototype,"getRecords"),_([y()],b.prototype,"getTables"),_([y()],b.prototype,"getIndexes"),_([y()],b.prototype,"getTags"),_([y()],b.prototype,"deleteRecords"),_([y()],b.prototype,"resendSignupConfirmation"),_([y()],b.prototype,"recoverAccount"),_([y()],b.prototype,"getUsers"),_([y()],b.prototype,"disableAccount"),_([y()],b.prototype,"lastVerifiedEmail"),_([y()],b.prototype,"unsubscribeNewsletter"),_([y()],b.prototype,"subscribeNotification"),_([y()],b.prototype,"unsubscribeNotification"),_([y()],b.prototype,"vapidPublicKey"),_([y()],b.prototype,"pushNotification"),_([y()],b.prototype,"getNewsletters"),_([y()],b.prototype,"getNewsletterSubscription"),_([y()],b.prototype,"requestUsernameChange"),_([y()],b.prototype,"grantPrivateRecordAccess"),_([y()],b.prototype,"removePrivateRecordAccess"),_([y()],b.prototype,"listPrivateRecordAccess"),_([y()],b.prototype,"requestPrivateRecordAccessKey"),_([y()],b.prototype,"deleteFiles"),_([y()],b.prototype,"uploadFiles"),_([y()],b.prototype,"mock"),_([y({preventMultipleCalls:true})],b.prototype,"login"),_([y()],b.prototype,"logout"),_([y({preventMultipleCalls:true})],b.prototype,"signup"),_([y({preventMultipleCalls:true})],b.prototype,"resetPassword"),_([y({preventMultipleCalls:true})],b.prototype,"verifyEmail"),_([y({preventMultipleCalls:true})],b.prototype,"verifyPhoneNumber"),_([y({preventMultipleCalls:true})],b.prototype,"forgotPassword"),_([y({preventMultipleCalls:true})],b.prototype,"changePassword"),_([y({preventMultipleCalls:true})],b.prototype,"updateProfile"),_([y()],b.prototype,"postRecord"),_([y()],b.prototype,"getSubscriptions"),_([y()],b.prototype,"subscribe"),_([y()],b.prototype,"unsubscribe"),_([y()],b.prototype,"blockSubscriber"),_([y()],b.prototype,"unblockSubscriber"),_([y()],b.prototype,"subscribeNewsletter");var Fr={};
233
- exports.Skapi=b;exports.SkapiError=a;exports.Types=Fr;//# sourceMappingURL=skapi.cjs.map
232
+ Full Documentation: https://docs.skapi.com/skapi.md`;console.log(t,"font-family: monospace; color:blue;"),this.connection.group===1&&console.log("%cSKAPI: THE SERVICE IS IN TRIAL MODE.","font-family: monospace; color:red;");}return this.__version}log(e,t){if(this.__network_logs){if(typeof t=="object")try{t=JSON.parse(JSON.stringify(t));}catch{t=String(t);}else typeof t=="string"&&t.length>100&&(t=t.substring(0,100)+"...");console.log(`%c${e}:`,"color: blue;",t);}}getFeed(e,t){return an.bind(this)(e,t)}closeRTC(e){return Q.bind(this)(e)}connectRTC(e,t){return Jt.bind(this)(e,t)}connectRealtime(e){return ke.bind(this)(e)}spellcast(e){return vn.bind(this)(e)}getspell(e){return Dn.bind(this)(e)}dopamine(e){return Un.bind(this)(e)}getUniqueId(e,t){return Vt.bind(this)(e,t)}resendInvitation(e){return Tn.bind(this)(e)}cancelInvitation(e){return In.bind(this)(e)}getInvitations(e,t){return An.bind(this)(e,t)}openIdLogin(e){return st.bind(this)(e)}loginWithToken(e){return ot.bind(this)(e)}clientSecretRequest(e){return nn.bind(this)(e)}consumeTicket(e){return Ye.bind(this)(e)}getConsumedTickets(e,t){return tt.bind(this)(e,t)}getTickets(e,t){return et.bind(this)(e,t)}closeRealtime(){return Zt.bind(this)()}getRealtimeUsers(e,t){return en.bind(this)(e,t)}sendInquiry(e){return rn.bind(this)(e)}blockAccount(e){return _n.bind(this)(e)}unblockAccount(e){return bn.bind(this)(e)}deleteAccount(e){return yn.bind(this)(e)}inviteUser(e,t){return wn.bind(this)(e,t)}createAccount(e){return En.bind(this)(e)}grantAccess(e){return Rn.bind(this)(e)}getRealtimeGroups(e,t){return tn.bind(this)(e,t)}postRealtime(e,t,i){return Yt.bind(this)(e,t,i)}joinRealtime(e){return Be.bind(this)(e)}getProfile(e){return it.bind(this)(e)}getFile(e,t){return Ie.bind(this)(e,t)}secureRequest(e,t){return sn.bind(this)(e,t)}getFormResponse(){return Pt.bind(this)()}getRecords(e,t){return Ut.bind(this)(e,t)}getTables(e,t){return Ot.bind(this)(e,t)}getIndexes(e,t){return Ft.bind(this)(e,t)}getTags(e,t){return Mt.bind(this)(e,t)}deleteRecords(e,t){return $t.bind(this)(e,t)}resendSignupConfirmation(){return at.bind(this)()}recoverAccount(e=false){return ct.bind(this)(e)}getUsers(e,t){return bt.bind(this)(e,t)}disableAccount(){return ut.bind(this)()}lastVerifiedEmail(e){return yt.bind(this)(e)}unsubscribeNewsletter(e){return pn.bind(this)(e)}subscribeNotification(e,t){return Pn.bind(this)({endpoint:e,keys:t})}unsubscribeNotification(e,t){return Sn.bind(this)({endpoint:e,keys:t})}vapidPublicKey(){return kn.bind(this)()}pushNotification(e,t){return xn.bind(this)(e,t)}getNewsletters(e,t){return mn.bind(this)(e,t)}getNewsletterSubscription(e,t){return fn.bind(this)(e,t)}requestUsernameChange(e){return wt.bind(this)(e)}grantPrivateRecordAccess(e){return qt.bind(this)(e)}removePrivateRecordAccess(e){return jt.bind(this)(e)}listPrivateRecordAccess(e){return Bt.bind(this)(e)}requestPrivateRecordAccessKey(e){return Kt.bind(this)(e)}deleteFiles(e){return vt.bind(this)(e)}uploadFiles(e,t){return we.bind(this)(e,t)}mock(e,t){return on.bind(this)(e,t)}login(e){return Ne.bind(this)(e)}logout(e){return ce.bind(this)(e)}signup(e,t){return lt.bind(this)(e,t)}resetPassword(e){return dt.bind(this)(e)}verifyEmail(e){return ht.bind(this)(e)}verifyPhoneNumber(e){return ft.bind(this)(e)}forgotPassword(e){return pt.bind(this)(e)}changePassword(e){return mt.bind(this)(e)}updateProfile(e){return _t.bind(this)(e)}postRecord(e,t,i){return Lt.bind(this)(e,t,i)}getSubscriptions(e,t){return cn.bind(this)(e,t)}subscribe(e){return ln.bind(this)(e)}unsubscribe(e){return un.bind(this)(e)}blockSubscriber(e){return dn.bind(this)(e)}unblockSubscriber(e){return gn.bind(this)(e)}subscribeNewsletter(e){return hn.bind(this)(e)}bulkPostRecords(e){return Ct.bind(this)(e)}};w([E()],b.prototype,"getFeed"),w([E()],b.prototype,"closeRTC"),w([E()],b.prototype,"connectRTC"),w([E()],b.prototype,"spellcast"),w([E()],b.prototype,"getspell"),w([E()],b.prototype,"dopamine"),w([E()],b.prototype,"getUniqueId"),w([E()],b.prototype,"resendInvitation"),w([E()],b.prototype,"cancelInvitation"),w([E()],b.prototype,"getInvitations"),w([E()],b.prototype,"openIdLogin"),w([E()],b.prototype,"loginWithToken"),w([E()],b.prototype,"clientSecretRequest"),w([E()],b.prototype,"consumeTicket"),w([E()],b.prototype,"getConsumedTickets"),w([E()],b.prototype,"getTickets"),w([E()],b.prototype,"getRealtimeUsers"),w([E()],b.prototype,"sendInquiry"),w([E()],b.prototype,"blockAccount"),w([E()],b.prototype,"unblockAccount"),w([E()],b.prototype,"deleteAccount"),w([E()],b.prototype,"inviteUser"),w([E()],b.prototype,"createAccount"),w([E()],b.prototype,"grantAccess"),w([E()],b.prototype,"getRealtimeGroups"),w([E()],b.prototype,"postRealtime"),w([E()],b.prototype,"joinRealtime"),w([E()],b.prototype,"getProfile"),w([E()],b.prototype,"getFile"),w([E()],b.prototype,"secureRequest"),w([E()],b.prototype,"getFormResponse"),w([E()],b.prototype,"getRecords"),w([E()],b.prototype,"getTables"),w([E()],b.prototype,"getIndexes"),w([E()],b.prototype,"getTags"),w([E()],b.prototype,"deleteRecords"),w([E()],b.prototype,"resendSignupConfirmation"),w([E()],b.prototype,"recoverAccount"),w([E()],b.prototype,"getUsers"),w([E()],b.prototype,"disableAccount"),w([E()],b.prototype,"lastVerifiedEmail"),w([E()],b.prototype,"unsubscribeNewsletter"),w([E()],b.prototype,"subscribeNotification"),w([E()],b.prototype,"unsubscribeNotification"),w([E()],b.prototype,"vapidPublicKey"),w([E()],b.prototype,"pushNotification"),w([E()],b.prototype,"getNewsletters"),w([E()],b.prototype,"getNewsletterSubscription"),w([E()],b.prototype,"requestUsernameChange"),w([E()],b.prototype,"grantPrivateRecordAccess"),w([E()],b.prototype,"removePrivateRecordAccess"),w([E()],b.prototype,"listPrivateRecordAccess"),w([E()],b.prototype,"requestPrivateRecordAccessKey"),w([E()],b.prototype,"deleteFiles"),w([E()],b.prototype,"uploadFiles"),w([E()],b.prototype,"mock"),w([E({preventMultipleCalls:true})],b.prototype,"login"),w([E()],b.prototype,"logout"),w([E({preventMultipleCalls:true})],b.prototype,"signup"),w([E({preventMultipleCalls:true})],b.prototype,"resetPassword"),w([E({preventMultipleCalls:true})],b.prototype,"verifyEmail"),w([E({preventMultipleCalls:true})],b.prototype,"verifyPhoneNumber"),w([E({preventMultipleCalls:true})],b.prototype,"forgotPassword"),w([E({preventMultipleCalls:true})],b.prototype,"changePassword"),w([E({preventMultipleCalls:true})],b.prototype,"updateProfile"),w([E()],b.prototype,"postRecord"),w([E()],b.prototype,"getSubscriptions"),w([E()],b.prototype,"subscribe"),w([E()],b.prototype,"unsubscribe"),w([E()],b.prototype,"blockSubscriber"),w([E()],b.prototype,"unblockSubscriber"),w([E()],b.prototype,"subscribeNewsletter");var Ur={};
233
+ exports.Skapi=b;exports.SkapiError=a;exports.Types=Ur;//# sourceMappingURL=skapi.cjs.map
234
234
  //# sourceMappingURL=skapi.cjs.map