skapi-js 1.5.0-beta.7 → 1.5.0-beta.8
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 +5 -5
- package/dist/skapi.cjs.map +1 -1
- package/dist/skapi.js +6 -6
- package/dist/skapi.js.map +1 -1
- package/dist/skapi.mjs +5 -5
- package/dist/skapi.mjs.map +1 -1
- package/package.json +1 -1
package/dist/skapi.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
'use strict';var amazonCognitoIdentityJs=require('amazon-cognito-identity-js'),
|
|
1
|
+
'use strict';var amazonCognitoIdentityJs=require('amazon-cognito-identity-js'),Jn=require('cocochex'),lr=require('qpass');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var Jn__default=/*#__PURE__*/_interopDefault(Jn);var lr__default=/*#__PURE__*/_interopDefault(lr);/**
|
|
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 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=`
|
|
206
|
+
var Cn=Object.defineProperty;var Ln=Object.getOwnPropertyDescriptor;var Y=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var _=(n,e,t,i)=>{for(var r=Ln(e,t),s=n.length-1,o;s>=0;s--)(o=n[s])&&(r=(o(e,t,r))||r);return r&&Cn(e,t,r),r};var J=typeof globalThis<"u"?globalThis:void 0,he=J?.window;function On(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=On(r),o=i.type||"application/octet-stream";this.result=`data:${o};base64,${s}`,this.onload&&this.onload({target:this}),this.onloadend&&this.onloadend({target:this});}).catch(r=>{this.error=r,this.onerror&&this.onerror({target:this});});}readAsArrayBuffer(i){i.arrayBuffer().then(r=>{this.result=r,this.onload&&this.onload({target:this}),this.onloadend&&this.onloadend({target:this});}).catch(r=>{this.error=r,this.onerror&&this.onerror({target:this});});}readAsText(i,r="utf-8"){i.text().then(s=>{this.result=s,this.onload&&this.onload({target:this}),this.onloadend&&this.onloadend({target:this});}).catch(s=>{this.error=s,this.onerror&&this.onerror({target:this});});}}J.FileReader=n;class e{constructor(){this.status=0;this.statusText="";this.readyState=0;this.responseText="";this.response=null;this.responseType="";this.responseURL="";this.timeout=0;this.withCredentials=false;this.onload=null;this.onerror=null;this.onabort=null;this.ontimeout=null;this.onprogress=null;this.onreadystatechange=null;this.upload={onprogress:null};this._method="GET";this._url="";this._headers={};this._aborted=false;}open(i,r){this._method=i,this._url=r,this.readyState=1;}setRequestHeader(i,r){this._headers[i]=r;}getResponseHeader(i){return null}abort(){this._aborted=true,this.onabort&&this.onabort({});}send(i){if(this._aborted)return;let r={method:this._method,headers:this._headers};i&&this._method!=="GET"&&this._method!=="HEAD"&&(r.body=i),fetch(this._url,r).then(async s=>{if(!this._aborted){if(this.status=s.status,this.statusText=s.statusText,this.responseURL=s.url,this.readyState=4,this.responseType==="blob")this.response=await s.blob();else if(this.responseType==="json")try{this.response=await s.json();}catch{this.response=null;}else this.responseType==="arraybuffer"?this.response=await s.arrayBuffer():(this.responseText=await s.text(),this.response=this.responseText);this.onload&&this.onload({});}}).catch(s=>{this._aborted||this.onerror&&this.onerror(s);});}}J.XMLHttpRequest=e,J.window={_runningInNodeJS:true,alert:t=>console.error("[Alert]",t),sessionStorage:{getItem:t=>null,setItem:(t,i)=>{},removeItem:t=>{}},localStorage:{getItem:t=>{let i=Y("fs"),r=Y("path");try{let s=r.resolve(process.cwd(),"states","localStorage",`${t}.skapi`);return i.existsSync(s)?i.readFileSync(s,"utf8"):null}catch{return null}},setItem:(t,i)=>{let r=Y("fs"),s=Y("path");try{let o=s.resolve(process.cwd(),"states","localStorage");r.existsSync(o)||r.mkdirSync(o,{recursive:!0});let c=s.resolve(o,`${t}.skapi`);r.writeFileSync(c,i,"utf8");}catch{}},removeItem:t=>{let i=Y("fs"),r=Y("path");try{let s=r.resolve(process.cwd(),"states","localStorage",`${t}.skapi`);i.existsSync(s)&&i.unlinkSync(s);}catch{}}},location:{href:"",origin:"",hostname:"",protocol:"",replace:t=>{}},navigator:{userAgent:`nodejs/${J?.process?.versions?.node||"unknown"}`,mediaDevices:{getUserMedia:async t=>{throw new Error("getUserMedia is not supported in Node.js environment.")}}},addEventListener:()=>{},removeEventListener:()=>{}};}var a=class extends Error{constructor(e,t){if(Array.isArray(e)&&e.length<=2){let i=e[1];if(e.length>2)for(let r=2;r<e.length&&typeof e[r]=="string";r++)i+=e[r];super((i||"Something went wrong.").trim()),this.name=t?.name||"SKAPI",this.code=t?.code||e[0]||"ERROR",t?.cause&&(this.cause=t.cause);}else super((e?.message||(typeof e=="string"?e:"Something went wrong.")).trim()),typeof e=="string"?(this.name=t?.name||"SKAPI",this.code=t?.code||"ERROR",t?.cause&&(this.cause=t.cause)):e instanceof Error?(this.cause=e,this.name=e.name,e.hasOwnProperty("code")&&(this.code=e.code)):typeof e=="object"&&e?.code&&e?.message&&(this.name=t?.name||"SKAPI",this.code=t?.code||"ERROR",this.cause=e?.cause);}};var ee="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",xe=BigInt(ee.length),Fn=2*1024*1024,Mn=["aud","cognito:username","event_id","exp","iat","iss","jti","origin_jti","secret_key","token_use"],Ke={auth_time:"log",sub:"user_id"},Vn=["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 V=p;function Ye(n){if(n===0)return ee[0];let e="";for(;n>0;)e=ee[n%62]+e,n=Math.floor(n/62);return e}function B(n){return n.split("").reverse().reduce((e,t,i)=>e+ee.indexOf(t)*62**i,0)}function 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 $(){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>Fn)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=$(),$n=typeof SubmitEvent<"u",qn=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 h=R.replace("]",""),I=Number(h);return !isNaN(I)&&!h.includes(".")?h=I:(h[0]==='"'&&h[h.length-1]==='"'||h[0]==="'"&&h[h.length-1]==="'")&&(h=h.replace(/"/g,"").replace(/'/g,"")),h}),m=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 h=l[R];R<l.length-1?(m[h]===void 0&&(typeof l[R+1]=="number"?m[h]=[]:m[h]={}),m=m[h]):m[h]===void 0?m[h]=f:Array.isArray(m[h])?m[h].push(f):m[h]=[m[h],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 m=f.item(l);m&&u.push({name:d,file:m});}}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 m=JSON.parse(l.text());s(i,d,m);}catch{s(i,d,l);}}else s(i,d,f);}return pe(i),{data:i,files:r}}if(me&&$n&&n instanceof SubmitEvent&&(n=n.target),me&&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++)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(!Mn.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=Hn(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=Vn[t],s=`${n.slice(4,-4)}-${i}${n.slice(-4)}-${e}`;return Wn(s)}function Je(n){let e=0n;for(let t of n){let i=ee.indexOf(t);if(i<0)throw new Error(`INVALID_PARAMETER: Invalid base62 character: ${t}`);e=e*xe+BigInt(i);}return e}function ze(n,e=1){if(n<0n)throw new Error("INVALID_PARAMETER: Negative values are not supported.");if(n===0n)return "0".repeat(Math.max(1,e));let t="",i=n;for(;i>0n;){let r=Number(i%xe);t=ee[r]+t,i/=xe;}return t.length<e&&(t="0".repeat(e-t.length)+t),t}function 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 jn(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 Bn(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 Kn(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 Qn(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 Wn(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=jn(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_${Kn(f).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}`}function Hn(n){let e=String(n);if(!e.startsWith("s1_"))return e;let t=Qn(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),m=ze(Xe(t.subarray(d,f)),s),R=Bn(t.subarray(f,f+16));return `${l}-${m}-${R}`}function zn(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 Gn(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 Xn(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 Zn(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 Yn(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 er(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 tr(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 Jn__default.default(o,e,t)}catch(c){throw new a(c.message,{code:"INVALID_PARAMETER"})}}var g={UserId:zn,PhoneNumber:Gn,Birthdate:Xn,Password:Zn,Email:Yn,Url:er,Params:tr};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 E.bind(this)(`https://${this.service.slice(0,4)}.${this.customApiDomain}/auth/consume/${this.service}/${this.owner}/${e}`,n?.data||{},{method:n.method,auth:!!n?.auth});return Ne(t)}async function rt(n,e){await this.__connection;let t=await E.bind(this)("ticket",Object.assign({exec:"list"},n||{}),{auth:true,fetchOptions:e});return t.list=t.list.map(Ne),t}async function it(n,e){await this.__connection;let t=await E.bind(this)("ticket",Object.assign({exec:"consumed"},n||{}),{auth:true,fetchOptions:e});return t.list=t.list.map(Ne),t}async function st(n){return E.bind(this)("register-ticket",Object.assign({exec:"reg"},n),{auth:true})}async function ot(n){return E.bind(this)("register-ticket",Object.assign({exec:"unreg"},n),{auth:true})}async function ne(){if(await this.__connection,this.session){let n=Math.floor(Date.now()/1e3),t=this.session.getIdToken().getExpiration();if(t<n){this.log("request:requesting new token",null);try{await F.bind(this)().getSession({refreshToken:!0}),this.log("request:received new tokens",{exp:this.session?.idToken?.payload?.exp,currentTime:n,expiresIn:t-n,token:this.session?.accessToken?.jwtToken,refreshToken:this.session?.refreshToken?.token});}catch(i){throw this.log("request:new token error",i),new a("User login is required.",{code:"INVALID_REQUEST"})}}else this.log("request:tokens",{exp:this.session.idToken.payload.exp,currentTime:n,expiresIn:t-n,token:this.session.accessToken.jwtToken,refreshToken:this.session.refreshToken.token});return this.session?.idToken?.jwtToken}else throw this.log("request:no session",null),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 F(){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 m=l.getIdToken().payload;if(this.log("getSession:respond:sessionAttribute",m),m["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,m)=>{if(this.log("getSession:getSessionCallback",{err:l,session:m}),!m){z.bind(this)(),c(new a("Current session does not exist.",{code:"INVALID_REQUEST"}));return}if(l){tt.bind(this)(m,N).then(w=>o(f(w))).catch(c);return}let R=Math.floor(Date.now()/1e3),h=m.getIdToken(),I=h.getExpiration(),k=I<R;if(this.log("getSession:currentTime",R),this.log("getSession:idTokenExp",I),this.log("getSession:isExpired",k),this.log("getSession:existingBearerToken",this.bearerToken),this.bearerToken=h.getJwtToken(),k||u||!m.isValid())tt.bind(this)(m,N).then(w=>o(f(w))).catch(c);else try{o(f(m));}catch(w){c(w);}});}),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),m=l.cognitoUsername,R=new amazonCognitoIdentityJs.AuthenticationDetails({Username:m,Password:o});l.cognitoUser.authenticateUser(R,{newPasswordRequired:(h,I)=>{this.__disabledAccount=null,this.__request_signup_confirmation=m,h["custom:signup_ticket"]==="PASS"||h["custom:signup_ticket"]==="MEMBER"||h["custom:signup_ticket"]==="OIDPASS"?l.cognitoUser.completeNewPasswordChallenge(o,{},{onSuccess:k=>{N=l.cognitoUser,e().then(w=>d(this.user));},onFailure:k=>{f(new a(k.message||"Failed to authenticate user.",{code:k.code}));}}):f(new a("User's signup confirmation is required.",{code:"SIGNUP_CONFIRMATION_NEEDED"}));},onSuccess:h=>e({skipUserUpdateEventTrigger:true}).then(I=>{this.__disabledAccount=null,this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user),d(this.user);}),onFailure:h=>{let I=[],{parsed:k,code:w}=_e(h),P=typeof h?.message=="string"?h.message:"";if(w==="NotAuthorizedException"?P.includes("User is disabled.")?(this.__disabledAccount=m,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"]:w==="UserNotFoundException"?I=["Incorrect username or password.","INCORRECT_USERNAME_OR_PASSWORD"]:w==="UserNotConfirmedException"?(this.__request_signup_confirmation=m,I=["User's signup confirmation is required.","SIGNUP_CONFIRMATION_NEEDED"]):(w==="TooManyRequestsException"||w==="LimitExceededException")&&(I=["Too many attempts. Please try again later.","REQUEST_EXCEED"]),k.code==="SIGNUP_CONFIRMATION_NEEDED"&&(this.__request_signup_confirmation=m),I.length){let T=I[1],S=I[0];f(new a(S,{code:T,cause:h}));}else f(k);}});}),createCognitoUser:t,signup:(s,o,c)=>new Promise((u,d)=>{this.userPool.signUp(s,o,c,null,(f,l)=>{if(f){let{parsed:m,code:R}=_e(f),h=[];R==="UsernameExistsException"?h=["The account already exists.","EXISTS"]:R==="InvalidPasswordException"?h=["Invalid password. Password must be at least 6 characters.","INVALID_PARAMETER"]:R==="InvalidParameterException"?h=[m.message||"Invalid parameter.","INVALID_PARAMETER"]:R==="TooManyRequestsException"||R==="LimitExceededException"?h=["Too many attempts. Please try again later.","REQUEST_EXCEED"]:R==="CodeDeliveryFailureException"?h=["Failed to deliver verification code.","CODE_DELIVERY_FAILURE"]:R==="UserLambdaValidationException"&&(h=[m.message||"Signup validation failed.","INVALID_REQUEST"]),h.length?d(new a(h[0],{code:h[1],cause:f})):d(m);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 F.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 E.bind(this)("openid-logger",n),t=e.logger.split("#"),i=this.service+"-"+t[0],r=t[1];return {userProfile:await F.bind(this)().authenticateUser(i,r,true,true),openid:e.openid}}function ar(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 cr(n){let e=n.split(".");if(e.length!==3)throw new Error("Invalid JWT format");let i=e[1].replace(/-/g,"+").replace(/_/g,"/"),r=ar(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=cr(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 M(){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 E.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 E.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 F.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=F.bind(this)().createCognitoUser(i.username||i.email);for(let d of ["email_public","address_public","gender_public","birthdate_public","phone_number_public"])i[d]=i[d]?"1":"0";i.access_group&&(i.access_group=i.access_group.toString());let o=(await E.bind(this)("signupkey",{username:s.cognitoUsername,signup_confirmation:typeof i.signup_confirmation=="boolean"?JSON.stringify(i.signup_confirmation):i.signup_confirmation,email_subscription:i.email_subscription})).split(":"),c=o.slice(1).join(":"),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?(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 E.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)=>{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 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?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?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)=>{F.bind(this)().createCognitoUser(e.email).cognitoUser.forgotPassword({onSuccess:s=>{t("SUCCESS: Verification code has been sent.");},onFailure:s=>{let{parsed:o,code:c}=_e(s),u={UserNotFoundException:"NOT_EXISTS",InvalidParameterException:"INVALID_PARAMETER",NotAuthorizedException:"INVALID_REQUEST",LimitExceededException:"REQUEST_EXCEED",TooManyRequestsException:"REQUEST_EXCEED",CodeDeliveryFailureException:"CODE_DELIVERY_FAILURE"}[c]||o.code||c||"ERROR";i(new a(o.message,{code:u,cause:s}));}});})}async function 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+"-"+V.hash(e.email));let t=[["email_public","email_verified","User's e-mail should be verified to set"],["phone_number_public","phone_number_verified","User's phone number should be verified to set"]];if(this.__user){for(let r of t)if(e[r[0]]&&!this.__user[r[1]])throw new a(`${r[2]} "${r[0]}" to true.`,{code:"INVALID_REQUEST"})}let i=[];for(let r in e){if(e[r]===this.user[r]){i.push(r);continue}if(["email_public","phone_number_public","address_public","gender_public","birthdate_public","misc"].includes(r)){let o=e[r];typeof o=="boolean"&&(o=o?"1":"0"),e["custom:"+r]=o,i.push(r);}}for(let r of i)delete e[r];if(e.user_id)if(e.user_id===this.user.user_id)delete e.user_id;else return E.bind(this)("admin-edit-profile",{attributes:e},{auth:true});if(e&&typeof e=="object"&&Object.keys(e).length){let r=[];for(let s in e)r.push(new 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 F.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 E.bind(this)("get-users",n,{auth:true,fetchOptions:e})}async function Rt(n){await this.__connection;let e=await E.bind(this)("last-verified-email",n,{auth:true});return e.includes("SUCCESS")?(await F.bind(this)().getSession({refreshToken:true}),this.user):e}async function At(n){return await this.__connection,n=g.Params(n,{username:g.Email,redirect:g.Url},["username"]),await E.bind(this)("request-username-change",n,{auth:true})}var re=null,St=typeof SubmitEvent<"u",ur=typeof HTMLFormElement<"u",le=$(),Ce=0;function Tt(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 Pt(){re&&(re.terminate(),re=null);}async function E(n,e=null,t,i){this.log("request",{url:n,data:e,options:t,_etc:i||{}}),t=t||{};let{auth:r=false,method:s="post",bypassAwaitConnection:o=false}=t;s=s.toUpperCase();let c=null,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 ne.bind(this)());let m={},{fetchMore:R=false,progress:h}=t?.fetchOptions||{};if(t?.fetchOptions&&Object.keys(t.fetchOptions).length){for(let x of ["limit","startKey","ascending"])t.fetchOptions.hasOwnProperty(x)&&(m[x]=t.fetchOptions[x]);m=g.Params(m,{limit:x=>{if(typeof x!="number")throw new a("Fetch limit should be a number.",{code:"INVALID_REQUEST"});if(x>1e3)throw new a("Fetch limit should be below 1000.",{code:"INVALID_REQUEST"});return x},startKey:x=>x,ascending:"boolean"});}let I=i?.ignoreService?{}:{service:u,owner:d};Object.assign(I,m),e=v(e).data,e?e&&typeof e=="object"&&(e=Object.assign(I,e)):e=I;let k=`${s}:${r?"auth":"public"}:${n}`,w=(()=>{if(e&&typeof e=="object"&&Object.keys(e).length&&!(le&&e instanceof FormData)){let x=function(D){return typeof D=="object"&&D!==null?Object.keys(D).sort().reduce((U,O)=>(typeof D[O]=="object"&&D[O]!==null?U[O]=x(D[O]):U[O]=D[O],U),{}):D};return V.hash(k+"/"+JSON.stringify(x(e)))}return V.hash(k+"/"+u)})(),{requestKey:P,requestKeyWithStartKey:T}=gr.bind(this)({params:e,url:n,fetchMore:R,hashedParams:w});if(!P||P&&typeof P=="object")return P;if(this.log("requestKey",T),typeof T=="string"&&ce[T]instanceof Promise)return this.log("request:returning pending",T),ce[T];let S={Accept:"*/*"};if(Object.prototype.hasOwnProperty.call(t,"contentType")&&t.contentType!==void 0){let x=t.contentType===null?"application/x-www-form-urlencoded":t.contentType;x&&(S["Content-Type"]=x);}else S["Content-Type"]="application/json";f&&(S.Authorization=f);let q={public_identifier:this.__public_identifier,service:u,owner:d};S["Content-Meta"]=JSON.stringify(q);let j={headers:S};if(t?.responseType&&(j.responseType=t.responseType),s==="GET"){if(e){let x=[];if(le&&e instanceof FormData?x=Array.from(e.entries()).map(([D,U])=>{let O=typeof U=="string"?U:U.name;return encodeURIComponent(D)+"="+encodeURIComponent(O)}):x=Object.keys(e).map(D=>{let U=e[D];return typeof U!="string"&&(U=JSON.stringify(U)),encodeURIComponent(D)+"="+encodeURIComponent(U)}),x.length){let D=l.includes("?")?l.endsWith("?")||l.endsWith("&")?"":"&":"?";l+=D+x.join("&");}}j.body=null;}else if(le&&e instanceof FormData)j.body=e;else if(S["Content-Type"]==="application/x-www-form-urlencoded"&&e&&typeof e=="object"){let x=new URLSearchParams;for(let D of Object.keys(e)){let U=e[D];x.append(D,typeof U=="string"?U:JSON.stringify(U));}j.body=x.toString();}else typeof e=="string"?j.body=e:j.body=e?JSON.stringify(e):null;if(j.method=s,re===null){let x={batchSize:this.requestBatchSize,breakWhenError:false,onProgress:D=>{this.onBatchProcess.forEach(U=>U(D));}};re=new lr__default.default(x);}return this.log("request-opt",j),new Promise((x,D)=>{re.add([async()=>{let U=kt.bind(this)(l,j,h);ce[T]=U;try{let O=fr.bind(this)({hashedParam:P,requestKeyWithStartKey:T,url:n,fetched:await U});return delete ce[T],this.log("request:end",O),x(O),O}catch(O){throw delete ce[T],this.log("request:err",O),D(O),O}}]);})}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+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 kt(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=Tt(c);u!==null?setTimeout(()=>{kt(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(),m=f.join(":").trim();r(new a(m||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,m=d?.cause;typeof l=="string"&&(l=l.trim()),r(new a(l,{cause:m,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(St&&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=(R,h,I)=>new Promise((k,w)=>{c=new XMLHttpRequest,c.open("POST",R),c.onload=()=>{let P=c.responseText;try{P=JSON.parse(P);}catch{}if(c.status>=200&&c.status<300)k(P);else if(c.status===429){let T=c.getResponseHeader("Retry-After"),S=Tt(T);S!==null?setTimeout(()=>{u(R,h,I).then(k,w);},S):w("Too many requests");}else w(P);},c.onerror=()=>w("Network error"),c.onabort=()=>w("Aborted"),c.ontimeout=()=>w("Timeout"),c.upload&&typeof I=="function"&&(c.upload.onprogress=I),c.send(h);});function d(R){let h="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";if(R===0)return h[0];let I="";for(;R>0;)I=h[R%62]+I,R=Math.floor(R/62);return I}let f=[],l=[],m=[];for(let[R,h]of n.entries()){if(!(h instanceof File))continue;let I=Object.assign({key:R+"/"+h.name,sizeKey:d(h.size),contentType:h.type||null},o),{fields:k=null,url:w,cdn:P}=await E.bind(this)("get-signed-url",I,{auth:!!this.__user});m.push(P);let T=new FormData;for(let S in k)T.append(S,k[S]);T.append("file",h);try{await u(w,T,typeof r=="function"?S=>r({status:"upload",progress:Le(S.loaded,S.total),currentFile:h,completed:f,failed:l,loaded:S.loaded,total:S.total,abort:()=>c.abort()}):null),f.push(h);}catch{l.push(h);}}return {completed:f,failed:l,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={},m=false;if(St&&c instanceof SubmitEvent){c.preventDefault();let w=window.location.href;d=c.target;let P=new URL(d.action);f=P.href;let T=f?f.match(/(?<=\{).*?(?=\})/g):"";if(T)for(let S of T){if(!S)continue;let L=d.querySelector(`[name="${S}"]`);if(L)if(L.type==="file")for(let q=0;q<=L.files.length-1;q++)L.files[q]&&(l[S]||(l[S]=[]),l[S].push(new Promise((j,x)=>{let D=new FileReader;D.onload=function(){j(D.result);},D.readAsDataURL(L.files[q]),D.onerror=x;})));else f=f.replace(`{${S}}`,L.value);}d.getAttribute("action")===null?u=false:m=P.href===w;}let R=async w=>{if(f)for(let P in l)l[P].length&&(f=f.replace(`{${P}}`,(await Promise.all(l[P])).join(",")));return d&&u&&(window.sessionStorage.setItem(`${this.service}:${V.hash(f)}`,JSON.stringify(w)),m?window.location.replace(f):window.location.href=f),w},h,I=w=>{throw w instanceof a?w.name=i+"()":w=w instanceof Error?w:new a(w,{name:i+"()"}),w},k=async()=>{try{if(h=s.bind(this)(...o),h instanceof Promise){let w=await h;return R(w)}return R(h)}catch(w){throw I(w)}};if(e){let w=`${i}:${this?.__public_identifier||""}:${this?.service||""}:${this?.owner||""}`;return ye?.[w]||(ye[w]=k().finally(()=>{delete ye[w];})),ye[w]}return k()};}}async function xt(){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 hr=128,pr=64,mr=128,br=256,_r="\u{10FFFF}",yr=/[\u0000-\u001F\u007F]|\u{10FFFF}/u,wr=/[\/!*#]/;function G(n,e,t={}){let{allowEmpty:i=false,maxLength:r,blockKeyDelimiters:s=false,disallowLeadingDollar:o=false,onlyAlphanumeric:c=false}=t;if(typeof n!="string")throw new a(`"${e}" should be type: <string>.`,{code:"INVALID_PARAMETER"});if(c&&/[^a-zA-Z0-9]/.test(n))throw new a(`"${e}" should only contain alphanumeric characters.`,{code:"INVALID_PARAMETER"});if(!i&&n.length===0)throw new a(`"${e}" is required.`,{code:"INVALID_PARAMETER"});if(r&&n.length>r)throw new a(`"${e}" should be <= ${r} characters.`,{code:"INVALID_PARAMETER"});if(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 G(n,e,{allowEmpty:false,maxLength:hr,blockKeyDelimiters:true})}function Fe(n,e="tag"){return G(n,e,{allowEmpty:false,maxLength:pr,blockKeyDelimiters:true})}function ue(n,e="index.name"){return G(n,e,{allowEmpty:false,maxLength:mr,blockKeyDelimiters:true,disallowLeadingDollar:true})}function Dt(n,e="index.value"){return G(n,e,{allowEmpty:true,maxLength:br})}function vt(n){if(!n.record_id&&!n.unique_id)return null;let e={};return n?.service&&(e.service=n.service),n?.owner&&(e.owner=n.owner),n?.record_id?e.record_id=G(n.record_id,"record_id",{allowEmpty:false,onlyAlphanumeric:true}):n?.unique_id&&(e.unique_id=n.unique_id),e}function 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 Dt(n,"index.value");throw new a('"index.value" should be type: <number | boolean | string>.',{code:"INVALID_PARAMETER"})}function Nt(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"?Dt(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("/"),m=l.split("/");if(m.length<12)return null;let R=decodeURIComponent(m[m.length-1]),h=decodeURIComponent(m[10]),I=m[9],k=m[8],w=r(m[6]),P=f;if(w!=="public")try{P=await Ie.bind(this)(f,{dataType:"endpoint",_ref:u});}catch(S){console.error("Error getting signed url for private file:",S),P=f;}let T={access_group:w,filename:R,url:P,path:l,size:B(I),uploaded:B(k),getFile:(S,L)=>{let q={dataType:S||"download",progress:L,_ref:u,_update:T};return Ie.bind(this)(P,q)}};return {pathKey:h,obj:T}}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 Ut(n){let{endpoints:e}=n;if(typeof e=="string"&&(e=[e]),!Array.isArray(e))throw new a('"endpoints" should be type: array | string.',{code:"INVALID_PARAMETER"});let t=await E.bind(this)("del-files",{endpoints:e,storage:"records"},{auth:true,method:"post"}),i=[];for(let r in t)i.push(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),m=false;if(!o&&(l[0]==="auth"||l[0]==="publ"))try{g.UserId(l[2]),g.UserId(l[3]),m=l[0]=="auth",o=!0;}catch{throw new a("Invalid file url.",{code:"INVALID_PARAMETER"})}let R=f?null:l[1];if(e=g.Params(e,{expires:["number",()=>0],dataType:["base64","blob","endpoint","text","info",()=>"download"],progress:"function",_ref:[null,"string"],_update:w=>w}),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 h=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 w={request:f?"get-host":"get",id:f||l[5],key:n,expires:I};R&&(w.service=R),n=(await E.bind(this)("get-signed-url",w,{auth:true})).url;}else if(m){let w=Math.floor(Date.now()/1e3);if(!this.bearerToken&&(!this.session?.idToken?.payload?.exp||this.session.idToken.payload.exp<w)){this.log("getFile:requesting new token",null);try{await F.bind(this)().getSession({refreshToken:!0}),this.log("getFile:received new tokens",{exp:this.session?.idToken?.payload?.exp,currTime:w,expiresIn:this.session?.idToken?.payload?.exp-w,token:this.session?.accessToken?.jwtToken,refreshToken:this.session?.refreshToken?.token});}catch(L){throw this.log("getFile:new token error",L),new a("User login is required.",{code:"INVALID_REQUEST"})}}let P=this.bearerToken||this.session?.idToken?.jwtToken;if(!P||!this.user?.user_id)throw new a("User login is required.",{code:"INVALID_REQUEST"});n+=`${n.includes("?")?"&":"?"}t=${encodeURIComponent(P)}`;let T=l[6]==="**"?"**":parseInt(l[6]),S=this.user?.access_group??-1;if(this.user.user_id!==l[3]&&(T==="**"||S<T)){let L=l[5];if(this.__private_access_key[L]&&typeof this.__private_access_key[L]=="string")n+=`&p=${encodeURIComponent(this.__private_access_key[L])}`;else if(this.owner!==this.host)try{let q=await this.requestPrivateRecordAccessKey({record_id:L,reference_id:e?._ref});n+=`&p=${encodeURIComponent(q)}`;}catch{}}}if(e?.dataType==="endpoint")return e._update&&(e._update.url=n),n;if(e?.dataType==="download"){let w=document.createElement("a");return w.href=n,document.body.appendChild(w),w.setAttribute("download",h),w.target="_blank",w.click(),document.body.removeChild(w),null}return new Promise(async(w,P)=>{try{let T=await E.bind(this)(n,null,{method:"get",contentType:null,responseType:e?.dataType==="text"?"text":"blob",fetchOptions:{progress:e?.progress}},{ignoreService:!0});if(e?.dataType==="base64"){let S=new FileReader;S.onloadend=()=>w(S.result),S.readAsDataURL(T);}else w(T);}catch(T){P(T);}})}async function Ct(n,e=false){n=v(n,{ignoreEmpty:true}).data||{};let t="",i=vt(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=>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=>Nt(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 Lt(n,e){await this.__connection;let t=await Ct.bind(this)(n),i=t.is_reference_fetch,r=await E.bind(this)("get-records",t.query,{fetchOptions:e,auth:!!this.__user,method:this.__user?"post":"get"});i&&r?.reference_private_key&&typeof r.reference_private_key=="string"&&(this.__private_access_key[i]=r.reference_private_key);let s=[];for(let o in r.list)s.push(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=>G(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),G(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 Ot(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 m=await E.bind(this)("post-record",f,c);if($()&&u.length){let h=new FormData;for(let w of u)h.append(w.name,w.file,w.file.name);let I={record_id:m.rec,progress:s};r.hasOwnProperty("service")&&(I.service=r.service);let{bin_endpoints:k}=await we.bind(this)(h,I);m.bin?m.bin.push(...k):m.bin=k;}o&&typeof m?.reference_private_key=="string"&&(this.__private_access_key[o]=m.reference_private_key);let R=await de.bind(this)(m,"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 Ft(n,e){let t=await E.bind(this)("get-table",g.Params(n||{},{table:"string",condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}),Object.assign({auth:!!this.__user},{fetchOptions:e})),i={cnt_rec:"number_of_records",tbl:"table",srvc:"service"};if(Array.isArray(t?.list))for(let r of t.list)for(let s in i)r.hasOwnProperty(s)&&(r[i[s]]=r[s],delete r[s]);return t}async function Mt(n,e){if(!n?.table)throw new a('"table" is required.',{code:"INVALID_PARAMETER"});let t=g.Params(n||{},{table:"string",index:s=>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 E.bind(this)("get-index",t,Object.assign({auth:!!this.__user},{fetchOptions:e})),r={cnt_bool:"boolean_count",cnt_numb:"number_count",totl_numb:"total_number",totl_bool:"total_bool",avrg_numb:"average_number",avrg_bool:"average_bool",cnt_str:"string_count"};return Array.isArray(i?.list)&&(i.list=i.list.map(s=>{let o=s.idx.split("/"),c={table:o[1],index:o[2],number_of_records:s.cnt_rec};for(let u in r)Object.prototype.hasOwnProperty.call(s,u)&&(c[r[u]]=s[u]);return c})),i}async function Vt(n,e){let t=await E.bind(this)("get-tag",g.Params(n||{},{table:"string",tag:"string",condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}),Object.assign({auth:!!this.__user},{fetchOptions:e}));return Array.isArray(t?.list)&&(t.list=t.list.map(i=>{let r=i.tag.split("/");return {table:r[1],tag:r[0],number_of_records:i.cnt_rec}})),t}async function $t(n,e){let t=await E.bind(this)("get-uniqueid",g.Params(n||{},{unique_id:"string",condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}),Object.assign({auth:!!this.__user},{fetchOptions:e}));if(Array.isArray(t?.list))for(let i in t.list){let r=t.list[i];t.list[i]={unique_id:r.unq,record_id:r.rec};}return t}async function qt(n,e){await this.__connection;let t=await Ct.bind(this)(n,true),i=t.is_reference_fetch,r=await E.bind(this)("del-records",t.query,{auth:true,fetchOptions:e});return i&&typeof r?.reference_private_key=="string"&&(this.__private_access_key[i]=r.reference_private_key),r?.message||r}function jt(n){return Wt.bind(this)({record_id:n.record_id,user_id:n.user_id,execute:"add"})}function Bt(n){return Wt.bind(this)({record_id:n.record_id,user_id:n.user_id||null,execute:"remove"})}async function Kt(n,e){let t={record_id:n.record_id||void 0,user_id:n.user_id||void 0,execute:"list"};if(!t.record_id&&!t.user_id)throw new a("Either record_id or user_id must be provided.",{code:"INVALID_PARAMETER"});if(t.user_id)if(typeof t.user_id=="string")g.UserId(t.user_id),t.user_id=[t.user_id];else if(Array.isArray(t.user_id))for(let s of t.user_id)g.UserId(s);else throw new a("user_id should be type: <string | string[]>",{code:"INVALID_PARAMETER"});let i=s=>(s.rec_usr?(s.record_id=s.rec_usr.split("/")[0],s.user_id=s.rec_usr.split("/")[1]):s.usr_rec&&(s.user_id=s.usr_rec.split("/")[0],s.record_id=s.usr_rec.split("/")[1]),s),r=await E.bind(this)("grant-private-access",t,{auth:true,fetchOptions:e});return r.list=r.list.map(i),r}function Qt(n){let e=n.record_id,t=n.reference_id||void 0;if(!e)throw new a("Record ID is required.",{code:"INVALID_PARAMETER"});if(typeof e!="string")throw new a("Record ID should be type: <string | string[]>",{code:"INVALID_PARAMETER"});if(t&&typeof t!="string")throw new a("Reference ID should be type: <string>",{code:"INVALID_PARAMETER"});if(typeof this.__private_access_key[e]=="string")return Promise.resolve(this.__private_access_key[e]);if(Ae[e])return Ae[e];let i=E.bind(this)("request-private-access-key",{record_id:e,reference_id:t},{auth:true}).then(r=>{let s=typeof r=="string"?r:r?.private_key;if(typeof s!="string")throw new a("Invalid private access key response.",{code:"ERROR"});return this.__private_access_key[e]=s,s}).finally(()=>{delete Ae[e];});return Ae[e]=i,i}function Wt(n){n.execute;let t=g.Params(n,{record_id:"string",user_id:i=>{if(!i)throw new a("User ID is required.",{code:"INVALID_PARAMETER"});let r=i;if(typeof r=="string"&&(r=[r]),r.length>100)throw new a("Cannot process more than 100 users at once.",{code:"INVALID_REQUEST"});for(let s of r)g.UserId(s,'User ID in "user_id"');return r},execute:["add","remove"]},["execute","record_id","user_id"]);return t.user_id||(t.user_id=null),E.bind(this)("grant-private-access",t,{auth:true})}var A={},C={},K={},H={},W={},Se={},Te={};function Ht(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&&Ht(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 Ht(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],C[s]&&Object.values(C[s]).forEach(o=>{o.readyState!=="closed"&&o.close();}),delete C[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 Jt(n){if(n instanceof MediaStream)return n;if(!n.video&&!n.audio){let e=new MediaStream,t=document.createElement("canvas");t.width=1,t.height=1;let r=t.captureStream().getVideoTracks()[0];return e.addTrack(r),e}return window.navigator.mediaDevices.getUserMedia(n)}async function zt(n,e){if(typeof window>"u"||window._runningInNodeJS)throw new a("WebRTC is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(typeof e!="function")throw new a("Callback is required.",{code:"INVALID_PARAMETER"});if(!this?.session?.accessToken?.jwtToken)throw new a("Access token is required.",{code:"INVALID_PARAMETER"});n=g.Params(n,{cid:o=>{if(typeof o!="string")throw new a('"cid" should be type: <string>.',{code:"INVALID_PARAMETER"});if(o&&o.slice(0,4)!=="cid:")throw new a('"cid" should be a valid connection id.',{code:"INVALID_PARAMETER"});return o},ice:["string",()=>"stun:stun.skapi.com:3468"],media:o=>o,channels:["text-chat","file-transfer","video-chat","voice-chat","gaming",{ordered:"boolean",maxPacketLifeTime:"number",maxRetransmits:"number",protocol:"string"},()=>[{ordered:true,maxPacketLifeTime:10,protocol:"default"}]]},["cid"]);let{cid:t,ice:i}=n;if(!(n?.media instanceof MediaStream)&&(n?.media?.video||n?.media?.audio)&&window.location.hostname!=="localhost"&&window.location.protocol!=="https:")throw new a("Media stream is only supported on either localhost or https.",{code:"INVALID_REQUEST"});let r=this.__socket?await this.__socket:this.__socket;if(!r)throw new a("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});if(r.readyState!==1)throw new a("Realtime connection is not ready.",{code:"INVALID_REQUEST"});let s={iceServers:[{urls:i}]};A?.[t]||(A[t]=new RTCPeerConnection(s)),n?.media&&(this.__mediaStream=await Jt(n.media),this.__mediaStream.getTracks().forEach(o=>{A[t].addTrack(o,this.__mediaStream);})),W[t]=e,C[t]||(C[t]={});for(let o=0;o<n.channels.length;o++){let c=n.channels[o];if(typeof c=="string")switch(c){case "text-chat":c={ordered:true,maxRetransmits:10,protocol:"text-chat"};break;case "file-transfer":c={ordered:false,maxPacketLifeTime:3e3,protocol:"file-transfer"};break;case "video-chat":c={ordered:true,maxRetransmits:10,protocol:"video-chat"};break;case "voice-chat":c={ordered:true,maxRetransmits:10,protocol:"voice-chat"};break;case "gaming":c={ordered:false,maxPacketLifeTime:100,protocol:"gaming"};break;default:c={ordered:true,maxRetransmits:10,protocol:"default"};break}let u=c.protocol||"default";if(Object.keys(C[t]).includes(u))throw new a(`Data channel with the protocol "${u}" already exists.`,{code:"INVALID_REQUEST"});let d=A[t].createDataChannel(u,c);C[t][u]=d;}for(let o in C[t]){let c=C[t][o];Zt.bind(this)(t,c);}return Xt.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:C[t],hangup:()=>Q.bind(this)({cid:t}),media:this.__mediaStream});}).bind(this);})}}function Gt(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 Jt(e.media),this.__mediaStream.getTracks().forEach(o=>{A[i].addTrack(o,this.__mediaStream);})),delete H[i],W[i]=t,C[i]||(C[i]={}),A[i].ondatachannel=o=>{this.log("ondatachannel",`received data channel "${o.channel.label}".`);let c=o.channel;C[i][c.label]=c,Zt.bind(this)(i,c);},Xt.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:C[i],hangup:()=>Q.bind(this)({cid:i}),media:this.__mediaStream}}}async function Ve(n){if(!this?.session?.accessToken?.jwtToken)throw new a("Access token is required.",{code:"INVALID_PARAMETER"});this.log("sendOffer",n);let e=await this.__socket,t=await 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 Xt(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 Zt(n,e,t){let i=new Set(t),r=W[n]||(o=>{}),s={onmessage:o=>{let c={type:o.type,target:e,timeStamp:o.timeStamp,data:o.data,lastEventId:o.lastEventId,origin:o.origin,readyState:e.readyState,bufferedAmount:e.bufferedAmount};this.log(`${e.label}: message`,o.data),r(c);},onerror:o=>{let c={type:o.type,target:e,timeStamp:o.timeStamp,error:o.error.message,errorCode:o.error.errorDetail,readyState:e.readyState,label:e.label};this.log(`${e.label}: error`,o.error.message),r(c);},onclose:o=>{let c={type:o.type,target:e,timeStamp:o.timeStamp,readyState:e.readyState,label:e.label,id:e.id};this.log(`${e.label}: closed`,null),r(c),C[n]&&(delete C[n][e.label],Object.keys(C[n]).length===0&&Q.bind(this)({cid:n}));},onbufferedamountlow:o=>{let c={target:e,bufferedAmount:e.bufferedAmount,bufferedAmountLowThreshold:e.bufferedAmountLowThreshold,type:o.type,timeStamp:o.timeStamp};this.log(`${e.label}: bufferedamountlow`,e.bufferedAmount),r(c);},onopen:o=>{this.log("dataChannel",`data channel: "${e.label}" is open and ready to send messages.`);let c={type:o.type,target:e,timeStamp:o.timeStamp,readyState:e.readyState,label:e.label,id:e.id,ordered:e.ordered,maxRetransmits:e.maxRetransmits,protocol:e.protocol};r(c);}};for(let[o,c]of Object.entries(s))i.has(o)||(e[o]=c);}var Z,X=null,ge=true,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 Yt(){if(typeof window>"u"||window._runningInNodeJS)throw new a("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});ge=true;let n=this.__socket?await this.__socket:this.__socket;Q.bind(this)({close_all:true}),Z&&Be.bind(this)({group:null}),ie=0,X&&(X.terminate(),X=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;X&&(X.terminate(),X=null),this.__socket=new Promise(async i=>{await ne.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."}),Z&&r.send(JSON.stringify({action:"joinRoom",rid:Z,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 Ln=Object.defineProperty;var On=Object.getOwnPropertyDescriptor;var ee=(n=>t
|
|
|
212
212
|
}
|
|
213
213
|
|
|
214
214
|
runInterval(); // Start interval
|
|
215
|
-
`,o=new Blob([s],{type:"application/javascript"});Z=new Worker(URL.createObjectURL(o)),Z.onmessage=c=>{r.readyState===1&&r.send(JSON.stringify({action:"keepAlive"}));},i(r);},r.onmessage=async s=>{let o="";try{o=JSON.parse(decodeURI(s.data)),this.log("socket onmessage",o);}catch{return}let c;switch(true){case !!o?.["#message"]:c="message";break;case !!o?.["#private"]:c="private";break;case !!o?.["#notice"]:c="notice";break;case !!o?.["#rtc"]:c="rtc";break;case !!o?.["#error"]:c="error";break}if(!c)return;let 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}
|
|
215
|
+
`,o=new Blob([s],{type:"application/javascript"});X=new Worker(URL.createObjectURL(o)),X.onmessage=c=>{r.readyState===1&&r.send(JSON.stringify({action:"keepAlive"}));},i(r);},r.onmessage=async s=>{let o="";try{o=JSON.parse(decodeURI(s.data)),this.log("socket onmessage",o);}catch{return}let c;switch(true){case !!o?.["#message"]:c="message";break;case !!o?.["#private"]:c="private";break;case !!o?.["#notice"]:c="notice";break;case !!o?.["#rtc"]:c="rtc";break;case !!o?.["#error"]:c="error";break}if(!c)return;let u={type:c,message:o?.["#rtc"]||o?.["#message"]||o?.["#private"]||o?.["#notice"]||o?.["#error"]||null,sender:o?.["#user_id"]||null,sender_cid:o?.["#scid"]?"cid:"+o["#scid"]:null,sender_rid:o?.["#srid"]||null,code:o?.["#code"]||null};if(c==="notice")n(u);else if(c==="rtc"){if(u.sender!==this.user.user_id){let d=u.message;if(d.hungup){K[u.sender_cid]&&(K[u.sender_cid](false),delete K[u.sender_cid]),H[u.sender_cid]&&delete H[u.sender_cid],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=Gt.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 en(n,e,t){if(typeof window>"u"||window._runningInNodeJS)throw new a("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});let i=this.__socket?await this.__socket:this.__socket;if(!i)throw new a("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});if(!e)throw new a("No recipient.",{code:"INVALID_REQUEST"});await ne.bind(this)(),n=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}),Z!==e)throw new a(`User has not joined to the recipient group. Run joinRealtime({ group: "${e}" })`,{code:"INVALID_REQUEST"});i.send(JSON.stringify({action:"broadcast",rid:e,content:n,notification:r,notificationConfig:t?.config||{},token:`IdT:${this.service}:${this.owner}:`+(this.bearerToken||this.session?.idToken?.jwtToken||"null")}));}return {type:"success",message:"Message sent."}}throw new a("Realtime connection is not open. Try reconnecting with connectRealtime().",{code:"INVALID_REQUEST"})}async function Be(n){if(typeof window>"u"||window._runningInNodeJS)throw new a("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});let e=this.__socket?await this.__socket:this.__socket;if(!e)throw new a("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});await ne.bind(this)(),n=v(n,{nullIfEmpty:true}).data;let{group:t=null}=n;if(!t&&!Z)return {type:"success",message:"Left realtime message group."};if(t!==null&&typeof t!="string")throw new a('"group" must be a string | null.',{code:"INVALID_PARAMETER"});return e.send(JSON.stringify({action:"joinRoom",rid:t,token:this.session.accessToken.jwtToken})),Z=t,{type:"success",message:t?`Joined realtime message group: "${t}".`:"Left realtime message group."}}async function tn(n,e){n=g.Params(n,{user_id:i=>g.UserId(i,'User ID in "user_id"'),group:["string",()=>{if(!Z)throw new a('No group has been joined. Otherwise "group" is required.',{code:"INVALID_REQUEST"});return Z}]});let t=await E.bind(this)("get-ws-group",n,{fetchOptions:e,auth:true,method:"post"});return t.list=t.list.map(i=>({user_id:i.uid.split("#")[1],cid:"cid:"+i.cid})),t}async function nn(n,e){if(await this.__connection,n||(n={searchFor:"group",value:" ",condition:">"}),n=g.Params(n,{searchFor:["group","number_of_users",()=>"group"],value:["string","number",()=>n?.searchFor&&n?.searchFor==="number_of_users"?0:" "],condition:[">",">=","=","<","<=","!=","gt","gte","eq","lt","lte","ne"],range:["string","number"]}),n.condition||(n.value===" "||!n.value?n.condition=">":n.condition="="),n.range&&n.condition&&delete n.condition,n.searchFor==="number_of_users"&&typeof n.value!="number")throw new a('"value" must be a number.',{code:"INVALID_PARAMETER"});if(n.searchFor==="group"&&typeof n.value!="string")throw new a('"value" must be a string.',{code:"INVALID_PARAMETER"});if(n.hasOwnProperty("range")&&typeof n.range!=typeof n.value)throw new a(`"range" must be a ${typeof n.value}.`,{code:"INVALID_PARAMETER"});let t=await E.bind(this)("get-ws-group",n,{fetchOptions:e,auth:true,method:"post"});return t.list=t.list.map(i=>({group:i.rid.split("#")[1],number_of_users:i.cnt})),t}var Sr=typeof FormData<"u",Tr=typeof HTMLFormElement<"u",Pr=typeof SubmitEvent<"u";async function rn(n){let e=false,t=r=>{for(let s in r)if(typeof r[s]=="string"&&r[s].includes("$CLIENT_SECRET")){e=true;break}};if(n=g.Params(n,{url:r=>{if(!r||typeof r!="string")throw new a('"url" should be type: <string>.',{code:"INVALID_PARAMETER"});return g.Url(r),r.includes("$CLIENT_SECRET")&&(e=true),r},clientSecretName:"string",method:r=>{if(r&&typeof r!="string")throw new a('"method" should be either "GET" or "POST" or "DELETE" or "PUT".',{code:"INVALID_PARAMETER"});let s=r.toLowerCase();if(s!=="get"&&s!=="post"&&s!=="delete"&&s!=="put")throw new a('"method" should be either "GET" or "POST" or "DELETE" or "PUT".',{code:"INVALID_PARAMETER"});return s},headers:r=>{if(r&&typeof r!="object")throw new a('"headers" should be type: <object>.',{code:"INVALID_PARAMETER"});return t(r),r},data:r=>{if(r&&typeof r!="object")throw new a('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return t(r),r},params:r=>{if(r&&typeof r!="object")throw new a('"params" should be type: <object>.',{code:"INVALID_PARAMETER"});return t(r),r}},["clientSecretName","method","url"]),!e)throw new a(`At least one parameter value should include "$CLIENT_SECRET" in ${n.method.toLowerCase()==="post"?'"data"':'"params"'} or "headers".`,{code:"INVALID_PARAMETER"});await this.__connection;let i=!!this.__user;return E.bind(this)("csr",n,{auth:i})}async function sn(n){await this.__connection;let e={name:"string",email:t=>(g.Email(t),t),subject:"string",message:"string"};return n=g.Params(n,e,["name","email","subject","message"]),await E.bind(this)("send-inquiry",n),"SUCCESS: Inquiry has been sent."}async function on(n,e){if(await this.__connection,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 E.bind(this)("post-secure",n,{auth:true})}async function an(n,e){await this.__connection;let{auth:t=false,method:i="POST",bypassAwaitConnection:r=false,responseType:s,contentType:o,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 E.bind(this)("mock",n,e)}async function cn(n,e){await this.__connection,n=g.Params(n||{},{access_group:i=>{if(i==="authorized"&&(i=1),i==="public"&&(i=0),typeof i!="number")throw new a('"access_group" should be type number.',{code:"INVALID_PARAMETER"});if(i<0)throw new a('"access_group" should be zero or a positive number.',{code:"INVALID_PARAMETER"});if(i>this.__user.access_group)throw new a("User has no access.",{code:"INVALID_REQUEST"});return i}});let t=await E.bind(this)("get-feed",n,{auth:true,fetchOptions:e});for(let i in t.list)t.list[i]=await 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 ln(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 E.bind(this)("get-subscription",n,Object.assign({auth:true},{fetchOptions:e}));return t.list=t.list.map((i=>{let r={};if(i.sub){let s=i.sub.split("#");r.subscriber=s[2],r.subscription=s[0];}else r.subscriber=i.subscriber,r.subscription=i.subscription;return r.timestamp=i?.timestamp||i.stmp,r.blocked=i?.blocked||i.grp.substring(0,1)==="N",Object.assign(r,i.opt),r})),t}async function un(n){await this.__connection,n=g.Params(n,{user_id:fe.bind(this),get_feed:["boolean",()=>false],get_notified:["boolean",()=>false],get_email:i=>{if(i&&!this.__user.email||!this.__user.email_verified)throw new a("User has no verified email address.",{code:"INVALID_REQUEST"});return !!i}},["user_id"]);let e=await E.bind(this)("subscription",{subscribe:n.user_id,option:{get_feed:n.get_feed,get_notified:n.get_notified,get_email:n.get_email||false}},{auth:true}),t={};if(e.sub){let i=e.sub.split("#");t.subscriber=i[2],t.subscription=i[0];}else t.subscriber=e.subscriber,t.subscription=e.subscription;return t.timestamp=e?.timestamp||e.stmp,t.blocked=e?.blocked||e.grp.substring(0,1)==="N",Object.assign(t,e.opt),t}async function dn(n){await this.__connection;let{user_id:e}=g.Params(n,{user_id:fe.bind(this)},["user_id"]);return await E.bind(this)("subscription",{unsubscribe:e},{auth:true})}async function gn(n){await this.__connection;let{user_id:e}=g.Params(n,{user_id:fe.bind(this)},["user_id"]);return await E.bind(this)("subscription",{block:e},{auth:true})}async function fn(n){await this.__connection;let{user_id:e}=g.Params(n,{user_id:fe.bind(this)},["user_id"]);return await E.bind(this)("subscription",{unblock:e},{auth:true})}async function hn(n,e){await this.__connection;let t=await M.bind(this)();n=g.Params(n,{user_id:o=>{if(o!==this.__user.user_id&&!t)throw new a("No access.",{code:"INVALID_REQUEST"});return o},group:o=>{if(o==="public"&&(o=0),o==="authorized"&&(o=1),typeof o!="number")throw new a('"group" should be type number | "public" | "authorized".',{code:"INVALID_PARAMETER"});return o}});let i=await E.bind(this)("get-newsletter-subscription",n,{auth:true,fetchOptions:e||null}),r=i?.list||i,s=[];Array.isArray(r)||(r=[]);for(let o of r){let c=o.subt.split("#"),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 pn(n){await this.__connection;let e=g.Params(n||{},{email:t=>Array.isArray(t)&&t.length>0?t.length===1?g.Email(t[0]):t.map(i=>g.Email(i)):g.Email(t),group:["number","public","authorized","admin",t=>{if(typeof t!="string"||t.length>20||!/^[a-zA-Z0-9]+$/.test(t))throw new a('"group" should be an alphanumeric string without spaces and less than 20 characters.',{code:"INVALID_PARAMETER"});return t}],redirect:t=>g.Url(t)},this.__user?["group"]:["email","group"]);return E.bind(this)(`subscribe-${this.__user?"":"public-"}newsletter`,e,{auth:!!this.__user})}async function mn(n){await this.__connection,n=g.Params(n,{group:["number","public","authorized","admin"]},["group"]);let e=Object.assign({action:"unsubscribe"},n);return E.bind(this)("subscribe-newsletter",e,{auth:true})}async function bn(n,e){let t=await M.bind(this)(),i={message_id:"string",timestamp:"number",read:"number",complaint:"number",subject:"string",bounced:"number"};n||(e=Object.assign({ascending:false},e||{})),n=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 E.bind(this)(r,n,Object.assign({method:"get",auth:r==="get-public-newsletters"?!!this.__user:true},{fetchOptions:e})),o={message_id:"mid",timestamp:"stmp",complaint:"cmpl",read:"read",subject:"subj",bounced:"bnce",url:"url",delivered:"delv"},c={message_id:"",timestamp:0,complaint:0,read:0,subject:"",bounced:"",url:"",delivered:0};return s.list=s.list.map(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 _n(n){let e=g.Params(n,{user_id:i=>g.UserId(i,'"user_id"')},["user_id"]);if(e?.service&&e?.owner?e={service:e?.service,owner:e?.owner,block:e.user_id}:e={block:e.user_id},!await M.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}return await E.bind(this)("block-account",e,{auth:true})}async function yn(n){let e=g.Params(n,{user_id:i=>g.UserId(i,'"user_id"')},["user_id"]);if(e?.service&&e?.owner?e={service:e?.service,owner:e?.owner,unblock:e.user_id}:e={unblock:e.user_id},!await M.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}return await E.bind(this)("block-account",e,{auth:true})}async function wn(n){let e=g.Params(n,{user_id:i=>g.UserId(i,'"user_id"')},["user_id"]);if(e?.service&&e?.owner?e={service:e?.service,owner:e?.owner,delete:e.user_id}:e={delete:e.user_id},!await M.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}return await E.bind(this)("remove-account",e,{auth:true})}async function En(n,e){let t={email:s=>g.Email(s),password:s=>g.Password(s),name:"string",username:"string",gender:"string",address:s=>{if(!s)return "";if(typeof s=="string")return s;if(typeof s=="object")return JSON.stringify(s)},birthdate:s=>g.Birthdate(s),phone_number:s=>g.PhoneNumber(s),picture:s=>{if(s)return g.Url(s)},profile:s=>{if(s)return g.Url(s)},website:s=>{if(s)return g.Url(s)},nickname:"string",misc:"string",email_public:["boolean",()=>false],gender_public:["boolean",()=>false],address_public:["boolean",()=>false],birthdate_public:["boolean",()=>false],phone_number_public:["boolean",()=>false],openid_id:"string",access_group:s=>{try{typeof s=="string"&&(s=s==="admin"?99:parseInt(s));}catch{throw new a('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof s!="number"||s<1||s>100)throw new a('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"});return s}},i=g.Params(n,t,["email"]);if(e=g.Params(e,{confirmation_url:s=>{let o=s;if(typeof s=="string")o=g.Url(s);else throw new a('"options.confirmation_url" should be type: <string>.',{code:"INVALID_PARAMETER"});if(o&&!i.email)throw new a('"email" is required for signup confirmation.',{code:"INVALID_PARAMETER"});return o},email_subscription:s=>{if(typeof s!="boolean")throw new a('"options.email_subscription" should be type: <boolean>.',{code:"INVALID_PARAMETER"});if(!e?.confirmation_url)throw new a('"options.confirmation_url" is required for email subscription.',{code:"INVALID_PARAMETER"});return s},template:s=>{if(typeof s!="object"||!s.url||!s.subject)throw new a('"options.template" should be type: <object> with "url" and "subject".',{code:"INVALID_PARAMETER"});return {url:g.Url(s.url),subject:s.subject}}}),i.signup_confirmation=e?.confirmation_url||true,i.email_subscription=e?.email_subscription||false,i.template=e?.template||{},!await M.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}return await E.bind(this)("admin-signup",i,{auth:true})}async function Rn(n){let e={email:r=>g.Email(r),password:r=>g.Password(r),openid_id:"string",name:"string",username:"string",gender:"string",address:r=>{if(!r)return "";if(typeof r=="string")return r;if(typeof r=="object")return JSON.stringify(r)},birthdate:r=>g.Birthdate(r),phone_number:r=>g.PhoneNumber(r),picture:r=>r?g.Url(r):"",profile:r=>r?g.Url(r):"",website:r=>r?g.Url(r):"",nickname:"string",misc:"string",email_public:["boolean",()=>false],gender_public:["boolean",()=>false],address_public:["boolean",()=>false],birthdate_public:["boolean",()=>false],phone_number_public:["boolean",()=>false],access_group:r=>{try{typeof r=="string"&&(r=parseInt(r));}catch{throw new a('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof r!="number"||r<1||r>100)throw new a('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"});return r}},t=g.Params(n,e,["email","password"]);if(!await M.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}return await E.bind(this)("admin-signup",t,{auth:true})}async function An(n){if(n=g.Params(n,{user_id:t=>g.UserId(t,'"user_id"'),access_group:t=>{try{typeof t=="string"&&(t=parseInt(t));}catch{throw new a('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof t=="number"&&t>0&&t<100)return t;throw new a('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"})}},["user_id","access_group"]),!await M.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}return await E.bind(this)("grant-access",n,{auth:true})}async function In(n,e){if(n=g.Params(n,{email:"string"}),!await M.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}let i=await E.bind(this)("invitation-list",Object.assign({mode:"search"},n),{fetchOptions:e,auth:true});return i.list=i.list.map(r=>oe(r.user)),i}async function Sn(n){if(n=g.Params(n,{email:t=>g.Email(t)},["email"]),!await M.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}return await E.bind(this)("invitation-list",Object.assign({mode:"cancel"},n),{auth:true})}async function Tn(n){if(n=g.Params(n,{email:t=>g.Email(t)},["email"]),!await M.bind(this)()){if(!this.__user)throw new a("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new a("Invalid access.",{code:"INVALID_REQUEST"})}return await E.bind(this)("invitation-list",Object.assign({mode:"resend"},n),{auth:true})}async function Pn(n){if(typeof window>"u"||window._runningInNodeJS)throw new a("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.__connection,!n.endpoint)throw new a("Missing parameter: endpoint",{code:"INVALID_PARAMETER"});if(!n.keys||!n.keys.p256dh||!n.keys.auth)throw new a("Missing parameter: keys.p256dh or keys.auth",{code:"INVALID_PARAMETER"});return await E.bind(this)("store-subscription",{endpoint:n.endpoint,keys:n.keys},{auth:true}),"SUCCESS: Subscribed to receive notifications."}async function kn(n){if(typeof window>"u"||window._runningInNodeJS)throw new a("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.__connection,!n.endpoint)throw new a("Missing parameter: endpoint",{code:"INVALID_PARAMETER"});if(!n.keys||!n.keys.p256dh||!n.keys.auth)throw new a("Missing parameter: keys.p256dh or keys.auth",{code:"INVALID_PARAMETER"});return await E.bind(this)("delete-subscription",{endpoint:n.endpoint,keys:n.keys},{auth:true}),"SUCCESS: Unsubscribed from notifications."}async function xn(){if(typeof window>"u"||window._runningInNodeJS)throw new a("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});return await this.__connection,{VAPIDPublicKey:await E.bind(this)("get-vapid-public-key",null,{auth:true})}}async function Dn(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 E.bind(this)("push-notification",r,{auth:true}),"SUCCESS: Notification sent."}async function vn(n){await this.__connection,n=g.Params(n,{spell:"string",name:"string",magic:t=>t},["spell","name"]);await E.bind(this)("castspell",n);return `The spell "${n.spell}" has been cast.`}async function Nn(n){return await this.__connection,n=g.Params(n||{},{search:["spell","name",()=>"spell"],value:"string"}),await E.bind(this)("getspell",n)}async function Un(n){await this.__connection,n=g.Params(n,{message:"string",name:"string"},["message","name"]);let e=await E.bind(this)("dopamine",n,{auth:true}),t=e?.previous_message?.message,i=e?.previous_message?.name;if($())t&&i&&window.alert(`${i} said: ${t}`),window.location.href=e.video;else return t&&i?`${i} said: ${t}
|
|
216
216
|
Watch the video here: ${e.video}`:`Your message has been uploaded for future generations to receive.
|
|
217
|
-
Watch the video here: ${e.video}`}var b=class{constructor(e,t,i,r){this.__version="1.5.0-beta.
|
|
217
|
+
Watch the video here: ${e.video}`}var b=class{constructor(e,t,i,r){this.__version="1.5.0-beta.8";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:se,toBase62:Ye,fromBase62:B,decodeServiceId:ve,formatServiceId:et,extractFormData:v,terminatePendingRequests:Pt,request:(e,t,i)=>E.bind(this)(e,t,i,{ignoreService:true})};this.__network_logs=false;this.__endpoint_version="v1";this.__public_identifier="";this.bearerToken="";this.registerTicket=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((m,R)=>{let h=new FileReader;h.onloadend=()=>m(h.result),h.onerror=R,h.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((m,R)=>{let h=new FileReader;h.onloadend=()=>m(h.result),h.onerror=R,h.readAsDataURL(l);})).then(l=>{try{return typeof l=="string"?JSON.parse(atob(l.split(",")[1])):null}catch{throw new a("Service does not exist. Create your service from skapi.com",{code:"NOT_EXISTS"})}});let u=$();if(u&&!window.sessionStorage)throw this._alert("This browser is not supported."),new Error("This browser is not supported.");let d=u?JSON.parse(window.sessionStorage.getItem(`${e}#${t}`)||"null"):null;if(this.log("constructor:restore",d),d?.connection){for(let l in d)this[l]=d[l];d.__public_identifier||(this.__public_identifier=`${this.service}:${this.owner}:${se(16)}`);}this.__authConnection=(async()=>{let l=await this.admin_endpoint,m={UserPoolId:l.userpool_id,ClientId:l.userpool_client};De()&&(m.Storage=window.localStorage),this.userPool=new amazonCognitoIdentityJs.CognitoUserPool(m);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 m=()=>{if(this.__class_properties_has_been_cached)return;let R=()=>{let h={},I=["__startKeyHistory","__disabledAccount","__cached_requests","__request_signup_confirmation","__public_identifier","connection"];if(this.connection){for(let k of I)h[k]=this[k];u&&window.sessionStorage.setItem(`${e}#${t}`,JSON.stringify(h)),this.__class_properties_has_been_cached=true;}};return l instanceof Promise?l.then(()=>R()):R()};return u&&(window.addEventListener("beforeunload",()=>{this.closeRealtime(),m();}),window.addEventListener("visibilitychange",()=>{m();})),await l,await this.__authConnection,this.connection})(),this.__connection.then(l=>{((l?.group||0)<3||this.__network_logs)&&this.version();});}get user(){return this.__user&&Object.keys(this.__user).length?JSON.parse(JSON.stringify(this.__user)):null}set user(e){}get onLogin(){return this._onLoginListeners}set onLogin(e){typeof e=="function"&&this._onLoginListeners.push(e);}get onUserUpdate(){return this._userProfileListeners}set onUserUpdate(e){typeof e=="function"&&this._userProfileListeners.push(e);}_runOnUserUpdateListeners(e){for(let t of this._userProfileListeners)typeof t=="function"&&t(e);}_runOnLoginListeners(e){for(let t of this._onLoginListeners)typeof t=="function"&&t(e);}get onBatchProcess(){return this._onBatchProcessListeners}set onBatchProcess(e){typeof e=="function"&&this._onBatchProcessListeners.push(e);}_alert(e){$()&&typeof window.alert=="function"&&window.alert(e);}async getConnectionInfo(){let e=await this.__connection,t=e?.user_agent||($()&&typeof window.navigator?.userAgent=="string"?window.navigator.userAgent:`skapi-node/${globalThis?.process?.versions?.node||"unknown"}`);return {user_ip:e.ip,user_agent:t,user_location:e.locale,service_name:e.service_name,version:this.__version}}async _updateConnection(){try{this.connection=await E.bind(this)("service",{service:this.service,owner:this.owner},{bypassAwaitConnection:!0,method:"get"});}catch(e){throw this.log("connection fail",e),this._alert("Service is not available: "+(e.message||e.toString())),this.connection=null,e}return this.connection}async version(){if(await this.__connection,$()){let t=`Built with:
|
|
218
218
|
%c\r
|
|
219
219
|
$$\\ $$\\ \r
|
|
220
220
|
$$ | \\__|\r
|
|
@@ -229,6 +229,6 @@ $$$$$$$ |$$ | \\$$\\\\$$$$$$$ |$$$$$$$ |$$ |\r
|
|
|
229
229
|
\\__| \r
|
|
230
230
|
Version: ${this.__version}
|
|
231
231
|
|
|
232
|
-
Full Documentation: https://docs.skapi.com/skapi.md`;console.log(t,"font-family: monospace; color:blue;"),this.connection.group===1&&console.log("%cSKAPI: THE SERVICE IS IN TRIAL MODE.","font-family: monospace; color:red;");}return this.__version}log(e,t){if(this.__network_logs){if(typeof t=="object")try{t=JSON.parse(JSON.stringify(t));}catch{t=String(t);}else typeof t=="string"&&t.length>100&&(t=t.substring(0,100)+"...");console.log(`%c${e}:`,"color: blue;",t);}}getFeed(e,t){return
|
|
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 cn.bind(this)(e,t)}closeRTC(e){return Q.bind(this)(e)}connectRTC(e,t){return zt.bind(this)(e,t)}connectRealtime(e){return ke.bind(this)(e)}spellcast(e){return vn.bind(this)(e)}getspell(e){return Nn.bind(this)(e)}dopamine(e){return Un.bind(this)(e)}getUniqueId(e,t){return $t.bind(this)(e,t)}resendInvitation(e){return Tn.bind(this)(e)}cancelInvitation(e){return Sn.bind(this)(e)}getInvitations(e,t){return In.bind(this)(e,t)}openIdLogin(e){return ct.bind(this)(e)}loginWithToken(e){return lt.bind(this)(e)}clientSecretRequest(e){return rn.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 Yt.bind(this)()}getRealtimeUsers(e,t){return tn.bind(this)(e,t)}sendInquiry(e){return sn.bind(this)(e)}blockAccount(e){return _n.bind(this)(e)}unblockAccount(e){return yn.bind(this)(e)}deleteAccount(e){return wn.bind(this)(e)}inviteUser(e,t){return En.bind(this)(e,t)}createAccount(e){return Rn.bind(this)(e)}grantAccess(e){return An.bind(this)(e)}getRealtimeGroups(e,t){return nn.bind(this)(e,t)}postRealtime(e,t,i){return en.bind(this)(e,t,i)}joinRealtime(e){return Be.bind(this)(e)}getProfile(e){return at.bind(this)(e)}getFile(e,t){return Ie.bind(this)(e,t)}secureRequest(e,t){return on.bind(this)(e,t)}getFormResponse(){return xt.bind(this)()}getRecords(e,t){return Lt.bind(this)(e,t)}getTables(e,t){return Ft.bind(this)(e,t)}getIndexes(e,t){return Mt.bind(this)(e,t)}getTags(e,t){return Vt.bind(this)(e,t)}deleteRecords(e,t){return qt.bind(this)(e,t)}resendSignupConfirmation(){return 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 mn.bind(this)(e)}subscribeNotification(e,t){return Pn.bind(this)({endpoint:e,keys:t})}unsubscribeNotification(e,t){return kn.bind(this)({endpoint:e,keys:t})}vapidPublicKey(){return xn.bind(this)()}pushNotification(e,t){return Dn.bind(this)(e,t)}getNewsletters(e,t){return bn.bind(this)(e,t)}getNewsletterSubscription(e,t){return hn.bind(this)(e,t)}requestUsernameChange(e){return At.bind(this)(e)}grantPrivateRecordAccess(e){return jt.bind(this)(e)}removePrivateRecordAccess(e){return Bt.bind(this)(e)}listPrivateRecordAccess(e){return Kt.bind(this)(e)}requestPrivateRecordAccessKey(e){return Qt.bind(this)(e)}deleteFiles(e){return Ut.bind(this)(e)}uploadFiles(e,t){return we.bind(this)(e,t)}mock(e,t){return an.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 Ot.bind(this)(e,t,i)}getSubscriptions(e,t){return ln.bind(this)(e,t)}subscribe(e){return un.bind(this)(e)}unsubscribe(e){return dn.bind(this)(e)}blockSubscriber(e){return gn.bind(this)(e)}unblockSubscriber(e){return fn.bind(this)(e)}subscribeNewsletter(e){return pn.bind(this)(e)}};_([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
233
|
exports.Skapi=b;exports.SkapiError=a;exports.Types=xr;//# sourceMappingURL=skapi.cjs.map
|
|
234
234
|
//# sourceMappingURL=skapi.cjs.map
|