skapi-js 1.5.0-beta.4 → 1.5.0-beta.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/skapi.cjs CHANGED
@@ -1,4 +1,4 @@
1
- 'use strict';var amazonCognitoIdentityJs=require('amazon-cognito-identity-js'),Zn=require('cocochex'),Pt=require('qpass');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var Zn__default=/*#__PURE__*/_interopDefault(Zn);var Pt__default=/*#__PURE__*/_interopDefault(Pt);/**
1
+ 'use strict';var amazonCognitoIdentityJs=require('amazon-cognito-identity-js'),zn=require('cocochex'),St=require('qpass');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var zn__default=/*#__PURE__*/_interopDefault(zn);var St__default=/*#__PURE__*/_interopDefault(St);/**
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 Mn=Object.defineProperty;var Vn=Object.getOwnPropertyDescriptor;var te=(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=Vn(e,t),s=n.length-1,o;s>=0;s--)(o=n[s])&&(r=(o(e,t,r))||r);return r&&Mn(e,t,r),r};var J=typeof globalThis<"u"?globalThis:void 0,pe=J?.window;function $n(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(pe)pe.global=pe,pe.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=$n(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=te("fs"),r=te("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=te("fs"),s=te("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=te("fs"),r=te("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 ne="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",ve=BigInt(ne.length),qn=2*1024*1024,jn=["aud","cognito:username","event_id","exp","iat","iss","jti","origin_jti","secret_key","token_use"],Qe={auth_time:"log",sub:"user_id"},Bn=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f","g","h","i","j","k","l"],Ye=["us31","us72","ap51","ap22","ap41","eu71","ap21","us32","us71","af51","ap31","ap43","ap23","ap42","ca01","eu01","eu72","eu51","eu73","eu11","me51","sa31"],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 et(n){if(n===0)return ne[0];let e="";for(;n>0;)e=ne[n%62]+e,n=Math.floor(n/62);return e}function B(n){return n.split("").reverse().reduce((e,t,i)=>e+ne.indexOf(t)*62**i,0)}function ae(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 q(){return !De()&&typeof document<"u"&&typeof document.createElement=="function"}function me(n){let e;try{e=JSON.stringify(n);}catch{throw new a("Invalid data type.",{code:"INVALID_REQUEST"})}if(new Blob([e]).size>qn)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 be=q(),Kn=typeof SubmitEvent<"u",Qn=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===""||We(u.value)?s(i,u.name,true):He(u.value)?s(i,u.name,false):u.value&&s(i,u.name,u.value):u.type==="checkbox"&&(We(u.value)?s(i,u.name,false):He(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(be&&(n instanceof HTMLInputElement||n instanceof HTMLSelectElement||n instanceof HTMLTextAreaElement))return c(n),me(i),{data:i,files:r};if(be&&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 me(i),{data:i,files:r}}if(be&&Kn&&n instanceof SubmitEvent&&(n=n.target),be&&Qn&&n instanceof HTMLFormElement){let u=n.querySelectorAll("input"),d=n.querySelectorAll("select"),f=n.querySelectorAll("textarea");for(let l=0;l<d.length;l++)Je(i,d[l],s);for(let l=0;l<f.length;l++)Je(i,f[l],s);for(let l=0;l<u.length;l++)c(u[l]);return me(i),{data:i,files:r}}return me(n),{data:n,files:r}}function ce(n){let e={};for(let t in n){let i=n[t];if(!jn.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 Ne(n){if(n=Xn(n),n.split("-").length===7){let e=n.split("-"),t,i;try{t=Ye[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 tt(n,e){let t=Ye.indexOf(n.slice(0,4)),i=Bn[t],s=`${n.slice(4,-4)}-${i}${n.slice(-4)}-${e}`;return Gn(s)}function ze(n){let e=0n;for(let t of n){let i=ne.indexOf(t);if(i<0)throw new Error(`INVALID_PARAMETER: Invalid base62 character: ${t}`);e=e*ve+BigInt(i);}return e}function Ge(n,e=1){if(n<0n)throw new Error("INVALID_PARAMETER: Negative values are not supported.");if(n===0n)return "0".repeat(Math.max(1,e));let t="",i=n;for(;i>0n;){let r=Number(i%ve);t=ne[r]+t,i/=ve;}return t.length<e&&(t="0".repeat(e-t.length)+t),t}function Xe(n){if(n===0n)return Buffer.from([0]);let e=[],t=n;for(;t>0n;)e.push(Number(t&0xffn)),t>>=8n;return e.reverse(),Buffer.from(e)}function Ze(n){let e=0n;for(let t of n)e=(e<<8n)+BigInt(t);return e}function Wn(n){let e=String(n).replace(/-/g,"");if(!/^[0-9a-fA-F]{32}$/.test(e))throw new Error("INVALID_PARAMETER: Invalid UUID format.");return Buffer.from(e,"hex")}function Hn(n){let e=Buffer.from(n).toString("hex");return [e.slice(0,8),e.slice(8,12),e.slice(12,16),e.slice(16,20),e.slice(20)].join("-")}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.")}function zn(n,e=false){let t=String(n).replace(/-/g,"+").replace(/_/g,"/"),i=t.length%4?"=".repeat(4-t.length%4):"",r=Buffer.from(t+i,"base64");return e?JSON.parse(r.toString("utf8")):r}function Gn(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=ze(t),o=ze(i),c=Xe(s),u=Xe(o),d=Wn(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=Buffer.concat([Buffer.from([1,t.length,i.length,c.length,u.length]),c,u,d]);return `s1_${Jn(f).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}`}function Xn(n){let e=String(n);if(!e.startsWith("s1_"))return e;let t=zn(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=Ge(Ze(t.subarray(u,d)),r),h=Ge(Ze(t.subarray(d,f)),s),R=Hn(t.subarray(f,f+16));return `${l}-${h}-${R}`}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 rt(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 Ue(t)}async function it(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(Ue),t}async function st(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(Ue),t}async function ot(n){return w.bind(this)("register-ticket",Object.assign({exec:"reg"},n),{auth:true})}async function at(n){return w.bind(this)("register-ticket",Object.assign({exec:"unreg"},n),{auth:true})}async function ie(){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 nt(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=ce(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){nt.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(),S=A<R;if(this.log("getSession:currentTime",R),this.log("getSession:idTokenExp",A),this.log("getSession:isExpired",S),this.log("getSession:existingBearerToken",this.bearerToken),this.bearerToken=p.getJwtToken(),S||u||!h.isValid())nt.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:S=>{U=l.cognitoUser,e().then(E=>d(this.user));},onFailure:S=>{f(new a(S.message||"Failed to authenticate user.",{code:S.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:S,code:E}=ye(p),k=typeof p?.message=="string"?p.message:"";if(E==="NotAuthorizedException"?k.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"]),S.code==="SIGNUP_CONFIRMATION_NEEDED"&&(this.__request_signup_confirmation=h),A.length){let P=A[1],x=A[0];f(new a(x,{code:P,cause:p}));}else f(S);}});}),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}=ye(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 ye(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 ct(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 lt(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 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 ut(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=ce(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 le.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 le(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 dt(){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 gt(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 ft(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 le.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 ht(){await this.__connection;let n=await w.bind(this)("remove-account",{disable:this.__user.user_id},{auth:true});return await le.bind(this)(),n}async function pt(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 mt(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 bt(n){return mt.bind(this)("phone_number",n)}function _t(n){return mt.bind(this)("email",n)}async function yt(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}=ye(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 wt(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}=ye(r);i(o);}return}t("SUCCESS: Password has been changed.");});})}async function Et(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 Rt(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 At(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 It(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 G=null,Tt=typeof SubmitEvent<"u",fr=typeof HTMLFormElement<"u",de=q(),Le=0;function kt(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 St=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 hr(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 St.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 St.bind(this)({auth:e,type:"record",endpoints:t})+n+o;default:return g.Url(n)+o}}var ue={};function xt(){G&&(G.terminate(),G=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 hr.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 ie.bind(this)());let h={},{fetchMore:R=false,progress:p}=t?.fetchOptions||{};if(t?.fetchOptions&&Object.keys(t.fetchOptions).length){for(let T of ["limit","startKey","ascending"])t.fetchOptions.hasOwnProperty(T)&&(h[T]=t.fetchOptions[T]);h=g.Params(h,{limit:T=>{if(typeof T!="number")throw new a("Fetch limit should be a number.",{code:"INVALID_REQUEST"});if(T>1e3)throw new a("Fetch limit should be below 1000.",{code:"INVALID_REQUEST"});return T},startKey:T=>T,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 S=`${s}:${r?"auth":"public"}:${n}`,E=(()=>{if(e&&typeof e=="object"&&Object.keys(e).length&&!(de&&e instanceof FormData)){let N=function(v){return typeof v=="object"&&v!==null?Object.keys(v).sort().reduce(($,ee)=>(typeof v[ee]=="object"&&v[ee]!==null?$[ee]=N(v[ee]):$[ee]=v[ee],$),{}):v};return V.hash(S+"/"+JSON.stringify(N(e)))}return V.hash(S+"/"+u)})(),{requestKey:k,requestKeyWithStartKey:P}=pr.bind(this)({params:e,url:n,fetchMore:R,hashedParams:E});if(!k||k&&typeof k=="object")return k;if(this.log("requestKey",P),typeof P=="string"&&ue[P]instanceof Promise)return this.log("request:returning pending",P),ue[P];let x={Accept:"*/*"};if(Object.prototype.hasOwnProperty.call(t,"contentType")&&t.contentType!==void 0){let T=t.contentType===null?"application/x-www-form-urlencoded":t.contentType;T&&(x["Content-Type"]=T);}else x["Content-Type"]="application/json";f&&(x.Authorization=f);let L={public_identifier:this.__public_identifier,service:u,owner:d};x["Content-Meta"]=JSON.stringify(L);let j={headers:x};if(t?.responseType&&(j.responseType=t.responseType),s==="GET"){if(e){let T=[];if(de&&e instanceof FormData?T=Array.from(e.entries()).map(([N,v])=>{let $=typeof v=="string"?v:v.name;return encodeURIComponent(N)+"="+encodeURIComponent($)}):T=Object.keys(e).map(N=>{let v=e[N];return typeof v!="string"&&(v=JSON.stringify(v)),encodeURIComponent(N)+"="+encodeURIComponent(v)}),T.length){let N=l.includes("?")?l.endsWith("?")||l.endsWith("&")?"":"&":"?";l+=N+T.join("&");}}j.body=null;}else if(de&&e instanceof FormData)j.body=e;else if(x["Content-Type"]==="application/x-www-form-urlencoded"&&e&&typeof e=="object"){let T=new URLSearchParams;for(let N of Object.keys(e)){let v=e[N];T.append(N,typeof v=="string"?v:JSON.stringify(v));}j.body=T.toString();}else typeof e=="string"?j.body=e:j.body=e?JSON.stringify(e):null;if(j.method=s,G===null){let T={batchSize:this.requestBatchSize,breakWhenError:false,onProgress:N=>{this.onBatchProcess.forEach(v=>v(N));}};G=new Pt__default.default(T);}return this.log("request-opt",j),new Promise((T,N)=>{G.add([async()=>{let v=vt.bind(this)(l,j,p);ue[P]=v;try{let $=mr.bind(this)({hashedParam:k,requestKeyWithStartKey:P,url:n,fetched:await v});return delete ue[P],this.log("request:end",$),T($),$}catch($){throw delete ue[P],this.log("request:err",$),N($),$}}]);})}function pr(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 vt(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=kt(c);u!==null?setTimeout(()=>{vt(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 mr(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 Ee(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(Tt&&n instanceof SubmitEvent&&(n=n.target),fr&&n instanceof HTMLFormElement&&(n=new FormData(n)),!de||!(n instanceof FormData))throw new a('"fileList" should be a FormData or HTMLFormElement.',{code:"INVALID_PARAMETER"});let o={reserved_key:ae(),service:i,request:"post"};e?.record_id&&(o.id=e.record_id);let c,u=(f,l,h)=>new Promise((R,p)=>{c=new XMLHttpRequest,c.open("POST",f),c.onload=()=>{let A=c.responseText;try{A=JSON.parse(A);}catch{}if(c.status>=200&&c.status<300)R(A);else if(c.status===429){let S=c.getResponseHeader("Retry-After"),E=kt(S);E!==null?setTimeout(()=>{u(f,l,h).then(R,p);},E):p("Too many requests");}else p(A);},c.onerror=()=>p("Network error"),c.onabort=()=>p("Aborted"),c.ontimeout=()=>p("Timeout"),c.upload&&typeof h=="function"&&(c.upload.onprogress=h),c.send(l);});function d(f){let l="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";if(f===0)return l[0];let h="";for(;f>0;)h=l[f%62]+h,f=Math.floor(f/62);return h}return G===null&&(G=new Pt__default.default({batchSize:this.requestBatchSize,breakWhenError:false})),new Promise((f,l)=>{G.add([async()=>{let h=[],R=[],p=[];for(let[A,S]of n.entries()){if(!(S instanceof File))continue;let E=Object.assign({key:A+"/"+S.name,sizeKey:d(S.size),contentType:S.type||null},o),{fields:k=null,url:P,cdn:x}=await w.bind(this)("get-signed-url",E,{auth:!!this.__user});p.push(x);let C=new FormData;for(let L in k)C.append(L,k[L]);C.append("file",S);try{await u(P,C,typeof r=="function"?L=>r({status:"upload",progress:Oe(L.loaded,L.total),currentFile:S,completed:h,failed:R,loaded:L.loaded,total:L.total,abort:()=>c.abort()}):null),h.push(S);}catch{R.push(S);}}return f({completed:h,failed:R,bin_endpoints:p}),{completed:h,failed:R,bin_endpoints:p}}]);})}var we={};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(Tt&&c instanceof SubmitEvent){c.preventDefault();let E=window.location.href;d=c.target;let k=new URL(d.action);f=k.href;let P=f?f.match(/(?<=\{).*?(?=\})/g):"";if(P)for(let x of P){if(!x)continue;let C=d.querySelector(`[name="${x}"]`);if(C)if(C.type==="file")for(let L=0;L<=C.files.length-1;L++)C.files[L]&&(l[x]||(l[x]=[]),l[x].push(new Promise((j,T)=>{let N=new FileReader;N.onload=function(){j(N.result);},N.readAsDataURL(C.files[L]),N.onerror=T;})));else f=f.replace(`{${x}}`,C.value);}d.getAttribute("action")===null?u=false:h=k.href===E;}let R=async E=>{if(f)for(let k in l)l[k].length&&(f=f.replace(`{${k}}`,(await Promise.all(l[k])).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},S=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 we?.[E]||(we[E]=S().finally(()=>{delete we[E];})),we[E]}return S()};}}async function Dt(){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,_r=64,yr=128,wr=256,Er="\u{10FFFF}",Rr=/[\u0000-\u001F\u007F]|\u{10FFFF}/u,Ar=/[\/!*#]/;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(Rr.test(n)||n.includes(Er))throw new a(`"${e}" cannot include control characters or unsupported sentinel characters.`,{code:"INVALID_PARAMETER"});if(s&&Ar.test(n))throw new a(`"${e}" cannot include reserved delimiters: / ! * #`,{code:"INVALID_PARAMETER"});if(o&&n.startsWith("$"))throw new a(`"${e}" cannot start with "$".`,{code:"INVALID_PARAMETER"});return n}function Fe(n,e="table.name"){return X(n,e,{allowEmpty:false,maxLength:br,blockKeyDelimiters:true})}function Me(n,e="tag"){return X(n,e,{allowEmpty:false,maxLength:_r,blockKeyDelimiters:true})}function ge(n,e="index.name"){return X(n,e,{allowEmpty:false,maxLength:yr,blockKeyDelimiters:true,disallowLeadingDollar:true})}function Nt(n,e="index.value"){return X(n,e,{allowEmpty:true,maxLength:wr})}function Ut(n){if(!n.record_id&&!n.unique_id)return null;let e={};return n?.service&&(e.service=n.service),n?.owner&&(e.owner=n.owner),n?.record_id?e.record_id=X(n.record_id,"record_id",{allowEmpty:false,onlyAlphanumeric:true}):n?.unique_id&&(e.unique_id=n.unique_id),e}function Ve(n){if(n===void 0)return 0;if(typeof n=="number"){if(n>99||n<0)throw new a('"table.access_group" value should be within a range of 0 ~ 99.',{code:"INVALID_REQUEST"})}else if(typeof n=="string"){if(n={private:"private",public:0,authorized:1,admin:99}[n],n===void 0)throw new a('"table.access_group" is invalid.',{code:"INVALID_PARAMETER"})}else throw new a('"table.access_group" should be type: <number | string>.',{code:"INVALID_PARAMETER"});if(!this.__user&&n)throw new a("Unsigned users have no access to records with access group.",{code:"INVALID_REQUEST"});return n}var Re=4503599627370496;function Ae(n){if(typeof n=="number"){if(n>Re||n<-Re)throw new a(`Number value should be within range -${Re} ~ +${Re}`,{code:"INVALID_PARAMETER"});return n}if(typeof n=="boolean")return n;if(typeof n=="string")return Nt(n,"index.value");throw new a('"index.value" should be type: <number | boolean | string>.',{code:"INVALID_PARAMETER"})}function Ct(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"?Nt(n,"index.range"):n}var Ie={};async function se(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=Ir("!"+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],S=h[8],E=r(h[6]),k=f;E!=="public"&&(k=await Se.bind(this)(f,{dataType:"endpoint",_ref:u}));let P={access_group:E,filename:R,url:k,path:l,size:B(A),uploaded:B(S),getFile:(x,C)=>{let L={dataType:x||"download",progress:C,_ref:u,_update:P};return Se.bind(this)(k,L)}};return {pathKey:p,obj:P}}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 Ir(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 Lt(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(se.bind(this)(t[r]));return Promise.all(i)}async function Se(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:"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(C){throw this.log("getFile:new token error",C),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 P=l[6]==="**"?"**":parseInt(l[6]),x=this.user?.access_group??-1;if(this.user.user_id!==l[3]&&(P==="**"||x<P)){let C=l[5];if(this.__private_access_key[C]&&typeof this.__private_access_key[C]=="string")n+=`&p=${encodeURIComponent(this.__private_access_key[C])}`;else if(this.owner!==this.host)try{let L=await this.requestPrivateRecordAccessKey({record_id:C,reference_id:e?._ref});n+=`&p=${encodeURIComponent(L)}`;}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,k)=>{try{let P=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 x=new FileReader;x.onloadend=()=>E(x.result),x.readAsDataURL(P);}else E(P);}catch(P){k(P);}})}async function Ot(n,e=false){n=D(n,{ignoreEmpty:true}).data||{};let t="",i=Ut(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=>ge(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?"":Ae(d)},condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq"],range:d=>Ct(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 Ft(n,e){await this.__connection;let t=await Ot.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(se.bind(this)(r.list[o]));return r.list=await Promise.all(s),r}function Mt(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=>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=>ge(u,'"name" in "index_restrictions"'),value:u=>Ae(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),X(o,"reference.record_id",{allowEmpty:false,onlyAlphanumeric:true}))})}},index:{name:s=>ge(s,"index.name"),value:s=>Ae(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 Vt(n,e,t){if(await this.__connection,!e)throw new a('"config" argument is required.',{code:"INVALID_PARAMETER"});let i=Mt.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(q()&&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:S}=await Ee.bind(this)(p,A);h.bin?h.bin.push(...S):h.bin=S;}o&&typeof h?.reference_private_key=="string"&&(this.__private_access_key[o]=h.reference_private_key);let R=await se.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 $t(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=Mt.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})};i!==void 0&&(c.service=i),r!==void 0&&(c.owner=r);let u={auth:!!this.__user,method:"post"},d={};typeof s=="function"&&(d.progress=s),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=>se.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 Object.keys(this.__my_unique_ids).length&&window.sessionStorage.setItem(`${this.service}:uniqueids`,JSON.stringify(this.__my_unique_ids)),l}async function qt(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 jt(n,e){if(!n?.table)throw new a('"table" is required.',{code:"INVALID_PARAMETER"});let t=g.Params(n||{},{table:"string",index:s=>ge(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 Bt(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 Kt(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 Qt(n,e){await this.__connection;let t=await Ot.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 Wt(n){return Gt.bind(this)({record_id:n.record_id,user_id:n.user_id,execute:"add"})}function Ht(n){return Gt.bind(this)({record_id:n.record_id,user_id:n.user_id||null,execute:"remove"})}async function Jt(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 zt(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(Ie[e])return Ie[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 Ie[e];});return Ie[e]=i,i}function Gt(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={},O={},K={},H={},W={},Pe={},Te={};function Xt(n,e,t){n[e]||(n[e]=[]),n[e].push(t);}async function ke(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 ke(Te,e,r=>i.bind(this)(r,e,t)),await i.bind(this)(n,e,t)):await ke(Te,e,r=>i.bind(this)(r,e,t)):n&&Xt(Te,e,n);}async function je(n,e){if(this.log("receiveIceCandidate",n),I?.[e]&&I[e]?.remoteDescription&&I[e]?.remoteDescription?.type){if(!n)return ke(Pe,e,t=>I[e].addIceCandidate(t));await ke(Pe,e,t=>I[e].addIceCandidate(t)),await I[e].addIceCandidate(n);}else Xt(Pe,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 Te[s],delete Pe[s],O[s]&&Object.values(O[s]).forEach(o=>{o.readyState!=="closed"&&o.close();}),delete O[s],I?.[s]){I[s].connectionState!=="closed"&&(I[s].close(),e.send(JSON.stringify({action:"rtc",uid:s,content:{hungup:this.user.user_id},token:this.session.accessToken.jwtToken})));let o={type:"connectionstatechange",target:I[s],timestamp:new Date().toISOString(),state:I[s].connectionState,iceState:I[s].iceConnectionState,signalingState:I[s].signalingState};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 Zt(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 Yt(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 Zt(n.media),this.__mediaStream.getTracks().forEach(o=>{I[t].addTrack(o,this.__mediaStream);})),W[t]=e,O[t]||(O[t]={});for(let o=0;o<n.channels.length;o++){let c=n.channels[o];if(typeof c=="string")switch(c){case "text-chat":c={ordered:true,maxRetransmits:10,protocol:"text-chat"};break;case "file-transfer":c={ordered:false,maxPacketLifeTime:3e3,protocol:"file-transfer"};break;case "video-chat":c={ordered:true,maxRetransmits:10,protocol:"video-chat"};break;case "voice-chat":c={ordered:true,maxRetransmits:10,protocol:"voice-chat"};break;case "gaming":c={ordered:false,maxPacketLifeTime:100,protocol:"gaming"};break;default:c={ordered:true,maxRetransmits:10,protocol:"default"};break}let u=c.protocol||"default";if(Object.keys(O[t]).includes(u))throw new a(`Data channel with the protocol "${u}" already exists.`,{code:"INVALID_REQUEST"});let d=I[t].createDataChannel(u,c);O[t][u]=d;}for(let o in O[t]){let c=O[t][o];nn.bind(this)(t,c);}return tn.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:O[t],hangup:()=>Q.bind(this)({cid:t}),media:this.__mediaStream});}).bind(this);})}}function en(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 Zt(e.media),this.__mediaStream.getTracks().forEach(o=>{I[i].addTrack(o,this.__mediaStream);})),delete H[i],W[i]=t,O[i]||(O[i]={}),I[i].ondatachannel=o=>{this.log("ondatachannel",`received data channel "${o.channel.label}".`);let c=o.channel;O[i][c.label]=c,nn.bind(this)(i,c);},tn.bind(this)(i,["onnegotiationneeded"]),await qe.bind(this)(null,i),await je.bind(this)(null,i),r.send(JSON.stringify({action:"rtc",uid:i,content:{pickup:this.user.user_id},token:this.session.accessToken.jwtToken})),{target:I[i],channels:O[i],hangup:()=>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 Sr(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 tn(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=>{Sr.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 nn(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),O[n]&&(delete O[n][e.label],Object.keys(O[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,fe=true,oe=0;async function Pr(){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 rn(){if(typeof window>"u"||window._runningInNodeJS)throw new a("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});fe=true;let n=this.__socket?await this.__socket:this.__socket;Q.bind(this)({close_all:true}),Y&&Ke.bind(this)({group:null}),oe=0,Z&&(Z.terminate(),Z=null);try{n&&n.close();}catch{}return window.removeEventListener("visibilitychange",Be),this.__socket=null,null}async function xe(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(fe&&(Be=()=>{!document.hidden&&!fe&&xe.bind(this)(n,0,"reconnect");},this.__socket instanceof Promise))return this.__socket;Z&&(Z.terminate(),Z=null),this.__socket=new Promise(async i=>{await ie.bind(this)(),setTimeout(async()=>{let r=await Pr.bind(this)();r.onopen=()=>{fe=false,oe=0,t!=="reconnect"&&window.addEventListener("visibilitychange",Be),this.log("realtime onopen","Connected to WebSocket server."),n({type:"success",message:"Connected to WebSocket server."}),Y&&r.send(JSON.stringify({action:"joinRoom",rid:Y,token:this.session.accessToken.jwtToken}));let s=`
206
+ var Ln=Object.defineProperty;var On=Object.getOwnPropertyDescriptor;var ee=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var _=(n,e,t,i)=>{for(var r=On(e,t),s=n.length-1,o;s>=0;s--)(o=n[s])&&(r=(o(e,t,r))||r);return r&&Ln(e,t,r),r};var J=typeof globalThis<"u"?globalThis:void 0,he=J?.window;function Fn(n){if(Buffer)return Buffer.from(n).toString("base64");let e="",t=new Uint8Array(n),i=32768;for(let r=0;r<t.length;r+=i){let s=t.subarray(r,r+i);e+=String.fromCharCode.apply(null,Array.from(s));}if(typeof btoa=="function")return btoa(e);throw new Error("No base64 encoder available in this environment.")}if(he)he.global=he,he.global._runningInNodeJS=false;else if(J&&(J.global=J,typeof J.window>"u")){class n{constructor(){this.result=null;this.error=null;this.onload=null;this.onloadend=null;this.onerror=null;}readAsDataURL(i){i.arrayBuffer().then(r=>{let s=Fn(r),o=i.type||"application/octet-stream";this.result=`data:${o};base64,${s}`,this.onload&&this.onload({target:this}),this.onloadend&&this.onloadend({target:this});}).catch(r=>{this.error=r,this.onerror&&this.onerror({target:this});});}readAsArrayBuffer(i){i.arrayBuffer().then(r=>{this.result=r,this.onload&&this.onload({target:this}),this.onloadend&&this.onloadend({target:this});}).catch(r=>{this.error=r,this.onerror&&this.onerror({target:this});});}readAsText(i,r="utf-8"){i.text().then(s=>{this.result=s,this.onload&&this.onload({target:this}),this.onloadend&&this.onloadend({target:this});}).catch(s=>{this.error=s,this.onerror&&this.onerror({target:this});});}}J.FileReader=n;class e{constructor(){this.status=0;this.statusText="";this.readyState=0;this.responseText="";this.response=null;this.responseType="";this.responseURL="";this.timeout=0;this.withCredentials=false;this.onload=null;this.onerror=null;this.onabort=null;this.ontimeout=null;this.onprogress=null;this.onreadystatechange=null;this.upload={onprogress:null};this._method="GET";this._url="";this._headers={};this._aborted=false;}open(i,r){this._method=i,this._url=r,this.readyState=1;}setRequestHeader(i,r){this._headers[i]=r;}getResponseHeader(i){return null}abort(){this._aborted=true,this.onabort&&this.onabort({});}send(i){if(this._aborted)return;let r={method:this._method,headers:this._headers};i&&this._method!=="GET"&&this._method!=="HEAD"&&(r.body=i),fetch(this._url,r).then(async s=>{if(!this._aborted){if(this.status=s.status,this.statusText=s.statusText,this.responseURL=s.url,this.readyState=4,this.responseType==="blob")this.response=await s.blob();else if(this.responseType==="json")try{this.response=await s.json();}catch{this.response=null;}else this.responseType==="arraybuffer"?this.response=await s.arrayBuffer():(this.responseText=await s.text(),this.response=this.responseText);this.onload&&this.onload({});}}).catch(s=>{this._aborted||this.onerror&&this.onerror(s);});}}J.XMLHttpRequest=e,J.window={_runningInNodeJS:true,alert:t=>console.error("[Alert]",t),sessionStorage:{getItem:t=>null,setItem:(t,i)=>{},removeItem:t=>{}},localStorage:{getItem:t=>{let i=ee("fs"),r=ee("path");try{let s=r.resolve(process.cwd(),"states","localStorage",`${t}.skapi`);return i.existsSync(s)?i.readFileSync(s,"utf8"):null}catch{return null}},setItem:(t,i)=>{let r=ee("fs"),s=ee("path");try{let o=s.resolve(process.cwd(),"states","localStorage");r.existsSync(o)||r.mkdirSync(o,{recursive:!0});let c=s.resolve(o,`${t}.skapi`);r.writeFileSync(c,i,"utf8");}catch{}},removeItem:t=>{let i=ee("fs"),r=ee("path");try{let s=r.resolve(process.cwd(),"states","localStorage",`${t}.skapi`);i.existsSync(s)&&i.unlinkSync(s);}catch{}}},location:{href:"",origin:"",hostname:"",protocol:"",replace:t=>{}},navigator:{userAgent:`nodejs/${J?.process?.versions?.node||"unknown"}`,mediaDevices:{getUserMedia:async t=>{throw new Error("getUserMedia is not supported in Node.js environment.")}}},addEventListener:()=>{},removeEventListener:()=>{}};}var a=class extends Error{constructor(e,t){if(Array.isArray(e)&&e.length<=2){let i=e[1];if(e.length>2)for(let r=2;r<e.length&&typeof e[r]=="string";r++)i+=e[r];super((i||"Something went wrong.").trim()),this.name=t?.name||"SKAPI",this.code=t?.code||e[0]||"ERROR",t?.cause&&(this.cause=t.cause);}else super((e?.message||(typeof e=="string"?e:"Something went wrong.")).trim()),typeof e=="string"?(this.name=t?.name||"SKAPI",this.code=t?.code||"ERROR",t?.cause&&(this.cause=t.cause)):e instanceof Error?(this.cause=e,this.name=e.name,e.hasOwnProperty("code")&&(this.code=e.code)):typeof e=="object"&&e?.code&&e?.message&&(this.name=t?.name||"SKAPI",this.code=t?.code||"ERROR",this.cause=e?.cause);}};var te="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",xe=BigInt(te.length),Mn=2*1024*1024,Vn=["aud","cognito:username","event_id","exp","iat","iss","jti","origin_jti","secret_key","token_use"],Ke={auth_time:"log",sub:"user_id"},$n=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f","g","h","i","j","k","l"],Ze=["us31","us72","ap51","ap22","ap41","eu71","ap21","us32","us71","af51","ap31","ap43","ap23","ap42","ca01","eu01","eu72","eu51","eu73","eu11","me51","sa31"],p=class p{static hash(e){typeof e!="string"&&(console.warn("coercing non-string value to empty string"),e="");let t=p.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=p.ff(i,r,s,o,t[l],7,-680876936),o=p.ff(o,i,r,s,t[l+1],12,-389564586),s=p.ff(s,o,i,r,t[l+2],17,606105819),r=p.ff(r,s,o,i,t[l+3],22,-1044525330),i=p.ff(i,r,s,o,t[l+4],7,-176418897),o=p.ff(o,i,r,s,t[l+5],12,1200080426),s=p.ff(s,o,i,r,t[l+6],17,-1473231341),r=p.ff(r,s,o,i,t[l+7],22,-45705983),i=p.ff(i,r,s,o,t[l+8],7,1770035416),o=p.ff(o,i,r,s,t[l+9],12,-1958414417),s=p.ff(s,o,i,r,t[l+10],17,-42063),r=p.ff(r,s,o,i,t[l+11],22,-1990404162),i=p.ff(i,r,s,o,t[l+12],7,1804603682),o=p.ff(o,i,r,s,t[l+13],12,-40341101),s=p.ff(s,o,i,r,t[l+14],17,-1502002290),r=p.ff(r,s,o,i,t[l+15],22,1236535329),i=p.gg(i,r,s,o,t[l+1],5,-165796510),o=p.gg(o,i,r,s,t[l+6],9,-1069501632),s=p.gg(s,o,i,r,t[l+11],14,643717713),r=p.gg(r,s,o,i,t[l],20,-373897302),i=p.gg(i,r,s,o,t[l+5],5,-701558691),o=p.gg(o,i,r,s,t[l+10],9,38016083),s=p.gg(s,o,i,r,t[l+15],14,-660478335),r=p.gg(r,s,o,i,t[l+4],20,-405537848),i=p.gg(i,r,s,o,t[l+9],5,568446438),o=p.gg(o,i,r,s,t[l+14],9,-1019803690),s=p.gg(s,o,i,r,t[l+3],14,-187363961),r=p.gg(r,s,o,i,t[l+8],20,1163531501),i=p.gg(i,r,s,o,t[l+13],5,-1444681467),o=p.gg(o,i,r,s,t[l+2],9,-51403784),s=p.gg(s,o,i,r,t[l+7],14,1735328473),r=p.gg(r,s,o,i,t[l+12],20,-1926607734),i=p.hh(i,r,s,o,t[l+5],4,-378558),o=p.hh(o,i,r,s,t[l+8],11,-2022574463),s=p.hh(s,o,i,r,t[l+11],16,1839030562),r=p.hh(r,s,o,i,t[l+14],23,-35309556),i=p.hh(i,r,s,o,t[l+1],4,-1530992060),o=p.hh(o,i,r,s,t[l+4],11,1272893353),s=p.hh(s,o,i,r,t[l+7],16,-155497632),r=p.hh(r,s,o,i,t[l+10],23,-1094730640),i=p.hh(i,r,s,o,t[l+13],4,681279174),o=p.hh(o,i,r,s,t[l],11,-358537222),s=p.hh(s,o,i,r,t[l+3],16,-722521979),r=p.hh(r,s,o,i,t[l+6],23,76029189),i=p.hh(i,r,s,o,t[l+9],4,-640364487),o=p.hh(o,i,r,s,t[l+12],11,-421815835),s=p.hh(s,o,i,r,t[l+15],16,530742520),r=p.hh(r,s,o,i,t[l+2],23,-995338651),i=p.ii(i,r,s,o,t[l],6,-198630844),o=p.ii(o,i,r,s,t[l+7],10,1126891415),s=p.ii(s,o,i,r,t[l+14],15,-1416354905),r=p.ii(r,s,o,i,t[l+5],21,-57434055),i=p.ii(i,r,s,o,t[l+12],6,1700485571),o=p.ii(o,i,r,s,t[l+3],10,-1894986606),s=p.ii(s,o,i,r,t[l+10],15,-1051523),r=p.ii(r,s,o,i,t[l+1],21,-2054922799),i=p.ii(i,r,s,o,t[l+8],6,1873313359),o=p.ii(o,i,r,s,t[l+15],10,-30611744),s=p.ii(s,o,i,r,t[l+6],15,-1560198380),r=p.ii(r,s,o,i,t[l+13],21,1309151649),i=p.ii(i,r,s,o,t[l+4],6,-145523070),o=p.ii(o,i,r,s,t[l+11],10,-1120210379),s=p.ii(s,o,i,r,t[l+2],15,718787259),r=p.ii(r,s,o,i,t[l+9],21,-343485551),i=p.ad(i,c),r=p.ad(r,u),s=p.ad(s,d),o=p.ad(o,f);return p.rh(i)+p.rh(r)+p.rh(s)+p.rh(o)}static rh(e){let t="";for(let i=0;i<=3;i++)t+=p.alphabet.charAt(e>>i*8+4&15)+p.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 p.ad(p.rl(p.ad(p.ad(t,e),p.ad(r,o)),s),i)}static ff(e,t,i,r,s,o,c){return p.cm(t&i|~t&r,e,t,s,o,c)}static gg(e,t,i,r,s,o,c){return p.cm(t&r|i&~r,e,t,s,o,c)}static hh(e,t,i,r,s,o,c){return p.cm(t^i^r,e,t,s,o,c)}static ii(e,t,i,r,s,o,c){return p.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}};p.alphabet="0123456789abcdef";var $=p;function Ye(n){if(n===0)return te[0];let e="";for(;n>0;)e=te[n%62]+e,n=Math.floor(n/62);return e}function B(n){return n.split("").reverse().reduce((e,t,i)=>e+te.indexOf(t)*62**i,0)}function se(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 q(){return !De()&&typeof document<"u"&&typeof document.createElement=="function"}function pe(n){let e;try{e=JSON.stringify(n);}catch{throw new a("Invalid data type.",{code:"INVALID_REQUEST"})}if(new Blob([e]).size>Mn)throw new a("Data should not exceed 2MB",{code:"INVALID_REQUEST"})}function Qe(n){return n===""||n==="on"||n==="true"}function We(n){return n==="false"}function He(n,e,t){e.name&&t(n,e.name,e.value);}var me=q(),qn=typeof SubmitEvent<"u",jn=typeof HTMLFormElement<"u";function v(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 m=R.replace("]",""),I=Number(m);return !isNaN(I)&&!m.includes(".")?m=I:(m[0]==='"'&&m[m.length-1]==='"'||m[0]==="'"&&m[m.length-1]==="'")&&(m=m.replace(/"/g,"").replace(/'/g,"")),m}),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 m=l[R];R<l.length-1?(h[m]===void 0&&(typeof l[R+1]=="number"?h[m]=[]:h[m]={}),h=h[m]):h[m]===void 0?h[m]=f:Array.isArray(h[m])?h[m].push(f):h[m]=[h[m],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===""||Qe(u.value)?s(i,u.name,true):We(u.value)?s(i,u.name,false):u.value&&s(i,u.name,u.value):u.type==="checkbox"&&(Qe(u.value)?s(i,u.name,false):We(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&&qn&&n instanceof SubmitEvent&&(n=n.target),me&&jn&&n instanceof HTMLFormElement){let u=n.querySelectorAll("input"),d=n.querySelectorAll("select"),f=n.querySelectorAll("textarea");for(let l=0;l<d.length;l++)He(i,d[l],s);for(let l=0;l<f.length;l++)He(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 oe(n){let e={};for(let t in n){let i=n[t];if(!Vn.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 ve(n){if(n=Jn(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 et(n,e){let t=Ze.indexOf(n.slice(0,4)),i=$n[t],s=`${n.slice(4,-4)}-${i}${n.slice(-4)}-${e}`;return Hn(s)}function Je(n){let e=0n;for(let t of n){let i=te.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=te[r]+t,i/=xe;}return t.length<e&&(t="0".repeat(e-t.length)+t),t}function Ge(n){if(n===0n)return Buffer.from([0]);let e=[],t=n;for(;t>0n;)e.push(Number(t&0xffn)),t>>=8n;return e.reverse(),Buffer.from(e)}function Xe(n){let e=0n;for(let t of n)e=(e<<8n)+BigInt(t);return e}function Bn(n){let e=String(n).replace(/-/g,"");if(!/^[0-9a-fA-F]{32}$/.test(e))throw new Error("INVALID_PARAMETER: Invalid UUID format.");return Buffer.from(e,"hex")}function Kn(n){let e=Buffer.from(n).toString("hex");return [e.slice(0,8),e.slice(8,12),e.slice(12,16),e.slice(16,20),e.slice(20)].join("-")}function Qn(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.")}function Wn(n,e=false){let t=String(n).replace(/-/g,"+").replace(/_/g,"/"),i=t.length%4?"=".repeat(4-t.length%4):"",r=Buffer.from(t+i,"base64");return e?JSON.parse(r.toString("utf8")):r}function Hn(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=Je(t),o=Je(i),c=Ge(s),u=Ge(o),d=Bn(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=Buffer.concat([Buffer.from([1,t.length,i.length,c.length,u.length]),c,u,d]);return `s1_${Qn(f).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}`}function Jn(n){let e=String(n);if(!e.startsWith("s1_"))return e;let t=Wn(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(Xe(t.subarray(u,d)),r),h=ze(Xe(t.subarray(d,f)),s),R=Kn(t.subarray(f,f+16));return `${l}-${h}-${R}`}function Gn(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 Xn(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 Zn(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 Yn(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 er(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 tr(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 nr(n,e,t=[],i){let r=v(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:Gn,PhoneNumber:Xn,Birthdate:Zn,Password:Yn,Email:er,Url:tr,Params:nr};var N=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 nt(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 rt(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 it(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 st(n){return w.bind(this)("register-ticket",Object.assign({exec:"reg"},n),{auth:true})}async function ot(n){return w.bind(this)("register-ticket",Object.assign({exec:"unreg"},n),{auth:true})}async function re(){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 M.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 tt(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 M(){if(!this.userPool)throw new a("User pool is missing",{code:"INVALID_REQUEST"});let n=()=>{let s=N.getSignInUserSession().getIdToken().payload||null,o=oe(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),N=this.userPool.getCurrentUser(),!N){this.log("getSession:cognitoUser",N),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};N.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){tt.bind(this)(h,N).then(E=>o(f(E))).catch(c);return}let R=Math.floor(Date.now()/1e3),m=h.getIdToken(),I=m.getExpiration(),S=I<R;if(this.log("getSession:currentTime",R),this.log("getSession:idTokenExp",I),this.log("getSession:isExpired",S),this.log("getSession:existingBearerToken",this.bearerToken),this.bearerToken=m.getJwtToken(),S||u||!h.isValid())tt.bind(this)(h,N).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+"-"+$.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:(m,I)=>{this.__disabledAccount=null,this.__request_signup_confirmation=h,m["custom:signup_ticket"]==="PASS"||m["custom:signup_ticket"]==="MEMBER"||m["custom:signup_ticket"]==="OIDPASS"?l.cognitoUser.completeNewPasswordChallenge(o,{},{onSuccess:S=>{N=l.cognitoUser,e().then(E=>d(this.user));},onFailure:S=>{f(new a(S.message||"Failed to authenticate user.",{code:S.code}));}}):f(new a("User's signup confirmation is required.",{code:"SIGNUP_CONFIRMATION_NEEDED"}));},onSuccess:m=>e({skipUserUpdateEventTrigger:true}).then(I=>{this.__disabledAccount=null,this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user),d(this.user);}),onFailure:m=>{let I=[],{parsed:S,code:E}=_e(m),x=typeof m?.message=="string"?m.message:"";if(E==="NotAuthorizedException"?x.includes("User is disabled.")?(this.__disabledAccount=h,I=["This account is disabled.","USER_IS_DISABLED"]):u?I=["The account already exists.","ACCOUNT_EXISTS"]:I=["Incorrect username or password.","INCORRECT_USERNAME_OR_PASSWORD"]:E==="UserNotFoundException"?I=["Incorrect username or password.","INCORRECT_USERNAME_OR_PASSWORD"]:E==="UserNotConfirmedException"?(this.__request_signup_confirmation=h,I=["User's signup confirmation is required.","SIGNUP_CONFIRMATION_NEEDED"]):(E==="TooManyRequestsException"||E==="LimitExceededException")&&(I=["Too many attempts. Please try again later.","REQUEST_EXCEED"]),S.code==="SIGNUP_CONFIRMATION_NEEDED"&&(this.__request_signup_confirmation=h),I.length){let P=I[1],D=I[0];f(new a(D,{code:P,cause:m}));}else f(S);}});}),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),m=[];R==="UsernameExistsException"?m=["The account already exists.","EXISTS"]:R==="InvalidPasswordException"?m=["Invalid password. Password must be at least 6 characters.","INVALID_PARAMETER"]:R==="InvalidParameterException"?m=[h.message||"Invalid parameter.","INVALID_PARAMETER"]:R==="TooManyRequestsException"||R==="LimitExceededException"?m=["Too many attempts. Please try again later.","REQUEST_EXCEED"]:R==="CodeDeliveryFailureException"?m=["Failed to deliver verification code.","CODE_DELIVERY_FAILURE"]:R==="UserLambdaValidationException"&&(m=[h.message||"Signup validation failed.","INVALID_REQUEST"]),m.length?d(new a(m[0],{code:m[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 at(n){await this.__authConnection;let e=n?.refreshToken||false;if(!e)return this.user;try{return await M.bind(this)().getSession(Object.assign({skipUserUpdateEventTrigger:!e,refreshToken:e},n)),this.user}catch{return null}}async function ct(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 M.bind(this)().authenticateUser(i,r,true,true),openid:e.openid}}function cr(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 lr(n){let e=n.split(".");if(e.length!==3)throw new Error("Invalid JWT format");let i=e[1].replace(/-/g,"+").replace(/_/g,"/"),r=cr(i);return JSON.parse(r)}async function lt(n){await this.__authConnection,this.log("loginWithToken:params",n),n=g.Params(n,{idToken:"string",accessToken:"string",refreshToken:"string"},["idToken"]);let e=lr(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=oe(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),N=new amazonCognitoIdentityJs.CognitoUser(i),N.setSignInUserSession(this.session),this.log("loginWithToken:cognitoUserRestored",{cognitoUserType:typeof N,cognitoUserKeys:Object.keys(N||{}),cognitoUser:N});}}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 V(){return await this.__connection,this.__user?.service===this.service?this.__user?.owner===this.host:(await ae.bind(this)(),false)}async function z(n=false){let e=null;N&&(n?e=new Promise((i,r)=>{N.globalSignOut({onSuccess:s=>{this.log("globalSignOut:success",s),i(s);},onFailure:s=>{this.log("globalSignOut:error",s),r(s);}});}):N.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 ae(n){await this.__connection;let{data:e}=v(n);return await z.bind(this)(e?.global),"SUCCESS: The user has been logged out."}async function ut(){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 dt(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 Ue(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 M.bind(this)().authenticateUser(e.username||e.email,e.password)}async function gt(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 ae.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=M.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 M.bind(this)().signup(s.cognitoUsername,i.password,u),i.signup_confirmation?(N=s.cognitoUser,this.__request_signup_confirmation=s.cognitoUsername,"SUCCESS: The account has been created. User's signup confirmation is required."):r?Ue.bind(this)({email:i.username||i.email,password:i.password}):"SUCCESS: The account has been created."}async function ft(){await this.__connection;let n=await w.bind(this)("remove-account",{disable:this.__user.user_id},{auth:true});return await ae.bind(this)(),n}async function ht(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)=>{M.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 pt(n,e){await this.__connection;let t;if(!N)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?M.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?N?.verifyAttribute(n,t,s):(s.inputVerificationCode=null,N?.getAttributeVerificationCode(n,s));})}function mt(n){return pt.bind(this)("phone_number",n)}function bt(n){return pt.bind(this)("email",n)}async function _t(n){await this.__connection;let e=g.Params(n,{email:t=>g.Email(t)},["email"]);return new Promise(async(t,i)=>{M.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 yt(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)=>{N.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 wt(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+"-"+$.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)=>{N?.updateAttributes(r,(c,u)=>{c&&o([c?.code||c?.name,c?.message||"Failed to update user settings."]),s(u);});}),await M.bind(this)().getSession({refreshToken:true}),this.user}return this.user}async function Et(n,e){n=v(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 Rt(n){await this.__connection;let e=await w.bind(this)("last-verified-email",n,{auth:true});return e.includes("SUCCESS")?(await M.bind(this)().getSession({refreshToken:true}),this.user):e}async function At(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 G=null,Tt=typeof SubmitEvent<"u",ur=typeof HTMLFormElement<"u",le=q(),Ce=0;function Pt(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 It=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,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[Ce%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[Ce%o.length]}throw new a("Invalid gateway type.",{code:"INVALID_REQUEST"})};async function dr(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 It.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 It.bind(this)({auth:e,type:"record",endpoints:t})+n+o;default:return g.Url(n)+o}}var ce={};function kt(){G&&(G.terminate(),G=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 dr.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 re.bind(this)());let h={},{fetchMore:R=false,progress:m}=t?.fetchOptions||{};if(t?.fetchOptions&&Object.keys(t.fetchOptions).length){for(let T of ["limit","startKey","ascending"])t.fetchOptions.hasOwnProperty(T)&&(h[T]=t.fetchOptions[T]);h=g.Params(h,{limit:T=>{if(typeof T!="number")throw new a("Fetch limit should be a number.",{code:"INVALID_REQUEST"});if(T>1e3)throw new a("Fetch limit should be below 1000.",{code:"INVALID_REQUEST"});return T},startKey:T=>T,ascending:"boolean"});}let I=i?.ignoreService?{}:{service:u,owner:d};Object.assign(I,h),e=v(e).data,e?e&&typeof e=="object"&&(e=Object.assign(I,e)):e=I;let S=`${s}:${r?"auth":"public"}:${n}`,E=(()=>{if(e&&typeof e=="object"&&Object.keys(e).length&&!(le&&e instanceof FormData)){let T=function(k){return typeof k=="object"&&k!==null?Object.keys(k).sort().reduce((U,F)=>(typeof k[F]=="object"&&k[F]!==null?U[F]=T(k[F]):U[F]=k[F],U),{}):k};return $.hash(S+"/"+JSON.stringify(T(e)))}return $.hash(S+"/"+u)})(),{requestKey:x,requestKeyWithStartKey:P}=gr.bind(this)({params:e,url:n,fetchMore:R,hashedParams:E});if(!x||x&&typeof x=="object")return x;if(this.log("requestKey",P),typeof P=="string"&&ce[P]instanceof Promise)return this.log("request:returning pending",P),ce[P];let D={Accept:"*/*"};if(Object.prototype.hasOwnProperty.call(t,"contentType")&&t.contentType!==void 0){let T=t.contentType===null?"application/x-www-form-urlencoded":t.contentType;T&&(D["Content-Type"]=T);}else D["Content-Type"]="application/json";f&&(D.Authorization=f);let L={public_identifier:this.__public_identifier,service:u,owner:d};D["Content-Meta"]=JSON.stringify(L);let j={headers:D};if(t?.responseType&&(j.responseType=t.responseType),s==="GET"){if(e){let T=[];if(le&&e instanceof FormData?T=Array.from(e.entries()).map(([k,U])=>{let F=typeof U=="string"?U:U.name;return encodeURIComponent(k)+"="+encodeURIComponent(F)}):T=Object.keys(e).map(k=>{let U=e[k];return typeof U!="string"&&(U=JSON.stringify(U)),encodeURIComponent(k)+"="+encodeURIComponent(U)}),T.length){let k=l.includes("?")?l.endsWith("?")||l.endsWith("&")?"":"&":"?";l+=k+T.join("&");}}j.body=null;}else if(le&&e instanceof FormData)j.body=e;else if(D["Content-Type"]==="application/x-www-form-urlencoded"&&e&&typeof e=="object"){let T=new URLSearchParams;for(let k of Object.keys(e)){let U=e[k];T.append(k,typeof U=="string"?U:JSON.stringify(U));}j.body=T.toString();}else typeof e=="string"?j.body=e:j.body=e?JSON.stringify(e):null;if(j.method=s,G===null){let T={batchSize:this.requestBatchSize,breakWhenError:false,onProgress:k=>{this.onBatchProcess.forEach(U=>U(k));}};G=new St__default.default(T);}return this.log("request-opt",j),new Promise((T,k)=>{G.add([async()=>{let U=xt.bind(this)(l,j,m);ce[P]=U;try{let F=fr.bind(this)({hashedParam:x,requestKeyWithStartKey:P,url:n,fetched:await U});return delete ce[P],this.log("request:end",F),T(F),F}catch(F){throw delete ce[P],this.log("request:err",F),k(F),F}}]);})}function gr(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+$.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+=$.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 xt(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=Pt(c);u!==null?setTimeout(()=>{xt(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: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 fr(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(Tt&&n instanceof SubmitEvent&&(n=n.target),ur&&n instanceof HTMLFormElement&&(n=new FormData(n)),!le||!(n instanceof FormData))throw new a('"fileList" should be a FormData or HTMLFormElement.',{code:"INVALID_PARAMETER"});let o={reserved_key:se(),service:i,request:"post"};e?.record_id&&(o.id=e.record_id);let c,u=(f,l,h)=>new Promise((R,m)=>{c=new XMLHttpRequest,c.open("POST",f),c.onload=()=>{let I=c.responseText;try{I=JSON.parse(I);}catch{}if(c.status>=200&&c.status<300)R(I);else if(c.status===429){let S=c.getResponseHeader("Retry-After"),E=Pt(S);E!==null?setTimeout(()=>{u(f,l,h).then(R,m);},E):m("Too many requests");}else m(I);},c.onerror=()=>m("Network error"),c.onabort=()=>m("Aborted"),c.ontimeout=()=>m("Timeout"),c.upload&&typeof h=="function"&&(c.upload.onprogress=h),c.send(l);});function d(f){let l="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";if(f===0)return l[0];let h="";for(;f>0;)h=l[f%62]+h,f=Math.floor(f/62);return h}return G===null&&(G=new St__default.default({batchSize:this.requestBatchSize,breakWhenError:false})),new Promise((f,l)=>{G.add([async()=>{let h=[],R=[],m=[];for(let[I,S]of n.entries()){if(!(S instanceof File))continue;let E=Object.assign({key:I+"/"+S.name,sizeKey:d(S.size),contentType:S.type||null},o),{fields:x=null,url:P,cdn:D}=await w.bind(this)("get-signed-url",E,{auth:!!this.__user});m.push(D);let C=new FormData;for(let L in x)C.append(L,x[L]);C.append("file",S);try{await u(P,C,typeof r=="function"?L=>r({status:"upload",progress:Le(L.loaded,L.total),currentFile:S,completed:h,failed:R,loaded:L.loaded,total:L.total,abort:()=>c.abort()}):null),h.push(S);}catch{R.push(S);}}return f({completed:h,failed:R,bin_endpoints:m}),{completed:h,failed:R,bin_endpoints:m}}]);})}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(Tt&&c instanceof SubmitEvent){c.preventDefault();let E=window.location.href;d=c.target;let x=new URL(d.action);f=x.href;let P=f?f.match(/(?<=\{).*?(?=\})/g):"";if(P)for(let D of P){if(!D)continue;let C=d.querySelector(`[name="${D}"]`);if(C)if(C.type==="file")for(let L=0;L<=C.files.length-1;L++)C.files[L]&&(l[D]||(l[D]=[]),l[D].push(new Promise((j,T)=>{let k=new FileReader;k.onload=function(){j(k.result);},k.readAsDataURL(C.files[L]),k.onerror=T;})));else f=f.replace(`{${D}}`,C.value);}d.getAttribute("action")===null?u=false:h=x.href===E;}let R=async E=>{if(f)for(let x in l)l[x].length&&(f=f.replace(`{${x}}`,(await Promise.all(l[x])).join(",")));return d&&u&&(window.sessionStorage.setItem(`${this.service}:${$.hash(f)}`,JSON.stringify(E)),h?window.location.replace(f):window.location.href=f),E},m,I=E=>{throw E instanceof a?E.name=i+"()":E=E instanceof Error?E:new a(E,{name:i+"()"}),E},S=async()=>{try{if(m=s.bind(this)(...o),m instanceof Promise){let E=await m;return R(E)}return R(m)}catch(E){throw I(E)}};if(e){let E=`${i}:${this?.__public_identifier||""}:${this?.service||""}:${this?.owner||""}`;return ye?.[E]||(ye[E]=S().finally(()=>{delete ye[E];})),ye[E]}return S()};}}async function Dt(){await this.__connection;let n=`${this.service}:${$.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 hr=128,pr=64,mr=128,br=256,_r="\u{10FFFF}",yr=/[\u0000-\u001F\u007F]|\u{10FFFF}/u,wr=/[\/!*#]/;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(yr.test(n)||n.includes(_r))throw new a(`"${e}" cannot include control characters or unsupported sentinel characters.`,{code:"INVALID_PARAMETER"});if(s&&wr.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:hr,blockKeyDelimiters:true})}function Fe(n,e="tag"){return X(n,e,{allowEmpty:false,maxLength:pr,blockKeyDelimiters:true})}function ue(n,e="index.name"){return X(n,e,{allowEmpty:false,maxLength:mr,blockKeyDelimiters:true,disallowLeadingDollar:true})}function vt(n,e="index.value"){return X(n,e,{allowEmpty:true,maxLength:br})}function Nt(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 vt(n,"index.value");throw new a('"index.value" should be type: <number | boolean | string>.',{code:"INVALID_PARAMETER"})}function Ut(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"?vt(n,"index.range"):n}var Ae={};async function de(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=Er("!"+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]),m=decodeURIComponent(h[10]),I=h[9],S=h[8],E=r(h[6]),x=f;E!=="public"&&(x=await Ie.bind(this)(f,{dataType:"endpoint",_ref:u}));let P={access_group:E,filename:R,url:x,path:l,size:B(I),uploaded:B(S),getFile:(D,C)=>{let L={dataType:D||"download",progress:C,_ref:u,_update:P};return Ie.bind(this)(x,L)}};return {pathKey:m,obj:P}}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 Er(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 Ct(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(de.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:"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 m=n.split("/").slice(-1)[0],I=e.expires;if(I){if(!o)throw new a("Expires option can only be used on skapi cdn endpoints.",{code:"INVALID_PARAMETER"});if(I<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:I};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 M.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(C){throw this.log("getFile:new token error",C),new a("User login is required.",{code:"INVALID_REQUEST"})}}let x=this.bearerToken||this.session?.idToken?.jwtToken;if(!x||!this.user?.user_id)throw new a("User login is required.",{code:"INVALID_REQUEST"});n+=`${n.includes("?")?"&":"?"}t=${encodeURIComponent(x)}`;let P=l[6]==="**"?"**":parseInt(l[6]),D=this.user?.access_group??-1;if(this.user.user_id!==l[3]&&(P==="**"||D<P)){let C=l[5];if(this.__private_access_key[C]&&typeof this.__private_access_key[C]=="string")n+=`&p=${encodeURIComponent(this.__private_access_key[C])}`;else if(this.owner!==this.host)try{let L=await this.requestPrivateRecordAccessKey({record_id:C,reference_id:e?._ref});n+=`&p=${encodeURIComponent(L)}`;}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",m),E.target="_blank",E.click(),document.body.removeChild(E),null}return new Promise(async(E,x)=>{try{let P=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 D=new FileReader;D.onloadend=()=>E(D.result),D.readAsDataURL(P);}else E(P);}catch(P){x(P);}})}async function Lt(n,e=false){n=v(n,{ignoreEmpty:true}).data||{};let t="",i=Nt(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 V.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=>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=>ue(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=>Ut(d,u)},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 Ot(n,e){await this.__connection;let t=await Lt.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(de.bind(this)(r.list[o]));return r.list=await Promise.all(s),r}function Rr(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:u=>ue(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),X(o,"reference.record_id",{allowEmpty:false,onlyAlphanumeric:true}))})}},index:{name:s=>ue(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 Ft(n,e,t){if(await this.__connection,!e)throw new a('"config" argument is required.',{code:"INVALID_PARAMETER"});let i=Rr.bind(this)(e),r=i.config,s=i.progress,o=i.is_reference_post,c={auth:!!this.__user,method:"post"},u=[],d=v(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(q()&&u.length){let m=new FormData;for(let E of u)m.append(E.name,E.file,E.file.name);let I={record_id:h.rec,progress:s};r.hasOwnProperty("service")&&(I.service=r.service);let{bin_endpoints:S}=await we.bind(this)(m,I);h.bin?h.bin.push(...S):h.bin=S;}o&&typeof h?.reference_private_key=="string"&&(this.__private_access_key[o]=h.reference_private_key);let R=await de.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 Mt(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 Vt(n,e){if(!n?.table)throw new a('"table" is required.',{code:"INVALID_PARAMETER"});let t=g.Params(n||{},{table:"string",index:s=>ue(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 $t(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 qt(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 jt(n,e){await this.__connection;let t=await Lt.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 Bt(n){return Ht.bind(this)({record_id:n.record_id,user_id:n.user_id,execute:"add"})}function Kt(n){return Ht.bind(this)({record_id:n.record_id,user_id:n.user_id||null,execute:"remove"})}async function Qt(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 Wt(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 Ht(n){n.execute;let t=g.Params(n,{record_id:"string",user_id:i=>{if(!i)throw new a("User ID is required.",{code:"INVALID_PARAMETER"});let r=i;if(typeof r=="string"&&(r=[r]),r.length>100)throw new a("Cannot process more than 100 users at once.",{code:"INVALID_REQUEST"});for(let s of r)g.UserId(s,'User ID in "user_id"');return r},execute:["add","remove"]},["execute","record_id","user_id"]);return t.user_id||(t.user_id=null),w.bind(this)("grant-private-access",t,{auth:true})}var A={},O={},K={},H={},W={},Se={},Te={};function Jt(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 $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 A[s].setRemoteDescription(new RTCSessionDescription(r));let c=await A[s].createAnswer();await A[s].setLocalDescription(c),o.send(JSON.stringify({action:"rtc",uid:s,content:{sdpanswer:c},token:this.session.accessToken.jwtToken}));}A?.[e]?n?(await Pe(Te,e,r=>i.bind(this)(r,e,t)),await i.bind(this)(n,e,t)):await Pe(Te,e,r=>i.bind(this)(r,e,t)):n&&Jt(Te,e,n);}async function qe(n,e){if(this.log("receiveIceCandidate",n),A?.[e]&&A[e]?.remoteDescription&&A[e]?.remoteDescription?.type){if(!n)return Pe(Se,e,t=>A[e].addIceCandidate(t));await Pe(Se,e,t=>A[e].addIceCandidate(t)),await A[e].addIceCandidate(n);}else Jt(Se,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 Te[s],delete Se[s],O[s]&&Object.values(O[s]).forEach(o=>{o.readyState!=="closed"&&o.close();}),delete O[s],A?.[s]){A[s].connectionState!=="closed"&&(A[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:A[s],timestamp:new Date().toISOString(),state:A[s].connectionState,iceState:A[s].iceConnectionState,signalingState:A[s].signalingState};W[s]&&W[s](o),this.log("closeRTC",o);}delete W[s],delete H[s],delete K[s],delete A[s];};if(i)for(let s in A)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 zt(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 Gt(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}]};A?.[t]||(A[t]=new RTCPeerConnection(s)),n?.media&&(this.__mediaStream=await zt(n.media),this.__mediaStream.getTracks().forEach(o=>{A[t].addTrack(o,this.__mediaStream);})),W[t]=e,O[t]||(O[t]={});for(let o=0;o<n.channels.length;o++){let c=n.channels[o];if(typeof c=="string")switch(c){case "text-chat":c={ordered:true,maxRetransmits:10,protocol:"text-chat"};break;case "file-transfer":c={ordered:false,maxPacketLifeTime:3e3,protocol:"file-transfer"};break;case "video-chat":c={ordered:true,maxRetransmits:10,protocol:"video-chat"};break;case "voice-chat":c={ordered:true,maxRetransmits:10,protocol:"voice-chat"};break;case "gaming":c={ordered:false,maxPacketLifeTime:100,protocol:"gaming"};break;default:c={ordered:true,maxRetransmits:10,protocol:"default"};break}let u=c.protocol||"default";if(Object.keys(O[t]).includes(u))throw new a(`Data channel with the protocol "${u}" already exists.`,{code:"INVALID_REQUEST"});let d=A[t].createDataChannel(u,c);O[t][u]=d;}for(let o in O[t]){let c=O[t][o];Yt.bind(this)(t,c);}return Zt.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;A[t].onnegotiationneeded=()=>{this.log("onnegotiationneeded",`sending offer to "${t}".`),Ve.bind(this)(t),W[t]&&W[t]({type:"negotiationneeded",target:A[t],timestamp:new Date().toISOString(),signalingState:A[t].signalingState,connectionState:A[t].iceConnectionState,gatheringState:A[t].iceGatheringState});},o({target:A[t],channels:O[t],hangup:()=>Q.bind(this)({cid:t}),media:this.__mediaStream});}).bind(this);})}}function Xt(n){return async(e,t)=>{e=e||{},e=v(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 A?.[i]||(A[i]=new RTCPeerConnection({iceServers:[{urls:s}]})),e?.media&&(this.__mediaStream=await zt(e.media),this.__mediaStream.getTracks().forEach(o=>{A[i].addTrack(o,this.__mediaStream);})),delete H[i],W[i]=t,O[i]||(O[i]={}),A[i].ondatachannel=o=>{this.log("ondatachannel",`received data channel "${o.channel.label}".`);let c=o.channel;O[i][c.label]=c,Yt.bind(this)(i,c);},Zt.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:A[i],channels:O[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 A[n].createOffer();await A[n].setLocalDescription(t);let i=A[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 Ar(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",A[e].iceGatheringState),i({type:"icecandidate",target:A[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:A[e].iceGatheringState,connectionState:A[e].iceConnectionState}),t.send(JSON.stringify({action:"rtc",uid:e,content:{candidate:r},token:this.session.accessToken.jwtToken}));}function Zt(n,e){let t=new Set(e),i=W[n]||(o=>{}),r=A[n],s={ontrack:o=>{i({type:"track",target:r,timeStamp:o.timeStamp,streams:o.streams,track:o.track});},onicecandidate:o=>{Ar.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 Yt(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),O[n]&&(delete O[n][e.label],Object.keys(O[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,ie=0;async function Ir(){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 en(){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}),ie=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 re.bind(this)(),setTimeout(async()=>{let r=await Ir.bind(this)();r.onopen=()=>{ge=false,ie=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 Mn=Object.defineProperty;var Vn=Object.getOwnPropertyDescriptor;var te=(n=>t
212
212
  }
213
213
 
214
214
  runInterval(); // Start interval
215
- `,o=new Blob([s],{type:"application/javascript"});Z=new Worker(URL.createObjectURL(o)),Z.onmessage=c=>{r.readyState===1&&r.send(JSON.stringify({action:"keepAlive"}));},i(r);},r.onmessage=async s=>{let o="";try{o=JSON.parse(decodeURI(s.data)),this.log("socket onmessage",o);}catch{return}let c;switch(true){case !!o?.["#message"]:c="message";break;case !!o?.["#private"]:c="private";break;case !!o?.["#notice"]:c="notice";break;case !!o?.["#rtc"]:c="rtc";break;case !!o?.["#error"]:c="error";break}if(!c)return;let 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=en.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=()=>{fe?(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."}),oe++,oe<3?(this.log("realtime onclose","Reconnecting to WebSocket server..."+oe),n({type:"reconnect",message:"Reconnecting to WebSocket server..."+oe}),xe.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 sn(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 ie.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 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 ie.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 on(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 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 an(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 Tr=typeof FormData<"u",kr=typeof HTMLFormElement<"u",xr=typeof SubmitEvent<"u";async function cn(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 ln(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 un(n,e){if(await this.__connection,Tr&&n instanceof FormData||kr&&n instanceof HTMLFormElement||xr&&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 dn(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 gn(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 se.bind(this)(t.list[i]);return t}function he(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 fn(n,e){if(n=D(n,{ignoreEmpty:true}).data,n=g.Params(n,{subscriber:i=>g.UserId(i,'User ID in "subscriber"'),subscription:he.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 hn(n){await this.__connection,n=g.Params(n,{user_id:he.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 pn(n){await this.__connection;let{user_id:e}=g.Params(n,{user_id:he.bind(this)},["user_id"]);return await w.bind(this)("subscription",{unsubscribe:e},{auth:true})}async function mn(n){await this.__connection;let{user_id:e}=g.Params(n,{user_id:he.bind(this)},["user_id"]);return await w.bind(this)("subscription",{block:e},{auth:true})}async function bn(n){await this.__connection;let{user_id:e}=g.Params(n,{user_id:he.bind(this)},["user_id"]);return await w.bind(this)("subscription",{unblock:e},{auth:true})}async function _n(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 yn(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 wn(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 En(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 Rn(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 An(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 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,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 Sn(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 Pn(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 Tn(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 kn(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=>ce(r.user)),i}async function xn(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 vn(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 Dn(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 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)("delete-subscription",{endpoint:n.endpoint,keys:n.keys},{auth:true}),"SUCCESS: Unsubscribed from notifications."}async function Un(){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 Cn(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 Ln(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 On(n){return await this.__connection,n=g.Params(n||{},{search:["spell","name",()=>"spell"],value:"string"}),await w.bind(this)("getspell",n)}async function Fn(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(q())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 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],A?.[u.sender_cid]&&Q.bind(this)({cid:u.sender_cid}),u.type="rtc:closed",n(u);return}if(d.candidate&&qe.bind(this)(d.candidate,u.sender_cid),d.sdpoffer&&($e.bind(this)(d.sdpoffer,u.sender_cid),H[u.sender_cid]||(H[u.sender_cid]=u.sender_cid,delete u.message,u.connectRTC=Xt.bind(this)(u),u.type="rtc:incoming",u.hangup=(()=>{A[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&&A[u.sender_cid])if(A[u.sender_cid].signalingState==="have-local-offer")await A[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."}),ie++,ie<3?(this.log("realtime onclose","Reconnecting to WebSocket server..."+ie),n({type:"reconnect",message:"Reconnecting to WebSocket server..."+ie}),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 tn(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 re.bind(this)(),n=v(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 re.bind(this)(),n=v(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 nn(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 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 rn(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 Sr=typeof FormData<"u",Tr=typeof HTMLFormElement<"u",Pr=typeof SubmitEvent<"u";async function sn(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 on(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 an(n,e){if(await this.__connection,Sr&&n instanceof FormData||Tr&&n instanceof HTMLFormElement||Pr&&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=v(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 cn(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 ln(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 de.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 un(n,e){if(n=v(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 dn(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 gn(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 fn(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 hn(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 pn(n,e){await this.__connection;let t=await V.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 mn(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 bn(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 _n(n,e){let t=await V.bind(this)(),i={message_id:"string",timestamp:"number",read:"number",complaint:"number",subject:"string",bounced:"number"};n||(e=Object.assign({ascending:false},e||{})),n=v(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 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,block:e.user_id}:e={block:e.user_id},!await V.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 wn(n){let e=g.Params(n,{user_id:i=>g.UserId(i,'"user_id"')},["user_id"]);if(e?.service&&e?.owner?e={service:e?.service,owner:e?.owner,unblock:e.user_id}:e={unblock:e.user_id},!await V.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 En(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 V.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 Rn(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 V.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 An(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 V.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 In(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 V.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 Sn(n,e){if(n=g.Params(n,{email:"string"}),!await V.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=>oe(r.user)),i}async function Tn(n){if(n=g.Params(n,{email:t=>g.Email(t)},["email"]),!await V.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 Pn(n){if(n=g.Params(n,{email:t=>g.Email(t)},["email"]),!await V.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 kn(n){if(typeof window>"u"||window._runningInNodeJS)throw new a("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.__connection,!n.endpoint)throw new a("Missing parameter: endpoint",{code:"INVALID_PARAMETER"});if(!n.keys||!n.keys.p256dh||!n.keys.auth)throw new a("Missing parameter: keys.p256dh or keys.auth",{code:"INVALID_PARAMETER"});return await w.bind(this)("store-subscription",{endpoint:n.endpoint,keys:n.keys},{auth:true}),"SUCCESS: Subscribed to receive notifications."}async function xn(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 Dn(){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 vn(n,e){if(typeof window>"u"||window._runningInNodeJS)throw new a("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});await this.__connection;let{title:t,body:i}=v(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 Nn(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 Un(n){return await this.__connection,n=g.Params(n||{},{search:["spell","name",()=>"spell"],value:"string"}),await w.bind(this)("getspell",n)}async function Cn(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(q())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.4";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:ae,toBase62:et,fromBase62:B,decodeServiceId:Ne,formatServiceId:tt,extractFormData:D,terminatePendingRequests:xt,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=ot.bind(this);this.unregisterTicket=at.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=Ne(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=q();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}:${ae(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 S of A)p[S]=this[S];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){q()&&typeof window.alert=="function"&&window.alert(e);}async getConnectionInfo(){let e=await this.__connection,t=e?.user_agent||(q()&&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,q()){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.7";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:$,generateRandom:se,toBase62:Ye,fromBase62:B,decodeServiceId:ve,formatServiceId:et,extractFormData:v,terminatePendingRequests:kt,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=st.bind(this);this.unregisterTicket=ot.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=ve(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 m=new FileReader;m.onloadend=()=>h(m.result),m.onerror=R,m.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 m=new FileReader;m.onloadend=()=>h(m.result),m.onerror=R,m.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=q();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}:${se(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 M.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 m={},I=["__startKeyHistory","__disabledAccount","__cached_requests","__request_signup_confirmation","__public_identifier","connection"];if(this.connection){for(let S of I)m[S]=this[S];u&&window.sessionStorage.setItem(`${e}#${t}`,JSON.stringify(m)),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){q()&&typeof window.alert=="function"&&window.alert(e);}async getConnectionInfo(){let e=await this.__connection,t=e?.user_agent||(q()&&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,q()){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 gn.bind(this)(e,t)}closeRTC(e){return Q.bind(this)(e)}connectRTC(e,t){return Yt.bind(this)(e,t)}connectRealtime(e){return xe.bind(this)(e)}spellcast(e){return Ln.bind(this)(e)}getspell(e){return On.bind(this)(e)}dopamine(e){return Fn.bind(this)(e)}getUniqueId(e,t){return Kt.bind(this)(e,t)}resendInvitation(e){return vn.bind(this)(e)}cancelInvitation(e){return xn.bind(this)(e)}getInvitations(e,t){return kn.bind(this)(e,t)}openIdLogin(e){return lt.bind(this)(e)}loginWithToken(e){return ut.bind(this)(e)}clientSecretRequest(e){return cn.bind(this)(e)}consumeTicket(e){return rt.bind(this)(e)}getConsumedTickets(e,t){return st.bind(this)(e,t)}getTickets(e,t){return it.bind(this)(e,t)}closeRealtime(){return rn.bind(this)()}getRealtimeUsers(e,t){return on.bind(this)(e,t)}sendInquiry(e){return ln.bind(this)(e)}blockAccount(e){return Rn.bind(this)(e)}unblockAccount(e){return An.bind(this)(e)}deleteAccount(e){return In.bind(this)(e)}inviteUser(e,t){return Sn.bind(this)(e,t)}createAccount(e){return Pn.bind(this)(e)}grantAccess(e){return Tn.bind(this)(e)}getRealtimeGroups(e,t){return an.bind(this)(e,t)}postRealtime(e,t,i){return sn.bind(this)(e,t,i)}joinRealtime(e){return Ke.bind(this)(e)}getProfile(e){return ct.bind(this)(e)}getFile(e,t){return Se.bind(this)(e,t)}secureRequest(e,t){return un.bind(this)(e,t)}getFormResponse(){return Dt.bind(this)()}getRecords(e,t){return Ft.bind(this)(e,t)}getTables(e,t){return qt.bind(this)(e,t)}getIndexes(e,t){return jt.bind(this)(e,t)}getTags(e,t){return Bt.bind(this)(e,t)}deleteRecords(e,t){return Qt.bind(this)(e,t)}resendSignupConfirmation(){return dt.bind(this)()}recoverAccount(e=false){return gt.bind(this)(e)}getUsers(e,t){return Rt.bind(this)(e,t)}disableAccount(){return ht.bind(this)()}lastVerifiedEmail(e){return At.bind(this)(e)}unsubscribeNewsletter(e){return wn.bind(this)(e)}subscribeNotification(e,t){return Dn.bind(this)({endpoint:e,keys:t})}unsubscribeNotification(e,t){return Nn.bind(this)({endpoint:e,keys:t})}vapidPublicKey(){return Un.bind(this)()}pushNotification(e,t){return Cn.bind(this)(e,t)}getNewsletters(e,t){return En.bind(this)(e,t)}getNewsletterSubscription(e,t){return _n.bind(this)(e,t)}requestUsernameChange(e){return It.bind(this)(e)}grantPrivateRecordAccess(e){return Wt.bind(this)(e)}removePrivateRecordAccess(e){return Ht.bind(this)(e)}listPrivateRecordAccess(e){return Jt.bind(this)(e)}requestPrivateRecordAccessKey(e){return zt.bind(this)(e)}deleteFiles(e){return Lt.bind(this)(e)}uploadFiles(e,t){return Ee.bind(this)(e,t)}mock(e,t){return dn.bind(this)(e,t)}login(e){return Ce.bind(this)(e)}logout(e){return le.bind(this)(e)}signup(e,t){return ft.bind(this)(e,t)}resetPassword(e){return pt.bind(this)(e)}verifyEmail(e){return _t.bind(this)(e)}verifyPhoneNumber(e){return bt.bind(this)(e)}forgotPassword(e){return yt.bind(this)(e)}changePassword(e){return wt.bind(this)(e)}updateProfile(e){return Et.bind(this)(e)}postRecord(e,t,i){return Vt.bind(this)(e,t,i)}async bulkPostRecords(e){return $t.bind(this)(e)}getSubscriptions(e,t){return fn.bind(this)(e,t)}subscribe(e){return hn.bind(this)(e)}unsubscribe(e){return pn.bind(this)(e)}blockSubscriber(e){return mn.bind(this)(e)}unblockSubscriber(e){return bn.bind(this)(e)}subscribeNewsletter(e){return yn.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({preventMultipleCalls:true})],b.prototype,"bulkPostRecords"),_([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 Dr={};
233
- exports.Skapi=b;exports.SkapiError=a;exports.Types=Dr;//# 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 ln.bind(this)(e,t)}closeRTC(e){return Q.bind(this)(e)}connectRTC(e,t){return Gt.bind(this)(e,t)}connectRealtime(e){return ke.bind(this)(e)}spellcast(e){return Nn.bind(this)(e)}getspell(e){return Un.bind(this)(e)}dopamine(e){return Cn.bind(this)(e)}getUniqueId(e,t){return qt.bind(this)(e,t)}resendInvitation(e){return Pn.bind(this)(e)}cancelInvitation(e){return Tn.bind(this)(e)}getInvitations(e,t){return Sn.bind(this)(e,t)}openIdLogin(e){return ct.bind(this)(e)}loginWithToken(e){return lt.bind(this)(e)}clientSecretRequest(e){return sn.bind(this)(e)}consumeTicket(e){return nt.bind(this)(e)}getConsumedTickets(e,t){return it.bind(this)(e,t)}getTickets(e,t){return rt.bind(this)(e,t)}closeRealtime(){return en.bind(this)()}getRealtimeUsers(e,t){return nn.bind(this)(e,t)}sendInquiry(e){return on.bind(this)(e)}blockAccount(e){return yn.bind(this)(e)}unblockAccount(e){return wn.bind(this)(e)}deleteAccount(e){return En.bind(this)(e)}inviteUser(e,t){return Rn.bind(this)(e,t)}createAccount(e){return An.bind(this)(e)}grantAccess(e){return In.bind(this)(e)}getRealtimeGroups(e,t){return rn.bind(this)(e,t)}postRealtime(e,t,i){return tn.bind(this)(e,t,i)}joinRealtime(e){return Be.bind(this)(e)}getProfile(e){return at.bind(this)(e)}getFile(e,t){return Ie.bind(this)(e,t)}secureRequest(e,t){return an.bind(this)(e,t)}getFormResponse(){return Dt.bind(this)()}getRecords(e,t){return Ot.bind(this)(e,t)}getTables(e,t){return Mt.bind(this)(e,t)}getIndexes(e,t){return Vt.bind(this)(e,t)}getTags(e,t){return $t.bind(this)(e,t)}deleteRecords(e,t){return jt.bind(this)(e,t)}resendSignupConfirmation(){return ut.bind(this)()}recoverAccount(e=false){return dt.bind(this)(e)}getUsers(e,t){return Et.bind(this)(e,t)}disableAccount(){return ft.bind(this)()}lastVerifiedEmail(e){return Rt.bind(this)(e)}unsubscribeNewsletter(e){return bn.bind(this)(e)}subscribeNotification(e,t){return kn.bind(this)({endpoint:e,keys:t})}unsubscribeNotification(e,t){return xn.bind(this)({endpoint:e,keys:t})}vapidPublicKey(){return Dn.bind(this)()}pushNotification(e,t){return vn.bind(this)(e,t)}getNewsletters(e,t){return _n.bind(this)(e,t)}getNewsletterSubscription(e,t){return pn.bind(this)(e,t)}requestUsernameChange(e){return At.bind(this)(e)}grantPrivateRecordAccess(e){return Bt.bind(this)(e)}removePrivateRecordAccess(e){return Kt.bind(this)(e)}listPrivateRecordAccess(e){return Qt.bind(this)(e)}requestPrivateRecordAccessKey(e){return Wt.bind(this)(e)}deleteFiles(e){return Ct.bind(this)(e)}uploadFiles(e,t){return we.bind(this)(e,t)}mock(e,t){return cn.bind(this)(e,t)}login(e){return Ue.bind(this)(e)}logout(e){return ae.bind(this)(e)}signup(e,t){return gt.bind(this)(e,t)}resetPassword(e){return ht.bind(this)(e)}verifyEmail(e){return bt.bind(this)(e)}verifyPhoneNumber(e){return mt.bind(this)(e)}forgotPassword(e){return _t.bind(this)(e)}changePassword(e){return yt.bind(this)(e)}updateProfile(e){return wt.bind(this)(e)}postRecord(e,t,i){return Ft.bind(this)(e,t,i)}getSubscriptions(e,t){return un.bind(this)(e,t)}subscribe(e){return dn.bind(this)(e)}unsubscribe(e){return gn.bind(this)(e)}blockSubscriber(e){return fn.bind(this)(e)}unblockSubscriber(e){return hn.bind(this)(e)}subscribeNewsletter(e){return mn.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 xr={};
233
+ exports.Skapi=b;exports.SkapiError=a;exports.Types=xr;//# sourceMappingURL=skapi.cjs.map
234
234
  //# sourceMappingURL=skapi.cjs.map