skapi-js 2.0.5 → 2.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/skapi.browser.mjs +6 -6
- package/dist/skapi.browser.mjs.map +1 -1
- package/dist/skapi.cjs +6 -6
- package/dist/skapi.cjs.map +1 -1
- package/dist/skapi.d.mts +793 -55
- package/dist/skapi.d.ts +793 -55
- package/dist/skapi.js +6 -6
- package/dist/skapi.js.map +1 -1
- package/dist/skapi.mjs +6 -6
- package/dist/skapi.mjs.map +1 -1
- package/package.json +2 -2
package/dist/skapi.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {CognitoUserPool,AuthenticationDetails,CognitoUserSession,CognitoRefreshToken,CognitoAccessToken,CognitoIdToken,CognitoUser,CognitoUserAttribute}from'amazon-cognito-identity-js';import
|
|
1
|
+
import {CognitoUserPool,AuthenticationDetails,CognitoUserSession,CognitoRefreshToken,CognitoAccessToken,CognitoIdToken,CognitoUser,CognitoUserAttribute}from'amazon-cognito-identity-js';import Po from'cocochex';import as from'qpass';/**
|
|
2
2
|
* @license
|
|
3
3
|
Apache License
|
|
4
4
|
Version 2.0, January 2004
|
|
@@ -203,7 +203,7 @@ import {CognitoUserPool,AuthenticationDetails,CognitoUserSession,CognitoRefreshT
|
|
|
203
203
|
limitations under the License.
|
|
204
204
|
|
|
205
205
|
*/
|
|
206
|
-
var Qs=Object.defineProperty;var zs=Object.getOwnPropertyDescriptor;var ke=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var P=(e,t,r,n)=>{for(var i=zs(t,r),s=e.length-1,o;s>=0;s--)(o=e[s])&&(i=(o(t,r,i))||i);return i&&Qs(t,r,i),i};function vr(e){let r=(typeof globalThis<"u"?globalThis:void 0)?.process;if(r&&typeof r.getBuiltinModule=="function")try{return r.getBuiltinModule(e)}catch{}try{if(typeof ke=="function")return ke(e)}catch{}return null}var Ct,Lt,Ot=()=>Ct!==void 0?Ct:Ct=vr("fs"),Mt=()=>Lt!==void 0?Lt:Lt=vr("path"),me=typeof globalThis<"u"?globalThis:void 0,ut=me?.window;function Js(e){if(Buffer)return Buffer.from(e).toString("base64");let t="",r=new Uint8Array(e),n=32768;for(let i=0;i<r.length;i+=n){let s=r.subarray(i,i+n);t+=String.fromCharCode.apply(null,Array.from(s));}if(typeof btoa=="function")return btoa(t);throw new Error("No base64 encoder available in this environment.")}if(ut)ut.global=ut,ut.global._runningInNodeJS=false;else if(me&&(me.global=me,typeof me.window>"u")){class e{constructor(){this.result=null;this.error=null;this.onload=null;this.onloadend=null;this.onerror=null;}readAsDataURL(n){n.arrayBuffer().then(i=>{let s=Js(i),o=n.type||"application/octet-stream";this.result=`data:${o};base64,${s}`,this.onload&&this.onload({target:this}),this.onloadend&&this.onloadend({target:this});}).catch(i=>{this.error=i,this.onerror&&this.onerror({target:this});});}readAsArrayBuffer(n){n.arrayBuffer().then(i=>{this.result=i,this.onload&&this.onload({target:this}),this.onloadend&&this.onloadend({target:this});}).catch(i=>{this.error=i,this.onerror&&this.onerror({target:this});});}readAsText(n,i="utf-8"){n.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});});}}me.FileReader=e;class t{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(n,i){this._method=n,this._url=i,this.readyState=1;}setRequestHeader(n,i){this._headers[n]=i;}getResponseHeader(n){return null}abort(){this._aborted=true,this.onabort&&this.onabort({});}send(n){if(this._aborted)return;let i={method:this._method,headers:this._headers};n&&this._method!=="GET"&&this._method!=="HEAD"&&(i.body=n),fetch(this._url,i).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);});}}me.XMLHttpRequest=t,me.window={_runningInNodeJS:true,alert:r=>console.error("[Alert]",r),sessionStorage:{getItem:r=>null,setItem:(r,n)=>{},removeItem:r=>{}},localStorage:{getItem:r=>{let n=Ot(),i=Mt();if(!n||!i)return null;try{let s=i.resolve(process.cwd(),"states","localStorage",`${r}.skapi`);return n.existsSync(s)?n.readFileSync(s,"utf8"):null}catch{return null}},setItem:(r,n)=>{let i=Ot(),s=Mt();if(!(!i||!s))try{let o=s.resolve(process.cwd(),"states","localStorage");i.existsSync(o)||i.mkdirSync(o,{recursive:!0});let a=s.resolve(o,`${r}.skapi`);i.writeFileSync(a,n,"utf8");}catch{}},removeItem:r=>{let n=Ot(),i=Mt();if(!(!n||!i))try{let s=i.resolve(process.cwd(),"states","localStorage",`${r}.skapi`);n.existsSync(s)&&n.unlinkSync(s);}catch{}}},location:{href:"",origin:"",hostname:"",protocol:"",replace:r=>{}},navigator:{userAgent:`nodejs/${me?.process?.versions?.node||"unknown"}`,mediaDevices:{getUserMedia:async r=>{throw new Error("getUserMedia is not supported in Node.js environment.")}}},addEventListener:()=>{},removeEventListener:()=>{}};}var c=class extends Error{constructor(t,r){if(Array.isArray(t)&&t.length<=2){let n=t[1];if(t.length>2)for(let i=2;i<t.length&&typeof t[i]=="string";i++)n+=t[i];super((n||"Something went wrong.").trim()),this.name=r?.name||"SKAPI",this.code=r?.code||t[0]||"ERROR",r?.cause&&(this.cause=r.cause);}else super((t?.message||(typeof t=="string"?t:"Something went wrong.")).trim()),typeof t=="string"?(this.name=r?.name||"SKAPI",this.code=r?.code||"ERROR",r?.cause&&(this.cause=r.cause)):t instanceof Error?(this.cause=t,this.name=t.name,t.hasOwnProperty("code")&&(this.code=t.code)):typeof t=="object"&&t?.code&&t?.message&&(this.name=r?.name||"SKAPI",this.code=r?.code||"ERROR",this.cause=t?.cause);}};var ye="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Ft=BigInt(ye.length),Ys=2*1024*1024,Xs=["aud","cognito:username","event_id","exp","iat","iss","jti","origin_jti","secret_key","token_use"],Nr={auth_time:"log",sub:"user_id"},Lr=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f","g","h","i","j","k","l"],Or=["us31","us72","ap51","ap22","ap41","eu71","ap21","us32","us71","af51","ap31","ap43","ap23","ap42","ca01","eu01","eu72","eu51","eu73","eu11","me51","sa31"],Ur=typeof TextEncoder<"u"?new TextEncoder:null;function Zs(){if(typeof globalThis<"u")return globalThis.Buffer}function K(e){if(Ur)return Ur.encode(e);let t=unescape(encodeURIComponent(e)),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}function qt(e){if(e instanceof Uint8Array)return e;if(typeof e=="string")return K(e);if(typeof ArrayBuffer<"u"&&e instanceof ArrayBuffer)return new Uint8Array(e);if(typeof ArrayBuffer<"u"&&ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);if(Array.isArray(e))return Uint8Array.from(e);let t=Zs();if(t)return new Uint8Array(t.from(e));throw new Error("No byte conversion available in this environment.")}var R=class R{static hash(t){typeof t!="string"&&(console.warn("coercing non-string value to empty string"),t="");let r=R.sb(t),n=1732584193,i=-271733879,s=-1732584194,o=271733878,a,u,l,g;for(let f=0;f<r.length;f+=16)a=n,u=i,l=s,g=o,n=R.ff(n,i,s,o,r[f],7,-680876936),o=R.ff(o,n,i,s,r[f+1],12,-389564586),s=R.ff(s,o,n,i,r[f+2],17,606105819),i=R.ff(i,s,o,n,r[f+3],22,-1044525330),n=R.ff(n,i,s,o,r[f+4],7,-176418897),o=R.ff(o,n,i,s,r[f+5],12,1200080426),s=R.ff(s,o,n,i,r[f+6],17,-1473231341),i=R.ff(i,s,o,n,r[f+7],22,-45705983),n=R.ff(n,i,s,o,r[f+8],7,1770035416),o=R.ff(o,n,i,s,r[f+9],12,-1958414417),s=R.ff(s,o,n,i,r[f+10],17,-42063),i=R.ff(i,s,o,n,r[f+11],22,-1990404162),n=R.ff(n,i,s,o,r[f+12],7,1804603682),o=R.ff(o,n,i,s,r[f+13],12,-40341101),s=R.ff(s,o,n,i,r[f+14],17,-1502002290),i=R.ff(i,s,o,n,r[f+15],22,1236535329),n=R.gg(n,i,s,o,r[f+1],5,-165796510),o=R.gg(o,n,i,s,r[f+6],9,-1069501632),s=R.gg(s,o,n,i,r[f+11],14,643717713),i=R.gg(i,s,o,n,r[f],20,-373897302),n=R.gg(n,i,s,o,r[f+5],5,-701558691),o=R.gg(o,n,i,s,r[f+10],9,38016083),s=R.gg(s,o,n,i,r[f+15],14,-660478335),i=R.gg(i,s,o,n,r[f+4],20,-405537848),n=R.gg(n,i,s,o,r[f+9],5,568446438),o=R.gg(o,n,i,s,r[f+14],9,-1019803690),s=R.gg(s,o,n,i,r[f+3],14,-187363961),i=R.gg(i,s,o,n,r[f+8],20,1163531501),n=R.gg(n,i,s,o,r[f+13],5,-1444681467),o=R.gg(o,n,i,s,r[f+2],9,-51403784),s=R.gg(s,o,n,i,r[f+7],14,1735328473),i=R.gg(i,s,o,n,r[f+12],20,-1926607734),n=R.hh(n,i,s,o,r[f+5],4,-378558),o=R.hh(o,n,i,s,r[f+8],11,-2022574463),s=R.hh(s,o,n,i,r[f+11],16,1839030562),i=R.hh(i,s,o,n,r[f+14],23,-35309556),n=R.hh(n,i,s,o,r[f+1],4,-1530992060),o=R.hh(o,n,i,s,r[f+4],11,1272893353),s=R.hh(s,o,n,i,r[f+7],16,-155497632),i=R.hh(i,s,o,n,r[f+10],23,-1094730640),n=R.hh(n,i,s,o,r[f+13],4,681279174),o=R.hh(o,n,i,s,r[f],11,-358537222),s=R.hh(s,o,n,i,r[f+3],16,-722521979),i=R.hh(i,s,o,n,r[f+6],23,76029189),n=R.hh(n,i,s,o,r[f+9],4,-640364487),o=R.hh(o,n,i,s,r[f+12],11,-421815835),s=R.hh(s,o,n,i,r[f+15],16,530742520),i=R.hh(i,s,o,n,r[f+2],23,-995338651),n=R.ii(n,i,s,o,r[f],6,-198630844),o=R.ii(o,n,i,s,r[f+7],10,1126891415),s=R.ii(s,o,n,i,r[f+14],15,-1416354905),i=R.ii(i,s,o,n,r[f+5],21,-57434055),n=R.ii(n,i,s,o,r[f+12],6,1700485571),o=R.ii(o,n,i,s,r[f+3],10,-1894986606),s=R.ii(s,o,n,i,r[f+10],15,-1051523),i=R.ii(i,s,o,n,r[f+1],21,-2054922799),n=R.ii(n,i,s,o,r[f+8],6,1873313359),o=R.ii(o,n,i,s,r[f+15],10,-30611744),s=R.ii(s,o,n,i,r[f+6],15,-1560198380),i=R.ii(i,s,o,n,r[f+13],21,1309151649),n=R.ii(n,i,s,o,r[f+4],6,-145523070),o=R.ii(o,n,i,s,r[f+11],10,-1120210379),s=R.ii(s,o,n,i,r[f+2],15,718787259),i=R.ii(i,s,o,n,r[f+9],21,-343485551),n=R.ad(n,a),i=R.ad(i,u),s=R.ad(s,l),o=R.ad(o,g);return R.rh(n)+R.rh(i)+R.rh(s)+R.rh(o)}static rh(t){let r="";for(let n=0;n<=3;n++)r+=R.alphabet.charAt(t>>n*8+4&15)+R.alphabet.charAt(t>>n*8&15);return r}static ad(t,r){let n=(t&65535)+(r&65535);return (t>>16)+(r>>16)+(n>>16)<<16|n&65535}static rl(t,r){return t<<r|t>>>32-r}static cm(t,r,n,i,s,o){return R.ad(R.rl(R.ad(R.ad(r,t),R.ad(i,o)),s),n)}static ff(t,r,n,i,s,o,a){return R.cm(r&n|~r&i,t,r,s,o,a)}static gg(t,r,n,i,s,o,a){return R.cm(r&i|n&~i,t,r,s,o,a)}static hh(t,r,n,i,s,o,a){return R.cm(r^n^i,t,r,s,o,a)}static ii(t,r,n,i,s,o,a){return R.cm(n^(r|~i),t,r,s,o,a)}static sb(t){let r,n=(t.length+8>>6)+1,i=new Array(n*16);for(r=0;r<n*16;r++)i[r]=0;for(r=0;r<t.length;r++)i[r>>2]|=t.charCodeAt(r)<<r%4*8;return i[r>>2]|=128<<r%4*8,i[n*16-2]=t.length*8,i}};R.alphabet="0123456789abcdef";var G=R;function Mr(e){if(e===0)return ye[0];let t="";for(;e>0;)t=ye[e%62]+t,e=Math.floor(e/62);return t}function se(e){return e.split("").reverse().reduce((t,r,n)=>t+ye.indexOf(r)*62**n,0)}function Re(e=6){let t="",r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n=r.length,i=0;for(;i<e;)t+=r.charAt(Math.floor(Math.random()*n)),i+=1;return t}function Vt(){return typeof window>"u"||!!window?._runningInNodeJS}function Y(){return !Vt()&&typeof document<"u"&&typeof document.createElement=="function"}function dt(e){let t;try{t=JSON.stringify(e);}catch{throw new c("Invalid data type.",{code:"INVALID_REQUEST"})}if(new Blob([t]).size>Ys)throw new c("Data should not exceed 2MB",{code:"INVALID_REQUEST"})}function xr(e){return e===""||e==="on"||e==="true"}function Dr(e){return e==="false"}function Cr(e,t,r){t.name&&r(e,t.name,t.value);}var ft=Y(),eo=typeof SubmitEvent<"u",to=typeof HTMLFormElement<"u";function j(e,t,r){let n={},i=[];function s(u,l,g){if(t?.ignoreEmpty&&g==="")return;if(t?.nullIfEmpty&&g===""&&(g=null),typeof r=="function"){let p=r(l,g);p!==void 0&&(g=p);}let f=l.split("[").map(p=>{let m=p.replace("]",""),y=Number(m);return !isNaN(y)&&!m.includes(".")?m=y:(m[0]==='"'&&m[m.length-1]==='"'||m[0]==="'"&&m[m.length-1]==="'")&&(m=m.replace(/"/g,"").replace(/'/g,"")),m}),d=u;if(typeof f[0]=="number")throw new c("Form key cannot start with an array index.",{code:"INVALID_REQUEST"});for(let p=0;p<f.length;p++){let m=f[p];p<f.length-1?(d[m]===void 0&&(typeof f[p+1]=="number"?d[m]=[]:d[m]={}),d=d[m]):d[m]===void 0?d[m]=g:Array.isArray(d[m])?d[m].push(g):d[m]=[d[m],g];}}function o(u,l,g){if(g instanceof File)u.push({name:l,file:g});else if(g instanceof FileList&&g&&g.length>0)for(let f=0;f<=g.length-1;f++){let d=g.item(f);d&&u.push({name:l,file:d});}}let a=u=>{u.name&&(u.type==="number"?u.value&&s(n,u.name,Number(u.value)):u.type==="checkbox"||u.type==="radio"?u.checked?u.type==="checkbox"&&u.value===""||xr(u.value)?s(n,u.name,true):Dr(u.value)?s(n,u.name,false):u.value&&s(n,u.name,u.value):u.type==="checkbox"&&(xr(u.value)?s(n,u.name,false):Dr(u.value)&&s(n,u.name,true)):u.type==="file"?u.files&&u.files.length>0&&o(i,u.name,u.files):s(n,u.name,u.value));};if(ft&&(e instanceof HTMLInputElement||e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement))return a(e),dt(n),{data:n,files:i};if(ft&&e instanceof FormData){for(let u of e.entries()){let l=u[0],g=u[1];if(g instanceof File||g instanceof FileList)o(i,l,g);else if(g instanceof Blob){let f=g;if(f.type==="application/json")try{let d=JSON.parse(f.text());s(n,l,d);}catch{s(n,l,f);}}else s(n,l,g);}return dt(n),{data:n,files:i}}if(ft&&eo&&e instanceof SubmitEvent&&(e=e.target),ft&&to&&e instanceof HTMLFormElement){let u=e.querySelectorAll("input"),l=e.querySelectorAll("select"),g=e.querySelectorAll("textarea");for(let f=0;f<l.length;f++)Cr(n,l[f],s);for(let f=0;f<g.length;f++)Cr(n,g[f],s);for(let f=0;f<u.length;f++)a(u[f]);return dt(n),{data:n,files:i}}return dt(e),{data:e,files:i}}function $e(e){let t={};for(let r in e){let n=e[r];if(!Xs.includes(r))if(Nr[r])t[Nr[r]]=n;else if(r.includes("custom:"))t[r.replace("custom:","")]=n;else if(r==="address"){let i=n;if(i&&typeof i=="object"&&Object.keys(i).length){if(i?.formatted)try{t[r]=JSON.parse(i.formatted);}catch{t[r]=i.formatted;}}else t[r]=i;}else t[r]=n;}for(let r of ["address_public","birthdate_public","email_public","gender_public","phone_number_public","access_group"])r.includes("_public")?t.hasOwnProperty(r.split("_")[0])?t[r]=t.hasOwnProperty(r)?!!Number(t[r]):false:delete t[r]:t[r]=t.hasOwnProperty(r)?Number(t[r]):0;for(let r of ["email","phone_number"])t.hasOwnProperty(r)?t[r+"_verified"]=t[r+"_verified"]===true:delete t[r+"_verified"];return t}function $t(e){if(e=co(e),e.split("-").length===7){let t=e.split("-"),r,n;try{r=Or[Lr.indexOf(t[1][0])],n=t.slice(2).join("-");}catch{throw new Error("INVALID_PARAMETER: Service ID is invalid: "+e)}if(!r)throw new Error("INVALID_PARAMETER: Service ID is invalid: "+e);return {service:r+t[0]+t[1].slice(1),owner:n}}return {service:e,owner:""}}function jt(e,t){let r=Or.indexOf(e.slice(0,4)),n=Lr[r],s=`${e.slice(4,-4)}-${n}${e.slice(-4)}-${t}`;return lo(s)}function ro(e){let t=0n;for(let r of e){let n=ye.indexOf(r);if(n<0)throw new Error(`INVALID_PARAMETER: Invalid base62 character: ${r}`);t=t*Ft+BigInt(n);}return t}function no(e,t=1){if(e<0n)throw new Error("INVALID_PARAMETER: Negative values are not supported.");if(e===0n)return "0".repeat(Math.max(1,t));let r="",n=e;for(;n>0n;){let i=Number(n%Ft);r=ye[i]+r,n/=Ft;}return r.length<t&&(r="0".repeat(t-r.length)+r),r}function io(e){if(e===0n)return Uint8Array.from([0]);let t=[],r=e;for(;r>0n;)t.push(Number(r&0xffn)),r>>=8n;return t.reverse(),Uint8Array.from(t)}function so(e){let t=0n;for(let r of e)t=(t<<8n)+BigInt(r);return t}function oo(e){let t=String(e).replace(/-/g,"");if(!/^[0-9a-fA-F]{32}$/.test(t))throw new Error("INVALID_PARAMETER: Invalid UUID format.");let r=new Uint8Array(16);for(let n=0;n<16;n++)r[n]=parseInt(t.slice(n*2,n*2+2),16);return r}function ao(e){let t=Array.from(qt(e),r=>r.toString(16).padStart(2,"0")).join("");return [t.slice(0,8),t.slice(8,12),t.slice(12,16),t.slice(16,20),t.slice(20)].join("-")}function lo(e){let t=String(e);if(t.split("-").length===2)return t;let r=t.match(/^([0-9A-Za-z]+)-([0-9A-Za-z]+)-([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/);if(!r)throw new Error("INVALID_PARAMETER: Input must match <base62>-<base62>-<uuid>.");let[,n,i,s]=r;if(n.length<2)throw new Error("INVALID_PARAMETER: The first part must contain at least 2 characters.");if(i.length>=ye.length)throw new Error("INVALID_PARAMETER: The middle section is too long to encode.");let o=n.slice(0,2),a=n.slice(2),u=i+o,l=ye[i.length]+a+u,g=oo(s),f=no(so(g));return `${l}-${f}`}function co(e){let t=String(e);if(t.split("-").length!==2)return t;let r=t.split("-");if(r.length!==2||!r[0]||!r[1])throw new Error("INVALID_PARAMETER: Corrupt compressed token: "+t);let[n,i]=r,s=ye.indexOf(n[0]);if(s<0)throw new Error("INVALID_PARAMETER: Corrupt compressed token: "+t);let o=n.slice(1),a=s+2;if(o.length<a)throw new Error("INVALID_PARAMETER: Corrupt compressed token: "+t);let u=o.slice(0,o.length-a),l=o.slice(o.length-a),g=l.slice(s),f=l.slice(0,s),d=g+u;if(!/^[0-9A-Za-z]+$/.test(d)||!/^[0-9A-Za-z]+$/.test(f))throw new Error("INVALID_PARAMETER: Corrupt compressed token: "+t);let p=ro(i),m=io(p);if(m.length>16)throw new Error("INVALID_PARAMETER: Corrupt compressed token: "+t);let y=new Uint8Array(16);y.set(m,16-m.length);let _=ao(y);return `${d}-${f}-${_}`}function je(e){if(typeof TextDecoder<"u")return new TextDecoder().decode(e);let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return decodeURIComponent(escape(t))}function Bt(...e){let t=0;for(let i of e)t+=i.length;let r=new Uint8Array(t),n=0;for(let i of e)r.set(i,n),n+=i.length;return r}function fo(e,t="User ID"){let r=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;if(e){if(typeof e!="string")throw new c(`${t} should be type: string.`,{code:"INVALID_PARAMETER"});if(!e.match(r))throw new c(`${t} is invalid.`,{code:"INVALID_PARAMETER"})}else throw new c(`${t} is empty.`,{code:"INVALID_PARAMETER"});return e}function go(e){if(e&&(typeof e!="string"||e.charAt(0)!=="+"||isNaN(Number(e.substring(1)))))throw new c('"phone_number" is invalid. The format should be "+00123456789". Type: string.',{code:"INVALID_PARAMETER"});return e||""}function po(e){if(e){if(typeof e!="string")throw new c('"birthdate" is invalid. The format should be "yyyy-mm-dd". Type: string.',{code:"INVALID_PARAMETER"});{let t=new RegExp(/([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))/);if(e.length!==10||e.split("-").length!==3||!t.test(e))throw new c('"birthdate" is invalid. The format should be "yyyy-mm-dd". Type: string.',{code:"INVALID_PARAMETER"})}}return e||""}function ho(e){if(e){if(typeof e!="string")throw new c('"password" should be type: string.',{code:"INVALID_PARAMETER"});if(e.length<6)throw new c('"password" should be at least 6 characters.',{code:"INVALID_PARAMETER"});if(e.length>60)throw new c('"password" can be up to 60 characters max.',{code:"INVALID_PARAMETER"})}else throw new c('"password" is required.',{code:"INVALID_PARAMETER"});return e}function mo(e,t="email"){if(e){if(typeof e!="string")throw new c(`"${t}"should be type: string.`,{code:"INVALID_PARAMETER"});if(e.length<5)throw new c(`"${t}" should be at least 5 characters.`,{code:"INVALID_PARAMETER"});if(/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/.test(e)&&(e=e.trim(),e.split("@")[1].split(".").length>=2))return e.toLowerCase()}else throw new c(`"${t}" is required.`,{code:"INVALID_PARAMETER"});throw new c(`"${e}" is an invalid email.`,{code:"INVALID_PARAMETER"})}function yo(e){let t=typeof window<"u",r=(()=>{let i=t&&window.location.origin||null;return i&&i.slice(-1)==="/"&&(i=i.slice(0,-1)),i})(),n=i=>{if(typeof i=="string"){if(i==="*")return "*";{let s=i.trim();if(s[0]==="/"&&r){if(r.slice(0,5)==="file:")throw new c(`"${i}" is an invalid url. Relative URL does not work on local file system. Use full URL string.`,{code:"INVALID_PARAMETER"});s=r+s;}else if(s[0]==="."&&r){if(r.slice(0,5)==="file:")throw new c(`"${i}" is an invalid url. Relative URL does not work on local file system. Use full URL string.`,{code:"INVALID_PARAMETER"});let a=t?window.location.href.split("?")[0]:"";a.slice(-1)!=="/"&&(a+="/"),s=a+s.slice(1);}let o;try{o=new URL(s);}catch{throw new c(`"${i}" is an invalid url.`,{code:"INVALID_PARAMETER"})}if(o.protocol)return o.href}}throw new c(`"${i}" is an invalid url.`,{code:"INVALID_PARAMETER"})};return Array.isArray(e)?e.map(i=>n(i)):n(e)}var bo=/^[a-z0-9]{2,20}$/,_o=/[a-z]/,wo=/^[0-9]+e[0-9]+$/,Eo=["tp","admin","public","authorized","newsletter","forward","all","true","false","null"];function Ao(e,t){if(e==null){if(t?.allowNull)return null;throw new c('"group" is required.',{code:"INVALID_PARAMETER"})}if(!t?.nameOnly){if(e==="public")return 0;if(e==="authorized")return 1;if(typeof e=="number"){if(!Number.isInteger(e)||e<0||e>99)throw new c('"group" should be an integer between 0 and 99.',{code:"INVALID_PARAMETER"});return e}}if(typeof e!="string"||!bo.test(e)||!_o.test(e)||wo.test(e)||Eo.includes(e))throw new c("Newsletter group name must be 2-20 lowercase alphanumeric characters, contain a letter, and not be a reserved name.",{code:"INVALID_PARAMETER"});return e}function Ro(e,t,r=[],n){let i=j(e,n),s=i.data;t.service="string",t.owner="string";let o={};for(let a in t)if(s&&typeof s=="object"&&!Array.isArray(s)&&s.hasOwnProperty(a))if(typeof s[a]=="function")o[a]=s[a];else try{o[a]=JSON.parse(JSON.stringify(s[a]));}catch{o[a]=s[a];}n?.precall&&n.precall({data:o,files:i?.files||[]});try{return uo(o,t,r)}catch(a){throw new c(a.message,{code:"INVALID_PARAMETER"})}}var h={UserId:fo,PhoneNumber:go,Birthdate:po,Password:ho,Email:mo,Url:yo,newsletterGroup:Ao,Params:Ro};var X="skapi.enc.v1",Vr=6e5,Be=12,gt=null,ve=null;function $r(){return new c("Encryption requires Web Crypto, which needs a secure context (https, or localhost) in the browser, or Node 18 or newer. A page served over plain http has crypto.getRandomValues but crypto.subtle is undefined.",{code:"NOT_SUPPORTED"})}function jr(){if(ve)return ve;let e=typeof globalThis<"u"?globalThis:void 0;if(e?.crypto?.subtle&&typeof e.crypto.getRandomValues=="function")return ve=e.crypto,ve;try{let t=typeof globalThis<"u"?globalThis:void 0,r=null;if(t?.process&&typeof t.process.getBuiltinModule=="function"&&(r=t.process.getBuiltinModule("crypto")),!r&&typeof ke=="function"&&(r=ke("crypto")),r?.webcrypto?.subtle)return ve=r.webcrypto,ve}catch{}throw $r()}function re(){if(gt)return gt;let e=jr();if(!e.subtle)throw $r();return gt=e.subtle,gt}function Ht(){try{return re(),!0}catch{return false}}function Z(e){let t=jr(),r=new Uint8Array(e),n=65536;for(let i=0;i<e;i+=n)t.getRandomValues(r.subarray(i,Math.min(i+n,e)));return r}function q(e){let t=qt(e),r;if(typeof Buffer<"u"&&typeof Buffer.from=="function")r=Buffer.from(t).toString("base64");else if(typeof btoa=="function"){let n="";for(let s=0;s<t.length;s+=32768)n+=String.fromCharCode.apply(null,Array.from(t.subarray(s,s+32768)));r=btoa(n);}else throw new c("No base64 encoder available in this environment.",{code:"NOT_SUPPORTED"});return r.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function $(e){if(typeof e!="string")throw new c("Expected a base64url string.",{code:"INVALID_PARAMETER"});let t=e.replace(/-/g,"+").replace(/_/g,"/"),r=t.length%4;if(r===2)t+="==";else if(r===3)t+="=";else if(r===1)throw new c("Malformed base64url string.",{code:"INVALID_PARAMETER"});if(typeof Buffer<"u"&&typeof Buffer.from=="function"){let n=Buffer.from(t,"base64");return new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}if(typeof atob=="function"){let n=atob(t),i=new Uint8Array(n.length);for(let s=0;s<n.length;s++)i[s]=n.charCodeAt(s);return i}throw new c("No base64 decoder available in this environment.",{code:"NOT_SUPPORTED"})}async function pt(e){let t=await re().digest("SHA-256",e);return new Uint8Array(t)}async function Ge(e,t,r,n){let i=re(),s=await i.importKey("raw",e,"HKDF",false,["deriveBits"]),o=await i.deriveBits({name:"HKDF",hash:"SHA-256",salt:t,info:r},s,n*8);return new Uint8Array(o)}async function Ue(e,t,r,n){let i=re(),s=K(e.normalize("NFC")),o=await i.importKey("raw",s,"PBKDF2",false,["deriveBits"]),a=new Uint8Array(await i.deriveBits({name:"PBKDF2",salt:t,iterations:r,hash:"SHA-256"},o,256)),u=await Ge(a,t,n,32);F(a),F(s);let l=await oe(u);return F(u),l}async function oe(e){return re().importKey("raw",e,{name:"AES-GCM"},false,["encrypt","decrypt"])}async function Br(){let e=Z(32),t=await oe(e);return {bytes:e,key:t}}async function ne(e,t,r){let n=Z(Be),i=await re().encrypt({name:"AES-GCM",iv:n,additionalData:r,tagLength:128},e,t);return {iv:n,ct:new Uint8Array(i)}}async function ae(e,t,r,n){let i=await re().decrypt({name:"AES-GCM",iv:t,additionalData:n,tagLength:128},e,r);return new Uint8Array(i)}var ht={name:"ECDH",namedCurve:"P-256"};async function Kr(){let e=re(),t=await e.generateKey(ht,true,["deriveBits"]),r=new Uint8Array(await e.exportKey("raw",t.publicKey)),n=new Uint8Array(await e.exportKey("pkcs8",t.privateKey)),i=await Gt(n);return {pubRaw:r,pkcs8:n,priv:i}}async function Gt(e){return re().importKey("pkcs8",e,ht,false,["deriveBits"])}async function Hr(e){if(e.length!==65||e[0]!==4)throw new c("Malformed public key: expected a 65 byte uncompressed P-256 point.",{code:"INVALID_PARAMETER"});return re().importKey("raw",e,ht,false,[])}async function Wt(e){return q(await pt(e))}async function Gr(e,t,r,n){let i=re(),s=await Hr(e),o=await i.generateKey(ht,true,["deriveBits"]),a=new Uint8Array(await i.deriveBits({name:"ECDH",public:s},o.privateKey,256)),u=await Ge(a,new Uint8Array(32),r,32);F(a);let l=await oe(u);F(u);let{iv:g,ct:f}=await ne(l,t,n);return {epk:new Uint8Array(await i.exportKey("raw",o.publicKey)),iv:g,ct:f}}async function Wr(e,t,r,n,i,s){let o=re(),a=await Hr(t),u=new Uint8Array(await o.deriveBits({name:"ECDH",public:a},e,256)),l=await Ge(u,new Uint8Array(32),i,32);F(u);let g=await oe(l);return F(l),ae(g,r,n,s)}function F(e){e&&e.length&&e.fill(0);}function Io(e,t){if(e.length!==t.length)return false;let r=0;for(let n=0;n<e.length;n++)r|=e[n]^t[n];return r===0}function Qt(e){return K(JSON.stringify(e))}function We(e,t,r){return Bt(e,new Uint8Array([0]),K(t),new Uint8Array([0]),K(r))}var Ie="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Ke=16,Fr=26,qr=28;function Qr(e){let t=2166136261;for(let r=0;r<e.length;r++)t^=e[r],t=t*16777619>>>0;return t&1023}function zr(e){if(e.length!==Ke)throw new c(`A recovery code needs exactly ${Ke} bytes.`,{code:"INVALID_PARAMETER"});let t="",r=0,n=0;for(let s=0;s<e.length;s++)for(r=r<<8|e[s],n+=8;n>=5;)n-=5,t+=Ie[r>>n&31];n>0&&(t+=Ie[r<<5-n&31]);let i=Qr(e);return t+=Ie[i>>5&31]+Ie[i&31],(t.match(/.{1,4}/g)||[]).join("-")}function Jr(e){if(typeof e!="string")throw new c("Recovery code should be a string.",{code:"INVALID_PARAMETER"});let t=e.toUpperCase().replace(/[\s\-_]/g,"").replace(/O/g,"0").replace(/[IL]/g,"1");if(t.length!==qr)throw new c(`That does not look like a recovery code: expected ${qr} characters, got ${t.length}.`,{code:"ENCRYPTION_BAD_RECOVERY_CODE"});let r=t.slice(0,Fr),n=t.slice(Fr),i=0,s=0,o=[];for(let l=0;l<r.length;l++){let g=Ie.indexOf(r[l]);if(g<0)throw new c(`That does not look like a recovery code: "${r[l]}" is not a valid character.`,{code:"ENCRYPTION_BAD_RECOVERY_CODE"});i=i<<5|g,s+=5,s>=8&&(s-=8,o.push(i>>s&255));}let a=new Uint8Array(o.slice(0,Ke)),u=Qr(a);if(n!==Ie[u>>5&31]+Ie[u&31])throw new c("That recovery code has a typo in it: the check characters do not match.",{code:"ENCRYPTION_BAD_RECOVERY_CODE"});return a}async function zt(e,t,r){let n=await Ge(e,t,r,32),i=await oe(n);return F(n),i}var Kt=[83,75,69,78,67,70],Yr=2,He=56,Xr=16,To=4*1024*1024;function Jt(e){if(!e||e.length<He)return false;for(let t=0;t<Kt.length;t++)if(e[t]!==Kt[t])return false;return true}function Te(e,t,r){e[t]=r>>>24&255,e[t+1]=r>>>16&255,e[t+2]=r>>>8&255,e[t+3]=r&255;}function Ne(e,t){return (e[t]<<24>>>0)+(e[t+1]<<16)+(e[t+2]<<8)+e[t+3]}function Po(e,t,r){let n=Math.floor(r/4294967296);Te(e,t,n),Te(e,t+4,r>>>0);}function So(e,t){return Ne(e,t)*4294967296+Ne(e,t+4)}async function Zr(e,t,r,n,i,s){let o=K(`${X}|binfile|${r}|${n}|${i}|${s}`),a=await Ge(e,t,o,32),u=await oe(a);return F(a),u}async function en(e){return (await pt(Bt(K(`${X}|dekid`),e))).subarray(0,8)}function tn(e,t,r){return Qt([`${X}|binchunk`,q(e),t,r])}function ko(e,t,r,n,i,s){let o=new Uint8Array(He+s.length);return o.set(Kt,0),o[6]=Yr,o[7]=s.length?1:0,Te(o,8,e),Te(o,12,t),o.set(r,16),Po(o,32,n),o.set(i,40),Te(o,48,s.length),Te(o,52,0),s.length&&o.set(s,He),o}async function rn(e,t,r,n,i=To){let s=Z(Xr),o=await Zr(e,s,r.service,r.owner,r.recordOwner,r.recordId),a=await en(e),u=n?K(JSON.stringify(n)):new Uint8Array(0);if(u.length>4096)throw new c("Encrypted file metadata is too large.",{code:"INVALID_PARAMETER"});let l=t.length===0?1:Math.ceil(t.length/i),g=ko(i,l,s,t.length,a,u),f=await pt(g),d=[],p=g.length;for(let _=0;_<l;_++){let w=t.subarray(_*i,Math.min((_+1)*i,t.length)),b=await ne(o,w,tn(f,_,l));d.push(b),p+=4+b.iv.length+b.ct.length;}let m=new Uint8Array(p);m.set(g,0);let y=g.length;for(let _ of d)Te(m,y,_.iv.length+_.ct.length),y+=4,m.set(_.iv,y),y+=_.iv.length,m.set(_.ct,y),y+=_.ct.length;return m}function vo(e){if(!Jt(e))throw new c("This file is not an encrypted skapi file.",{code:"INVALID_PARAMETER"});let t=Ne(e,48),r=He+t;if(e.length<r)throw new c("Encrypted file header is truncated.",{code:"INVALID_REQUEST"});let n=null;return t&&(n=JSON.parse(je(e.subarray(He,r)))),{version:e[6],chunkBytes:Ne(e,8),count:Ne(e,12),fileId:e.subarray(16,16+Xr),plainLen:So(e,32),dekId:e.subarray(40,48),meta:n,headerLen:r}}async function nn(e,t,r){let n=vo(t);if(n.version!==Yr)throw new c(`This file was encrypted by a different version of the SDK (container v${n.version}).`,{code:"NOT_SUPPORTED"});if(!n.count||!n.chunkBytes)throw new c("Encrypted file header is malformed.",{code:"INVALID_PARAMETER"});let i=await en(e);if(!Io(i,n.dekId))throw new c("This file was encrypted under a previous data key for this record, so it can no longer be opened. It was most likely left behind by an interrupted access change.",{code:"ENCRYPTION_FILE_STALE_KEY"});let s=await Zr(e,n.fileId,r.service,r.owner,r.recordOwner,r.recordId),o=await pt(t.subarray(0,n.headerLen)),a=[],u=n.headerLen,l=0;for(let d=0;d<n.count;d++){if(u+4>t.length)throw new c("Encrypted file is truncated.",{code:"INVALID_REQUEST"});let p=Ne(t,u);if(u+=4,p<Be+16||u+p>t.length)throw new c("Encrypted file is truncated.",{code:"INVALID_REQUEST"});let m=await ae(s,t.subarray(u,u+Be),t.subarray(u+Be,u+p),tn(o,d,n.count));u+=p,a.push(m),l+=m.length;}let g=new Uint8Array(l),f=0;for(let d of a)g.set(d,f),f+=d.length;return {bytes:g,meta:n.meta}}var No="__skapi__keyring",Qe="__skapi_enc__",on=1,Uo="skapi-enc",Ee="keys",Xt=new WeakMap;function an(e){if(!e)return null;if(e===true&&(e={}),typeof e!="object")throw new c('"options.encryption" should be a boolean or an object.',{code:"INVALID_PARAMETER"});let t=typeof e.iterations=="number"?e.iterations:Vr;if(t<1e5)throw new c('"encryption.iterations" must be at least 100000.',{code:"INVALID_PARAMETER"});let r=e.trustPolicy==="strict"?"strict":"tofu";return {enabled:true,iterations:t,trustPolicy:r,persistDevice:e.persistDevice!==false,minPasswordLength:typeof e.minPasswordLength=="number"?e.minPasswordLength:0,withheld:e.withheld==="sentinel"?"sentinel":"null",recovery:e.recovery==="none"?"none":"code",table:typeof e.table=="string"&&e.table?e.table:No}}function O(){return Xt.get(this)||null}function ln(e){if(!e){Xt.delete(this);return}Xt.set(this,{cfg:e,status:"locked",reason:"NO_SESSION_KEY",user_id:"",scope:"",mk:null,ikPriv:null,pubRaw:null,fpr:"",keyringRecordId:"",pins:{},dek:new Map,roll:new Set,passthrough:new Map,rawRead:false,ready:null,unlocking:false,pendingRecoveryCode:"",peerPub:new Map,peerInflight:new Map});}function Zt(){let e=O.call(this);if(e){e.user_id&&ur.call(this,e).catch(()=>{}),e.ready=null,e.unlocking=false,e.pendingRecoveryCode="";for(let[,t]of e.dek)F(t.bytes);e.dek.clear(),e.roll.clear(),e.passthrough.clear(),e.peerPub.clear(),e.peerInflight.clear(),e.pins={},e.mk=null,e.ikPriv=null,e.pubRaw=null,e.fpr="",e.keyringRecordId="",e.user_id="",e.status="locked",e.reason="NO_SESSION_KEY";}}function cn(){let e=O.call(this);return e?{status:e.status,reason:e.status==="unlocked"?void 0:e.reason,user_id:e.user_id||void 0,fingerprint:e.fpr||void 0}:{status:"disabled"}}function un(e,t){return typeof t=="string"&&t===e.cfg.table}function xe(){return `${this.service}/${this.owner}`}function er(e,t,r,n){let[i,s]=e.split("/");return Qt([X,i,s,t,r,n])}function dn(e,t,r,n,i){let[s,o]=e.split("/");return K(`${X}|dekwrap|${s}|${o}|${t}|${r}|${n}|${i}`)}function tr(e){return e.anch==="uid"?e.uid:e.anch==="rid"?e.rid:""}function yt(e){return !!e&&typeof e=="object"&&!Array.isArray(e)&&typeof e[Qe]=="number"&&typeof e.ct=="string"&&typeof e.iv=="string"&&typeof e.own=="string"&&typeof e.anch=="string"&&!!e.k&&typeof e.k=="object"&&!Array.isArray(e.k)}var fn="__skapi_no_access__";function ee(e,t,r){if(e.withheld!=="sentinel")return null;let n={[fn]:true,reason:t};return r&&(n.recipients=r),Object.freeze(n)}function rr(e){return !!e&&typeof e=="object"&&e[fn]===true}var xo=256*1024,Ye="__skenc_ct__",gn="payload.bin",Do=`/${Ye}/${gn}`;function nr(e,t){return e===Ye&&t===gn}async function Co(e,t,r){let n=t?.table,i=typeof n=="string"?n:n?.name;if(n&&(typeof n=="string"||n.access_group!==void 0))return {group:typeof n=="string"?0:sn(n.access_group),table:i,record:null};if(!r)return {group:n?.access_group!==void 0?sn(n.access_group):0,table:i,record:null};let s=e.dek.get(r);if(s)return {group:s.access_group,table:i,record:null};let o=await we.call(this,r);if(!o)throw new c(`Record "${r}" not found.`,{code:"NOT_EXISTS"});return {group:o.table.access_group,table:o.table.name,record:o}}function Lo(e){return this.getFile(e,{dataType:"blob"})}async function we(e){let t=/^[a-zA-Z0-9]+$/.test(e)?{record_id:e}:{unique_id:e};return (await this.getRecords(t,{limit:1}))?.list?.[0]||null}function sn(e){return e==="private"||e==="*"||e==="**"?"private":e==="public"?0:e==="authorized"?1:e==="admin"?99:typeof e=="number"?e:0}function Yt(e,t,r){let n=this.user?.user_id;if(!(!e||!e.user_id||!n||e.user_id===n))throw new c(`Record "${t}" belongs to another user (${e.user_id}), so ${r} would either seal it under the wrong key or strand its contents. Encryption only operates on records you own, no matter what access level you hold.`,{code:"ENCRYPTION_NOT_RECORD_OWNER"})}async function ir(e,t,r){let n=O.call(this);if(!n)return {send:e,plain:e,encrypted:false,omit:false};let i=t?.record_id||"",s=i,o=t?.unique_id||"";if(i&&n.passthrough.has(i)){let M=n.passthrough.get(i);return n.passthrough.delete(i),{send:M,plain:e,encrypted:true,omit:false}}let{group:a,table:u,record:l}=await Co.call(this,n,t,s);if(a!=="private"){let M=true;if(!r&&i){let Q=l||await we.call(this,i);if(Q&&Q.encrypted){if(Yt.call(this,Q,i,"making it non-private"),Q.encrypted.status==="failed")throw new c(`Cannot make record "${i}" non-private: its current contents could not be decrypted (${Q.encrypted.reason}), so they cannot be written back in the clear. Unlock encryption, or supply the record's data with the access group change.`,{code:"ENCRYPTION_LOCKED"});let Ve=!!Q.bin&&Object.keys(Q.bin).some(ct=>(Q.bin[ct]||[]).some(kr=>kr&&kr.encrypted));if(!Ve&&s){let ct=n.dek.get(s);ct&&(F(ct.bytes),n.dek.delete(s));}return {send:Q.data,plain:Q.data,encrypted:false,omit:false,files:Ve?"decrypt":void 0}}}let J=l;i&&!J&&(J=await we.call(this,i).catch(()=>null)),J&&J.encrypted&&Yt.call(this,J,i,"making it non-private");let lt=!!J&&!!J.bin&&Object.keys(J.bin).some(Q=>(J.bin[Q]||[]).some(Ve=>Ve&&Ve.encrypted));if(lt&&(M=false),M&&s){let Q=n.dek.get(s);Q&&(F(Q.bytes),n.dek.delete(s));}return {send:e,plain:e,encrypted:false,omit:!r,files:lt?"decrypt":void 0}}if(un(n,u))return {send:e,plain:e,encrypted:false,omit:false};if(n.ready&&!n.unlocking)try{await n.ready;}catch{}if(!r)return {send:e,plain:e,encrypted:false,omit:true};if(rr.call(this,e))throw new c("This record's data could not be decrypted by this session, so it cannot be written back. Writing it would replace the record with the placeholder.",{code:"ENCRYPTION_CANNOT_REWRITE_WITHHELD"});if(n.status!=="unlocked"||!n.mk)throw new c("Encryption is enabled but locked, so this private record cannot be written. Call unlockEncryption({ password }) first, or the user must log in with their password.",{code:"ENCRYPTION_LOCKED"});if(e&&typeof e=="object"&&!Array.isArray(e)&&Object.prototype.hasOwnProperty.call(e,Qe))throw new c(`"${Qe}" is a reserved key in record data.`,{code:"INVALID_PARAMETER"});if(t?.service&&t.service!==this.service||t?.owner&&t.owner!==this.owner)throw new c("Encrypted records cannot be written to another project. The encryption key is derived per project, so a record written under one service and read under another could never be decrypted. Construct a separate Skapi instance for that project.",{code:"INVALID_REQUEST"});let g=this.user?.user_id;if(!g)throw new c("User login is required to write an encrypted record.",{code:"INVALID_REQUEST"});let f=xe.call(this),d=false;if(i&&n.roll.has(i)){d=true,n.roll.delete(i);let M=n.dek.get(i);n.dek.delete(i),M&&F(M.bytes);}let p=l;i&&!p&&!n.dek.has(i)&&(p=await we.call(this,i).catch(()=>null)),p&&Yt.call(this,p,i,"making it private");let m=!!p&&!p.encrypted&&!!p.bin&&Object.keys(p.bin).some(M=>(p.bin[M]||[]).some(J=>J&&!J.encrypted)),y=null;if(i&&!d&&(y=n.dek.get(i)||null,!y)){let M=p||l||await we.call(this,i);if(M&&(s=M.record_id||i,y=n.dek.get(s)||null,!o&&M.unique_id&&(o=M.unique_id),!y&&M.encrypted?.status==="failed"))throw new c(`Cannot update encrypted record "${i}": its current contents could not be decrypted (${M.encrypted.reason}), so its existing key wraps cannot be preserved. Updating anyway would revoke everyone it is shared with.`,{code:"ENCRYPTION_LOCKED"})}s===i&&y&&y.rid&&(s=y.rid),!o&&y&&y.anch==="uid"&&y.uid&&(o=y.uid);let _,w,b;if(y){if(y.own&&y.own!==g)throw new c(`Record "${i}" belongs to another user (${y.own}). Encryption only operates on records you own.`,{code:"ENCRYPTION_NOT_RECORD_OWNER"});_=y.bytes,w=y.key,b=Object.assign({},y.recipients);}else {let M=await Br();_=M.bytes,w=M.key,b={};}let E=o?"uid":s?"rid":"new",k=E==="uid"?o:E==="rid"?s:"",A=er(f,g,E,k),D=We(A,g,"mk"),x=await ne(n.mk,_,D);b[g]={t:"mk",iv:q(x.iv),ct:q(x.ct)},y&&(y.anch!==E||tr(y)!==k)&&(b=await Oo.call(this,n,_,b,f,g,E,k,A));let C=K(JSON.stringify(e===void 0?null:e)),v=await ne(w,C,A);F(C);let U={[Qe]:on,enc:"A256GCM",kw:"ECDH-ES+A256GCM",anch:E,uid:o,rid:s,own:g,iv:q(v.iv),ct:q(v.ct),k:b},L,V,de=U.ct;s&&de.length>xo&&(L=$(de),U.ct="",U.ct_ref=Do,y&&y.ctRef&&(V=y.ctRef));let ie=JSON.stringify(U).length;if(ie>2*1024*1024)throw new c(`Encrypted record data is too large: once encrypted and base64 encoded it becomes ${ie} bytes, over the ${2*1024*1024} byte limit. Encryption costs about 33% plus roughly 230 bytes per additional recipient.`,{code:"ENCRYPTED_DATA_TOO_LARGE"});return s&&n.dek.set(s,{bytes:_,key:w,recipients:b,anch:E,uid:o,rid:s,own:g,access_group:"private"}),{send:U,plain:e,encrypted:true,omit:false,spill:L,retireCt:V,dek:{bytes:_,key:w,recipients:b,anch:E,uid:o,rid:s,own:g,access_group:"private"},files:m?"encrypt":void 0}}function pn(e,t){let r=O.call(this);!r||!t||!e||r.dek.has(e)||r.dek.set(e,Object.assign({},t,{rid:e}));}async function Oo(e,t,r,n,i,s,o,a){let u=Object.keys(r).filter(f=>f!==i);if(!u.length)return r;let l=await dr.call(this,u),g={[i]:r[i]};for(let f of u){let d=l[f];d&&(g[f]=await hn.call(this,t,d,n,o,i,f,a));}return g}async function hn(e,t,r,n,i,s,o){let a=dn(r,n,i,s,t.fpr),u=We(o,s,t.fpr),l=await Gr(t.pubRaw,e,a,u);return {t:"ecdh",epk:q(l.epk),iv:q(l.iv),ct:q(l.ct),fpr:t.fpr}}async function mn(e,t){if(!yt(e))return {value:e};if(t.access_group!=="private")return {value:e};let r=O.call(this);if(!r)return {value:null,flag:{status:"failed",reason:"ENCRYPTION_DISABLED"}};if(r.rawRead)return {value:e};if(un(r,t.table_name))return {value:e};if(e[Qe]!==on)return {value:ee(r.cfg,"UNSUPPORTED_VERSION"),flag:{status:"failed",reason:"UNSUPPORTED_VERSION"}};if(r.ready&&!r.unlocking)try{await r.ready;}catch{}if(e.own!==t.user_id)return {value:ee(r.cfg,"BINDING_MISMATCH"),flag:{status:"failed",reason:"BINDING_MISMATCH"}};if(e.uid&&t.unique_id&&e.uid!==t.unique_id)return {value:ee(r.cfg,"BINDING_MISMATCH"),flag:{status:"failed",reason:"BINDING_MISMATCH"}};if(e.rid&&t.record_id&&e.rid!==t.record_id)return {value:ee(r.cfg,"BINDING_MISMATCH"),flag:{status:"failed",reason:"BINDING_MISMATCH"}};let n=this.user?.user_id,i=n?e.k[n]:null;if(!i)return {value:ee(r.cfg,"NOT_A_RECIPIENT",Object.keys(e.k)),flag:{status:"failed",reason:"NOT_A_RECIPIENT",recipients:Object.keys(e.k)}};if(r.status!=="unlocked"||!r.mk)return {value:ee(r.cfg,"NO_SESSION_KEY"),flag:{status:"failed",reason:"NO_SESSION_KEY"}};let s=xe.call(this),o=tr(e),a=er(s,e.own,e.anch,o),u;try{if(i.t==="mk")u=await ae(r.mk,$(i.iv),$(i.ct),We(a,n,"mk"));else if(i.t==="ecdh"){if(!r.ikPriv)return {value:ee(r.cfg,"NO_SESSION_KEY"),flag:{status:"failed",reason:"NO_SESSION_KEY"}};u=await Wr(r.ikPriv,$(i.epk),$(i.iv),$(i.ct),dn(s,o,e.own,n,i.fpr),We(a,n,i.fpr));}else return {value:ee(r.cfg,"UNSUPPORTED_VERSION"),flag:{status:"failed",reason:"UNSUPPORTED_VERSION"}}}catch{return {value:ee(r.cfg,"BAD_KEY"),flag:{status:"failed",reason:"BAD_KEY"}}}let l;try{if(e.ct_ref){if(!t.ctUrl)return F(u),{value:ee(r.cfg,"DATA_UNAVAILABLE"),flag:{status:"failed",reason:"DATA_UNAVAILABLE"}};let p=await Lo.call(this,t.ctUrl);l=new Uint8Array(await p.arrayBuffer());}else l=$(e.ct);}catch{return F(u),{value:ee(r.cfg,"DATA_UNAVAILABLE"),flag:{status:"failed",reason:"DATA_UNAVAILABLE"}}}let g,f;try{f=await oe(u),g=await ae(f,$(e.iv),l,a);}catch{return F(u),{value:ee(r.cfg,"CORRUPT"),flag:{status:"failed",reason:"CORRUPT"}}}let d;try{d=JSON.parse(je(g));}catch{return F(g),F(u),{value:ee(r.cfg,"CORRUPT"),flag:{status:"failed",reason:"CORRUPT"}}}if(F(g),t.record_id){let p=r.dek.get(t.record_id);p?(p.bytes=u,p.key=f,p.recipients=e.k,p.anch=e.anch,p.uid=e.uid,p.own=e.own,p.access_group="private",p.ctRef=e.ct_ref||""):r.dek.set(t.record_id,{bytes:u,key:f,recipients:e.k,anch:e.anch,uid:e.uid,rid:t.record_id,own:e.own,access_group:"private",ctRef:e.ct_ref||""});}else F(u);return {value:d,flag:{status:"encrypted",recipients:Object.keys(e.k)}}}function ze(e,t){let[r,n]=e.split("/");return K(`${X}|kek|${r}|${n}|${t}`)}function Je(e,t,r,n){let[i,s]=e.split("/");return K(`${X}|mk|${i}|${s}|${t}|PBKDF2-SHA256|${r}|${n}`)}function yn(e,t){let[r,n]=e.split("/");return K(`${X}|recovery|${r}|${n}|${t}`)}function bn(e,t,r){let[n,i]=e.split("/");return K(`${X}|rk|${n}|${i}|${t}|HKDF-SHA256|${r}`)}function _n(e,t){let[r,n]=e.split("/");return K(`${X}|self|${r}|${n}|${t}`)}function wn(e,t){let[r,n]=e.split("/");return K(`${X}|ik|${r}|${n}|${t}`)}async function bt(e){let r=((await this.getRecords({table:{name:e.cfg.table,access_group:"private"},index:{name:"$user_id",value:this.user.user_id,condition:"="}},{limit:2}))?.list||[]).filter(n=>n.user_id===this.user.user_id);return r.length?(r.sort((n,i)=>n.uploaded-i.uploaded),r[0]):null}async function sr(e,t,r){let n=Z(Ke),i=zr(n),s=Z(16),o=q(s),a=await zt(n,s,yn(e,t)),u=await ne(a,r,bn(e,t,o));return F(n),{code:i,wrap:{id:q(Z(6)),p:"recovery",kdf:{a:"HKDF-SHA256",s:o},iv:q(u.iv),ct:q(u.ct),created:Date.now()}}}async function Mo(e,t,r,n){let i=Jr(n),s=(r||[]).filter(o=>o.p==="recovery");s.sort((o,a)=>(a.created||0)-(o.created||0));for(let o of s)try{let a=await zt(i,$(o.kdf.s),yn(e,t)),u=await ae(a,$(o.iv),$(o.ct),bn(e,t,o.kdf.s));return F(i),u}catch{}return F(i),null}async function Fo(e,t,r,n,i){let s=Z(16),o=q(s),a=await Ue(n,s,e.cfg.iterations,ze(t,r)),u=await ne(a,i,Je(t,r,e.cfg.iterations,o));return {id:q(Z(6)),p:"password",kdf:{a:"PBKDF2-SHA256",it:e.cfg.iterations,s:o},iv:q(u.iv),ct:q(u.ct),created:Date.now()}}async function qo(e,t){let r=this.user.user_id,n=e.scope,i=Z(16),s=q(i),o=await Ue(t,i,e.cfg.iterations,ze(n,r)),a=Z(32),u=await ne(o,a,Je(n,r,e.cfg.iterations,s)),l=await oe(a),g=await Kr(),f=await ne(l,g.pkcs8,wn(n,r));F(g.pkcs8);let d=null;e.cfg.recovery==="code"&&(d=await sr(n,r,a));let p=await ne(l,a,_n(n,r));F(a);let m=await Wt(g.pubRaw),y=Date.now(),_=[{id:q(Z(6)),p:"password",kdf:{a:"PBKDF2-SHA256",it:e.cfg.iterations,s},iv:q(u.iv),ct:q(u.ct),created:y}];d&&_.push(d.wrap);let w={v:1,alg:"ECDH-P-256",user_id:r,wraps:_,ik:{iv:q(f.iv),ct:q(f.ct)},self:{iv:q(p.iv),ct:q(p.ct)},pub:q(g.pubRaw),fpr:m,pins:null,created:y,updated:y};await this.postRecord({v:1,alg:"ECDH-P-256",user_id:r,pub:q(g.pubRaw),fpr:m,created:y},{table:{name:e.cfg.table,access_group:"authorized"},index:{name:"pubkey",value:r}});let b=await this.postRecord(w,{table:{name:e.cfg.table,access_group:"private"}}),E=await bt.call(this,e);if(E&&E.record_id!==b.record_id){await En.call(this,e,E,t);return}e.mk=l,e.ikPriv=g.priv,e.pubRaw=g.pubRaw,e.fpr=m,e.keyringRecordId=b.record_id,d&&(e.pendingRecoveryCode=d.code),e.user_id=r,e.pins={},e.status="unlocked",e.reason="";}async function En(e,t,r){let n=this.user.user_id,i=e.scope,s=t.data;if(t.user_id!==n||s&&s.user_id&&s.user_id!==n)throw new c("The encryption keyring does not belong to this user.",{code:"ENCRYPTION_KEYRING_CORRUPT"});let a=(Array.isArray(s?.wraps)?s.wraps:[]).filter(g=>g.p==="password");if(!a.length)throw new c("The keyring has no password wrap.",{code:"ENCRYPTION_KEYRING_CORRUPT"});a.sort((g,f)=>(f.created||0)-(g.created||0));let u=null;for(let g of a)try{let f=$(g.kdf.s),d=await Ue(r,f,g.kdf.it,ze(i,n));u=await ae(d,$(g.iv),$(g.ct),Je(i,n,g.kdf.it,g.kdf.s));break}catch{}if(!u)throw new c("Incorrect password: the encryption keyring could not be opened.",{code:"ENCRYPTION_BAD_PASSWORD"});let l=await oe(u);F(u),await or.call(this,e,t,l);}async function or(e,t,r){let n=this.user.user_id,i=t.data,s=await ae(r,$(i.ik.iv),$(i.ik.ct),wn(e.scope,n)),o=await Gt(s);F(s);let a={};if(i.pins&&typeof i.pins=="object"&&i.pins.ct)try{let u=await ae(r,$(i.pins.iv),$(i.pins.ct),K(`${X}|pins|${e.scope}|${n}`));a=JSON.parse(je(u)),F(u);}catch{a={};}e.mk=r,e.ikPriv=o,e.pubRaw=$(i.pub),e.fpr=i.fpr,e.keyringRecordId=t.record_id,e.user_id=n,e.pins=a,e.status="unlocked",e.reason="";}async function _t(e){let t=O.call(this);if(!t||!this.user?.user_id)return;if(!Ht()){t.status="locked",t.reason="NO_WEB_CRYPTO";return}if(this.user?.is_openid){t.status="locked",t.reason="OPENID_UNSUPPORTED";return}if(t.cfg.minPasswordLength&&e.length<t.cfg.minPasswordLength){t.status="locked",t.reason="WEAK_PASSWORD";return}t.scope=xe.call(this);let r=await bt.call(this,t);r?await En.call(this,t,r,e):await qo.call(this,t,e),t.cfg.persistDevice&&await Pn.call(this,t).catch(()=>{});}async function An(e){await this.__connection;let t=O.call(this);if(!t)throw new c("Encryption is not enabled for this instance.",{code:"INVALID_REQUEST"});if(!this.user?.user_id)throw new c("User login is required.",{code:"INVALID_REQUEST"});if(!e?.password||typeof e.password!="string")throw new c('"password" is required.',{code:"INVALID_PARAMETER"});if(await _t.call(this,e.password),t.status!=="unlocked")throw new c(`Encryption could not be unlocked: ${t.reason}`,{code:"ENCRYPTION_LOCKED"});return {status:t.status}}async function Rn(e){let t=O.call(this);return t?(e?.forgetDevice&&await ur.call(this,t).catch(()=>{}),Zt.call(this),this.__cached_requests={},{status:t.status}):{status:"disabled"}}async function In(e,t){let r=O.call(this);if(!r)return;if(r.status!=="unlocked"||!r.mk)throw new c("Encryption must be unlocked before changing the password, or the encryption keyring would be left wrapped under a password that no longer exists. Call unlockEncryption({ password }) first.",{code:"ENCRYPTION_LOCKED"});let i=(await this.getRecords({record_id:r.keyringRecordId},{limit:1}))?.list?.[0];if(!i)throw new c("The encryption keyring could not be read, so the password change was stopped before it could strand it.",{code:"ENCRYPTION_KEYRING_CORRUPT"});let s=this.user.user_id,o=i.data,a=(o.wraps||[]).filter(y=>y.p==="password");a.sort((y,_)=>(_.created||0)-(y.created||0));let u=null;for(let y of a)try{let _=await Ue(e,$(y.kdf.s),y.kdf.it,ze(r.scope,s));u=await ae(_,$(y.iv),$(y.ct),Je(r.scope,s,y.kdf.it,y.kdf.s));break}catch{}if(!u)throw new c("Incorrect current password: the encryption keyring was not re-wrapped.",{code:"ENCRYPTION_BAD_PASSWORD"});let l=Z(16),g=q(l),f=await Ue(t,l,r.cfg.iterations,ze(r.scope,s)),d=await ne(f,u,Je(r.scope,s,r.cfg.iterations,g));F(u);let p=Date.now(),m=(o.wraps||[]).concat([{id:q(Z(6)),p:"password",kdf:{a:"PBKDF2-SHA256",it:r.cfg.iterations,s:g},iv:q(d.iv),ct:q(d.ct),created:p}]);await this.postRecord(Object.assign({},o,{wraps:m,updated:p}),{record_id:r.keyringRecordId});}async function Tn(){let e=O.call(this);if(!e||e.status!=="unlocked"||!e.keyringRecordId)return;let r=(await this.getRecords({record_id:e.keyringRecordId},{limit:1}))?.list?.[0];if(!r)return;let n=r.data,i=(n.wraps||[]).filter(o=>o.p==="password").sort((o,a)=>(a.created||0)-(o.created||0)),s=(n.wraps||[]).filter(o=>o.p!=="password");i.length<=1||await this.postRecord(Object.assign({},n,{wraps:[i[0]].concat(s),updated:Date.now()}),{record_id:e.keyringRecordId});}function ar(){return typeof indexedDB<"u"&&!!indexedDB}function lr(){return new Promise((e,t)=>{let r=indexedDB.open(Uo,1);r.onupgradeneeded=()=>{let n=r.result;n.objectStoreNames.contains(Ee)||n.createObjectStore(Ee);},r.onsuccess=()=>e(r.result),r.onerror=()=>t(r.error);})}function cr(e){return `${e.scope}#${this.user?.user_id}`}async function Pn(e){if(!ar()||!e.mk)return;let t=await lr();await new Promise((r,n)=>{let i=t.transaction(Ee,"readwrite");i.objectStore(Ee).put({mk:e.mk,keyringRecordId:e.keyringRecordId,saved:Date.now()},cr.call(this,e)),i.oncomplete=()=>r(),i.onerror=()=>n(i.error);}),t.close();}async function Vo(e){if(!ar())return null;let t=await lr(),r=await new Promise((n,i)=>{let o=t.transaction(Ee,"readonly").objectStore(Ee).get(cr.call(this,e));o.onsuccess=()=>n(o.result||null),o.onerror=()=>i(o.error);});return t.close(),r&&r.mk?r:null}async function ur(e){if(!ar())return;let t=await lr();await new Promise((r,n)=>{let i=t.transaction(Ee,"readwrite");i.objectStore(Ee).delete(cr.call(this,e)),i.oncomplete=()=>r(),i.onerror=()=>n(i.error);}),t.close();}function Sn(){let e=O.call(this);!e||e.ready||(e.unlocking=true,e.ready=$o.bind(this)().catch(()=>false).then(()=>{e.unlocking=false;}));}async function $o(){let e=O.call(this);if(!e||!this.user?.user_id||!e.cfg.persistDevice||!Ht())return false;e.scope=xe.call(this);try{let t=await Vo.call(this,e);if(!t)return !1;let r=await bt.call(this,e);return r?(await or.call(this,e,r,t.mk),!0):(await ur.call(this,e).catch(()=>{}),!1)}catch{return e.status="locked",e.reason="NO_SESSION_KEY",false}}async function dr(e){let t=O.call(this);if(!t)throw new c("Encryption is not enabled for this instance.",{code:"INVALID_REQUEST"});let r={},n=[],i=false;for(let s of e){let o=t.peerPub.get(s);o?r[s]=o:n.push(s);}return await Promise.all(n.map(async s=>{let o=t.peerInflight.get(s);o||(o=(async()=>{let l=((await this.getRecords({table:{name:t.cfg.table,access_group:"authorized"},index:{name:"$user_id",value:s,condition:"="}},{limit:10}))?.list||[]).filter(p=>p.user_id===s&&p.data?.pub);if(!l.length)return null;l.sort((p,m)=>m.uploaded-p.uploaded);let g=$(l[0].data.pub),f=await Wt(g),d=t.pins[s];if(d&&d!==f)throw new c(`The public key for user "${s}" has changed since it was first seen. This is expected if they reset their account, and is what a key substitution attack also looks like. Verify the new fingerprint out of band, then call pinPeerKey({ user_id, fingerprint }).`,{code:"ENCRYPTION_PEER_KEY_CHANGED"});if(!d){if(t.cfg.trustPolicy==="strict")throw new c(`No pinned key for user "${s}" and trustPolicy is "strict". Pin it first with pinPeerKey().`,{code:"ENCRYPTION_PEER_NOT_PINNED"});t.pins[s]=f,i=true;}return {pubRaw:g,fpr:f}})().finally(()=>t.peerInflight.delete(s)),t.peerInflight.set(s,o));let a=await o;a&&t.peerPub.set(s,a),r[s]=a;})),i&&await Un.call(this,t).catch(()=>{}),r}async function kn(e,t){let r=xe.call(this),n=e.dek.get(t);if(n)return {entry:n,scope:r};let i=await we.call(this,t);if(!i)throw new c(`Record "${t}" not found.`,{code:"NOT_EXISTS"});if(i.encrypted?.status==="failed"&&i.encrypted.reason==="DATA_UNAVAILABLE")throw new c(`Cannot change sharing on record "${t}": its data could not be read, so whether it is encrypted is unknown. Retry once the record reads normally.`,{code:"ENCRYPTION_DATA_UNAVAILABLE"});if(!i.encrypted)return null;if(i.user_id!==this.user?.user_id)throw new c("Only the record owner can share or revoke an encrypted record, because adding or removing a key wrap means writing the record.",{code:"ENCRYPTION_GRANT_REQUIRES_OWNER"});let s=e.dek.get(i.record_id)||e.dek.get(t);if(!s)throw new c(`Cannot change sharing on record "${t}": its data could not be decrypted`+(i.encrypted.reason?` (${i.encrypted.reason})`:"")+".",{code:"ENCRYPTION_LOCKED"});return {entry:s,scope:r}}async function fr(e,t){let r=O.call(this);if(!r)return;let n=await kn.call(this,r,e);if(!n)return;let{entry:i,scope:s}=n,o=this.user.user_id;if(i.own!==o)throw new c("Only the record owner can share an encrypted record, because adding a key wrap means writing the record.",{code:"ENCRYPTION_GRANT_REQUIRES_OWNER"});let a=await dr.call(this,t),u=t.filter(d=>!a[d]);if(u.length)throw new c(`These users have no encryption key yet, so they cannot be given access: ${u.join(", ")}. A user's key is created the first time they log in with encryption enabled.`,{code:"ENCRYPTION_RECIPIENT_HAS_NO_KEY"});let l=tr(i),g=er(s,i.own,i.anch,l),f=Object.assign({},i.recipients);for(let d of t)d!==o&&(f[d]=await hn.call(this,i.bytes,a[d],s,l,i.own,d,g));await Bo.call(this,r,e,i,f);}async function vn(e,t){let r=O.call(this);if(!r)return;let n=await kn.call(this,r,e);if(!n)return;let{entry:i}=n,s=this.user.user_id;if(i.own!==s)throw new c("Only the record owner can revoke access to an encrypted record.",{code:"ENCRYPTION_GRANT_REQUIRES_OWNER"});let o=Object.keys(i.recipients).filter(l=>l===s?true:t?!t.includes(l):false).filter(l=>l!==s),a=await we.call(this,e);if(!a)throw new c(`Record "${e}" not found.`,{code:"NOT_EXISTS"});jo(a,e);let u={};if(o.length){u=await dr.call(this,o);let l=o.filter(g=>!u[g]);if(l.length)throw new c(`Cannot revoke on record "${e}": these users keep access but their encryption keys could not be read, so re-sharing after the key roll would fail and lock them out: ${l.join(", ")}.`,{code:"ENCRYPTION_RECIPIENT_HAS_NO_KEY"})}r.roll.add(a.record_id||e),await this.postRecord(a.data,{record_id:a.record_id||e,table:{name:a.table.name,access_group:"private"}}),o.length&&await fr.call(this,a.record_id||e,o);}function jo(e,t){if(e?.encrypted?.status==="failed")throw new c(`Cannot change sharing on record "${t}": its current data could not be read (${e.encrypted.reason}), so re-writing the record would destroy it.`,{code:"ENCRYPTION_DATA_UNAVAILABLE"})}async function Bo(e,t,r,n){let i=await Ko.call(this,t);if(!i)throw new c(`Cannot change sharing on record "${t}": its stored envelope could not be read.`,{code:"ENCRYPTION_DATA_UNAVAILABLE"});r.recipients=n,e.dek.set(t,r);let s=Object.assign({},i,{k:n});e.passthrough.set(t,s),await this.postRecord(void 0,{record_id:t});}async function Ko(e){let t=O.call(this);if(!t)return null;t.rawRead=true;let r;try{r=(await this.getRecords({record_id:e},{limit:1}))?.list?.[0];}finally{t.rawRead=false;}return r&&yt(r.data)?r.data:null}async function Nn(e){let t=O.call(this);if(!t||t.status!=="unlocked")throw new c("Encryption is locked.",{code:"ENCRYPTION_LOCKED"});t.pins[e.user_id]=e.fingerprint,t.peerPub.delete(e.user_id),await Un.call(this,t);}async function Un(e){if(!e.mk||!e.keyringRecordId)return;let r=(await this.getRecords({record_id:e.keyringRecordId},{limit:1}))?.list?.[0];if(!r)return;let n=await ne(e.mk,K(JSON.stringify(e.pins)),K(`${X}|pins|${e.scope}|${e.user_id}`));await this.postRecord(Object.assign({},r.data,{pins:{iv:q(n.iv),ct:q(n.ct)},updated:Date.now()}),{record_id:e.keyringRecordId});}function xn(){let e=O.call(this);if(!e||!e.pendingRecoveryCode)return null;let t=e.pendingRecoveryCode;return e.pendingRecoveryCode="",t}async function Dn(e){await this.__connection;let t=O.call(this);if(!t)throw new c("Encryption is not enabled for this instance.",{code:"INVALID_REQUEST"});if(!this.user?.user_id)throw new c("User login is required. Reset the password and log in first, then use the recovery code.",{code:"INVALID_REQUEST"});if(!e?.code||typeof e.code!="string")throw new c('"code" is required.',{code:"INVALID_PARAMETER"});t.scope=xe.call(this);let r=this.user.user_id,n=await bt.call(this,t);if(!n)throw new c("This account has no encryption keyring, so there is nothing to recover.",{code:"NOT_EXISTS"});let i=await Mo(t.scope,r,n.data?.wraps||[],e.code);if(!i)throw new c("That recovery code did not open the keyring. Check it against the copy you saved when encryption was set up.",{code:"ENCRYPTION_BAD_RECOVERY_CODE"});let s=await oe(i);await or.call(this,t,n,s);let o=false,a=null,u=(n.data?.wraps||[]).slice();if(e.password&&(u=u.filter(l=>l.p!=="password"),u.push(await Fo(t,t.scope,r,e.password,i)),o=true),t.cfg.recovery==="code"){let l=await sr(t.scope,r,i);u=u.filter(g=>g.p!=="recovery"),u.push(l.wrap),a=l.code;}return F(i),await this.postRecord(Object.assign({},n.data,{wraps:u,updated:Date.now()}),{record_id:n.record_id}),t.cfg.persistDevice&&await Pn.call(this,t).catch(()=>{}),{status:t.status,repaired:o,recoveryCode:a}}async function Cn(){await this.__connection;let e=O.call(this);if(!e)throw new c("Encryption is not enabled for this instance.",{code:"INVALID_REQUEST"});if(e.status!=="unlocked"||!e.mk)throw new c("Encryption must be unlocked to issue a recovery code. Only someone who can already decrypt can create one.",{code:"ENCRYPTION_LOCKED"});if(e.cfg.recovery!=="code")throw new c('Recovery codes are disabled for this instance ("recovery" is "none").',{code:"INVALID_REQUEST"});let r=(await this.getRecords({record_id:e.keyringRecordId},{limit:1}))?.list?.[0];if(!r)throw new c("The encryption keyring could not be read.",{code:"ENCRYPTION_KEYRING_CORRUPT"});let n=r.data?.self;if(!n||!n.ct)throw new c("This keyring predates recovery-code rotation and cannot issue a new code. Use unlockWithRecoveryCode() with the existing code, which issues a replacement.",{code:"ENCRYPTION_KEYRING_CORRUPT"});let i=await ae(e.mk,$(n.iv),$(n.ct),_n(e.scope,e.user_id)),s=await sr(e.scope,e.user_id,i);F(i);let o=(r.data.wraps||[]).filter(a=>a.p!=="recovery").concat([s.wrap]);return await this.postRecord(Object.assign({},r.data,{wraps:o,updated:Date.now()}),{record_id:e.keyringRecordId}),{recoveryCode:s.code}}var mt="__skenc__",Ln="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function Ho(e){if(e===0)return "0";let t="";for(;e>0;)t=Ln[e%62]+t,e=Math.floor(e/62);return t}function Go(e){let t=0;for(let r of e){let n=Ln.indexOf(r);if(n<0)return NaN;t=t*62+n;}return t}function wt(e){if(typeof e!="string")return null;let t=e.lastIndexOf(mt);if(t<0)return null;let r=Go(e.slice(t+mt.length));return Number.isFinite(r)?{key:e.slice(0,t),plainSize:r}:null}function gr(e){try{let t=String(e).split("?")[0].split("/").slice(3);if(t.length<12||t[4]!=="records"||t[7]!=="bin")return null;let r=wt(t[10]);return r?{recordId:t[5],recordOwner:t[3],filename:t[t.length-1],plainSize:r.plainSize}:null}catch{return null}}function On(e,t){return {service:this.service,owner:this.owner,recordOwner:t,recordId:e}}async function Mn(e,t,r){let n=O.call(this);if(!n||!e)return {key:t,file:r,encrypted:false};let i=n.dek.get(e);if(!i)return {key:t,file:r,encrypted:false};if(wt(t))throw new c(`"${mt}" is reserved in an upload form key.`,{code:"INVALID_PARAMETER"});if(t===Ye)return {key:t,file:r,encrypted:false};let s=new Uint8Array(await r.arrayBuffer()),o={n:r.name,t:r.type||"",lm:r.lastModified||0},a=await rn(i.bytes,s,On.call(this,e,i.own),o);return F(s),{key:`${t}${mt}${Ho(r.size)}`,file:new File([a],r.name,{type:"application/octet-stream"}),encrypted:true}}async function Fn(e,t){let r=O.call(this),n=gr(e);if(!r||!n)return t;let i=r.dek.get(n.recordId);if(!i)throw new c(`Cannot open this file: the data key for record "${n.recordId}" is not available. Read the record first, and make sure encryption is unlocked.`,{code:"ENCRYPTION_LOCKED"});let s=new Uint8Array(await t.arrayBuffer());if(!Jt(s))throw new c("This file is marked as encrypted but its contents are not an encrypted container.",{code:"ENCRYPTION_FILE_CORRUPT"});let o=await nn(i.bytes,s,On.call(this,n.recordId,n.recordOwner)),a=o.meta&&o.meta.t||"application/octet-stream";return new Blob([o.bytes],{type:a})}function Wo(e){let t=[];for(let r in e?.bin||{})for(let n of e.bin[r]||[])n&&n.encrypted&&t.push({formKey:r,url:n.url,filename:n.filename});return t}function Qo(e){let t=[];for(let r in e?.bin||{})for(let n of e.bin[r]||[])n&&!n.encrypted&&t.push({formKey:r,url:n.url,filename:n.filename});return t}async function pr(e,t,r){let n=O.call(this);if(!n)return [];let i=await we.call(this,e);if(!i)return [];let s=t==="decrypt"?Wo(i):Qo(i);if(!s.length)return [];let o=[],a=new FormData,u=false;for(let l of s){let g=i.bin[l.formKey].find(d=>d.url===l.url);if(!g||typeof g.getFile!="function")continue;let f=await g.getFile("blob");f&&(a.append(l.formKey,new File([f],l.filename,{type:f.type||"application/octet-stream"})),o.push(l.url),u=true);}if(!u)return [];if(t==="decrypt"){let l=n.dek.get(e);l&&(F(l.bytes),n.dek.delete(e));}return await this.uploadFiles(a,{record_id:e,progress:r}),o}var B=null;function hr(e){let t={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"},r={};for(let n in e)if(n==="tkid"){let i=e[n].split("#");if(i.length===1){r.ticket_id=i[0];continue}r.ticket_id=i[1],r.consume_id=i[2],r.user_id=i[3];let s=i[2].slice(-4);if(r.is_test=s===":CHK",!e.stmp){let o=i[2].slice(0,-4);/^[0-9]+$/.test(o)?r.timestamp=parseInt(o,10):r.timestamp=se(i[2].slice(0,-4));}}else t[n]?r[t[n]]=e[n]:r[n]=e[n];return r}async function Vn(e){if(!e.ticket_id)throw new c("Ticket ID is required.",{code:"INVALID_PARAMETER"});if(!e.method)throw new c('Method is required. Should be either "GET" or "POST"',{code:"INVALID_PARAMETER"});let t=e.ticket_id;await this.__connection;let r=await T.bind(this)(`https://${this.service.slice(0,4)}.${this.customApiDomain}/auth/consume/${this.service}/${this.owner}/${t}`,e?.data||{},{method:e.method,auth:!!e?.auth});return hr(r)}async function $n(e,t){await this.__connection;let r=await T.bind(this)("ticket",Object.assign({exec:"list"},e||{}),{auth:true,fetchOptions:t});return r.list=r.list.map(hr),r}async function jn(e,t){await this.__connection;let r=await T.bind(this)("ticket",Object.assign({exec:"consumed"},e||{}),{auth:true,fetchOptions:t});return r.list=r.list.map(hr),r}async function Bn(e){return T.bind(this)("register-ticket",Object.assign({exec:"reg"},e),{auth:true})}async function Kn(e){return T.bind(this)("register-ticket",Object.assign({exec:"unreg"},e),{auth:true})}var ea=3600;async function Ce(){if(await this.__connection,this.session){let e=Math.floor(Date.now()/1e3),r=this.session.getIdToken().getExpiration();if(r<e+ea){this.log("request:requesting new token",null);try{await z.bind(this)().getSession({refreshToken:!0}),this.log("request:received new tokens",{exp:this.session?.idToken?.payload?.exp,currentTime:e,expiresIn:r-e,token:this.session?.accessToken?.jwtToken,refreshToken:this.session?.refreshToken?.token});}catch(n){throw this.log("request:new token error",n),new c("User login is required.",{code:"INVALID_REQUEST"})}}else this.log("request:tokens",{exp:this.session.idToken.payload.exp,currentTime:e,expiresIn:r-e,token:this.session.accessToken.jwtToken,refreshToken:this.session.refreshToken.token});return this.session?.idToken?.jwtToken}else throw this.log("request:no session",null),be.bind(this)(),new c("User login is required.",{code:"INVALID_REQUEST"})}function qn(e,t){return new Promise((r,n)=>{t.refreshSession(e.getRefreshToken(),(i,s)=>{this.log("getSession:refreshSessionCallback",{refreshErr:i,refreshedSession:s}),i?(be.bind(this)(),n(i)):s.isValid()?r(s):(be.bind(this)(),n(new c("Invalid session.",{code:"INVALID_REQUEST"})));});})}function z(){if(!this.userPool)throw new c("User pool is missing",{code:"INVALID_REQUEST"});let e=()=>{let s=B.getSignInUserSession().getIdToken().payload||null,o=$e(s);return this.log("normalized user attribute",o),this.__user=o,o},t=async s=>new Promise((o,a)=>{this.log("getSession:option",s);let{refreshToken:u=false,skipUserUpdateEventTrigger:l=false}=s||{};if(u&&l&&(l=false),B=this.userPool.getCurrentUser(),!B){this.log("getSession:cognitoUser",B),be.bind(this)(),a(null);return}let g=f=>{let d=f.getIdToken().payload;if(this.log("getSession:respond:sessionAttribute",d),d["custom:service"]!==this.service)throw this.log("getSession:respond","invalid service, signing out"),be.bind(this)(),new c("Invalid session.",{code:"INVALID_REQUEST"});return this.session=f,e(),l||this._runOnUserUpdateListeners(this.user),this.session};B.getSession((f,d)=>{if(this.log("getSession:getSessionCallback",{err:f,session:d}),!d){be.bind(this)(),a(new c("Current session does not exist.",{code:"INVALID_REQUEST"}));return}if(f){qn.bind(this)(d,B).then(w=>o(g(w))).catch(a);return}let p=Math.floor(Date.now()/1e3),m=d.getIdToken(),y=m.getExpiration(),_=y<p;if(this.log("getSession:currentTime",p),this.log("getSession:idTokenExp",y),this.log("getSession:isExpired",_),this.log("getSession:existingBearerToken",this.bearerToken),this.bearerToken=m.getJwtToken(),_||u||!d.isValid())qn.bind(this)(d,B).then(w=>o(g(w))).catch(a);else try{o(g(d));}catch(w){a(w);}});}),r=(s,o)=>{let a=o||s.includes(this.service+"-")?s:this.service+"-"+G.hash(s);return {cognitoUser:new CognitoUser({Username:a,Pool:this.userPool}),cognitoUsername:a}};return {getSession:t,authenticateUser:(s,o,a=false,u=false)=>new Promise((l,g)=>{this.__request_signup_confirmation=null,this.__disabledAccount=null;let f=r(s,a),d=f.cognitoUsername,p=new AuthenticationDetails({Username:d,Password:o});f.cognitoUser.authenticateUser(p,{newPasswordRequired:(m,y)=>{this.__disabledAccount=null,this.__request_signup_confirmation=d,m["custom:signup_ticket"]==="PASS"||m["custom:signup_ticket"]==="MEMBER"||m["custom:signup_ticket"]==="OIDPASS"?f.cognitoUser.completeNewPasswordChallenge(o,{},{onSuccess:_=>{B=f.cognitoUser,t().then(async w=>{if(O.call(this))try{await _t.bind(this)(o);}catch(b){this.log("encryption:ensureKeyring:failed",b);}l(this.user);});},onFailure:_=>{g(new c(_.message||"Failed to authenticate user.",{code:_.code}));}}):g(new c("User's signup confirmation is required.",{code:"SIGNUP_CONFIRMATION_NEEDED"}));},onSuccess:m=>t({skipUserUpdateEventTrigger:true}).then(async y=>{if(this.__disabledAccount=null,O.call(this))try{await _t.bind(this)(o);}catch(_){this.log("encryption:ensureKeyring:failed",_);}this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user),l(this.user);}),onFailure:m=>{let y=[],{parsed:_,code:w}=At(m),b=typeof m?.message=="string"?m.message:"";if(w==="NotAuthorizedException"?b.includes("User is disabled.")?(this.__disabledAccount=d,y=["This account is disabled.","USER_IS_DISABLED"]):u?y=["The account already exists.","ACCOUNT_EXISTS"]:y=["Incorrect username or password.","INCORRECT_USERNAME_OR_PASSWORD"]:w==="UserNotFoundException"?y=["Incorrect username or password.","INCORRECT_USERNAME_OR_PASSWORD"]:w==="UserNotConfirmedException"?(this.__request_signup_confirmation=d,y=["User's signup confirmation is required.","SIGNUP_CONFIRMATION_NEEDED"]):(w==="TooManyRequestsException"||w==="LimitExceededException")&&(y=["Too many attempts. Please try again later.","REQUEST_EXCEED"]),_.code==="SIGNUP_CONFIRMATION_NEEDED"&&(this.__request_signup_confirmation=d),y.length){let E=y[1],k=y[0];g(new c(k,{code:E,cause:m}));}else g(_);}});}),createCognitoUser:r,signup:(s,o,a)=>new Promise((u,l)=>{this.userPool.signUp(s,o,a,null,(g,f)=>{if(g){let{parsed:d,code:p}=At(g),m=[];p==="UsernameExistsException"?m=["The account already exists.","EXISTS"]:p==="InvalidPasswordException"?m=["Invalid password. Password must be at least 6 characters.","INVALID_PARAMETER"]:p==="InvalidParameterException"?m=[d.message||"Invalid parameter.","INVALID_PARAMETER"]:p==="TooManyRequestsException"||p==="LimitExceededException"?m=["Too many attempts. Please try again later.","REQUEST_EXCEED"]:p==="CodeDeliveryFailureException"?m=["Failed to deliver verification code.","CODE_DELIVERY_FAILURE"]:p==="UserLambdaValidationException"&&(m=[d.message||"Signup validation failed.","INVALID_REQUEST"]),m.length?l(new c(m[0],{code:m[1],cause:g})):l(d);return}u(f);});})}}function At(e){let t=typeof e?.code=="string"&&e.code.trim()?e.code.trim():"ERROR",n=((typeof e?.message=="string"?e.message:typeof e=="string"?e:"An error occurred.")||"An error occurred.").trim();n||(n="An error occurred.");let i=n.match(/#([A-Za-z0-9_]+)\s*:\s*([\s\S]+)/),s=i?.[1]?.trim()||t,o=i?.[2]?.trim()||n;return {parsed:new c(o,{code:s,cause:e}),code:t}}async function Hn(e){await this.__authConnection;let t=e?.refreshToken||false;if(!t)return this.user;try{return await z.bind(this)().getSession(Object.assign({skipUserUpdateEventTrigger:!t,refreshToken:t},e)),this.user}catch{return null}}async function Gn(e){await this.__connection,e=h.Params(e,{token:"string",id:"string",merge:o=>{if(o===void 0)return false;if(typeof o=="string")return [o];if(Array.isArray(o)){for(let a of o)if(typeof a!="string")throw new c('"merge" array items should be type: <string>.',{code:"INVALID_PARAMETER"})}if(typeof o!="boolean"&&!Array.isArray(o))throw new c('"merge" should be type: <boolean | string[]>.',{code:"INVALID_PARAMETER"});return o},template:o=>{if(typeof o!="object"||o===null)throw new c('"template" should be type: <object>.',{code:"INVALID_PARAMETER"});if(o.welcome!==void 0&&(typeof o.welcome!="string"||!o.welcome))throw new c('"template.welcome" should be a non-empty <string> (template message_id).',{code:"INVALID_PARAMETER"});return o}});let t={token:e.token,id:e.id,merge:e.merge};e.template?.welcome&&(t.template_welcome=e.template.welcome);let r=await T.bind(this)("openid-logger",t),n=r.logger.split("#"),i=this.service+"-"+n[0],s=n[1];return {userProfile:await z.bind(this)().authenticateUser(i,s,true,true),openid:r.openid}}function ta(e){let t=typeof globalThis<"u"?globalThis:void 0;if(t?.Buffer)return t.Buffer.from(e,"base64").toString("utf8");if(typeof atob=="function"){let r=atob(e),n=new Uint8Array(r.length);for(let i=0;i<r.length;i++)n[i]=r.charCodeAt(i);return typeof TextDecoder<"u"?new TextDecoder().decode(n):r}throw new Error("No base64 decoder available in this environment")}function ra(e){let t=e.split(".");if(t.length!==3)throw new Error("Invalid JWT format");let n=t[1].replace(/-/g,"+").replace(/_/g,"/"),i=ta(n);return JSON.parse(i)}async function Wn(e){await this.__authConnection,this.log("loginWithToken:params",e),e=h.Params(e,{idToken:"string",accessToken:"string",refreshToken:"string"},["idToken"]);let t=ra(e.idToken);if(this.log("loginWithToken:idTokenPayload",t),t["custom:service"]!==this.service)throw new c("Token does not belong to this service.",{code:"INVALID_REQUEST"});let r=Math.floor(Date.now()/1e3);if(t.exp&&t.exp<r)throw new c("Token has expired.",{code:"INVALID_REQUEST"});if(this.__user=$e(t),this.session=null,e.accessToken&&e.refreshToken)try{if(this.session=new CognitoUserSession({IdToken:new CognitoIdToken({IdToken:e.idToken}),AccessToken:new CognitoAccessToken({AccessToken:e.accessToken}),RefreshToken:new CognitoRefreshToken({RefreshToken:e.refreshToken})}),this.log("loginWithToken:session",this.session),this.log("loginWithToken:CognitoUser",CognitoUser),this.log("loginWithToken:userPool",this.userPool),CognitoUser&&this.userPool){this.log("loginWithToken:cognito:username",t["cognito:username"]);let n={Username:t["cognito:username"],Pool:this.userPool};this.log("loginWithToken:cognitoUserParams",n),B=new CognitoUser(n),B.setSignInUserSession(this.session),this.log("loginWithToken:cognitoUserRestored",{cognitoUserType:typeof B,cognitoUserKeys:Object.keys(B||{}),cognitoUser:B});}}catch(n){this.log("loginWithToken:err",n);try{this.log("loginWithToken:err:stringified",JSON.stringify(n));}catch{this.log("loginWithToken:err:stringifyFail",String(n));}try{let i=Object.keys(n||{}),s=Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(n||{}):[],o=Object.getOwnPropertyDescriptors?Object.getOwnPropertyDescriptors(n||{}):{};this.log("loginWithToken:createSessionError:allKeys",{keys:i,symbols:s,descriptors:o});}catch(i){this.log("loginWithToken:createSessionError:allKeysFail",String(i));}}return this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user),this.user}async function W(){return await this.__connection,this.__user?.service===this.service?this.__user?.owner===this.host:(await Xe.bind(this)(),false)}async function be(e=false){let t=null;B&&(e?t=new Promise((n,i)=>{B.globalSignOut({onSuccess:s=>{this.log("globalSignOut:success",s),n(s);},onFailure:s=>{this.log("globalSignOut:error",s),i(s);}});}):B.signOut()),Zt.bind(this)();let r={session:null,__startKeyHistory:{},__cached_requests:{},__user:null};t&&(t=await t);for(let n in r)this[n]=r[n];return this._runOnUserUpdateListeners(null),this._runOnLoginListeners(null),t}async function Xe(e){await this.__connection;let{data:t}=j(e);return await be.bind(this)(t?.global),"SUCCESS: The user has been logged out."}async function Qn(){if(!this.__request_signup_confirmation)throw new c("Least one login attempt is required.",{code:"INVALID_REQUEST"});return await T.bind(this)("confirm-signup",{username:this.__request_signup_confirmation})}async function zn(e=false){if(typeof e=="string")e=h.Url(e);else if(typeof e!="boolean")throw new c("Argument should be type: <boolean | string>.",{code:"INVALID_REQUEST"});if(!this.__disabledAccount)throw new c("Least one signin attempt of disabled account is required.",{code:"INVALID_REQUEST"});return await T.bind(this)("recover-account",{username:this.__disabledAccount,redirect:e}),"SUCCESS: Recovery e-mail has been sent."}async function mr(e){let t=h.Params(e,{username:"string",email:"string",password:"string"},["password"]);if(await this.__authConnection,t.email)try{h.Email(t.email);}catch{t.username=t.email,delete t.email;}if(!t.username&&!t.email)throw new c('Least one of "username" or "email" is required.',{code:"INVALID_PARAMETER"});return await z.bind(this)().authenticateUser(t.username||t.email,t.password)}async function Jn(e,t){await this.__authConnection;let r={username:"string",password:l=>h.Password(l),email:l=>h.Email(l),name:"string",address:l=>{if(!l)return "";if(typeof l=="string")return l;if(typeof l=="object")return JSON.stringify(l)},gender:"string",birthdate:l=>l?h.Birthdate(l):"",phone_number:l=>l?h.PhoneNumber(l):"",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:l=>l?h.Url(l):"",profile:l=>l?h.Url(l):"",family_name:"string",given_name:"string",middle_name:"string",nickname:"string",website:l=>l?h.Url(l):""},n=h.Params(e||{},r,["email","password"]);await Xe.bind(this)(),t=h.Params(t||{},{email_subscription:l=>{if(typeof l!="boolean")throw new c('"option.email_subscription" should be type: <boolean>.',{code:"INVALID_PARAMETER"});if(!t?.signup_confirmation)throw new c('"option.signup_confirmation" is required for email subscription.',{code:"INVALID_PARAMETER"});return l},signup_confirmation:l=>{let g=l;if(typeof l=="string")g=h.Url(l);else if(typeof l=="boolean")g=l;else throw new c('"option.signup_confirmation" should be type: <string | boolean>.',{code:"INVALID_PARAMETER"});if(g&&!n.email)throw new c('"email" is required for signup confirmation.',{code:"INVALID_PARAMETER"});return g},login:l=>{if(typeof l=="boolean"){if(t.signup_confirmation&&l)throw new c('"login" is not allowed when "option.signup_confirmation" is true.',{code:"INVALID_PARAMETER"});return l}throw new c('"option.login" should be type: boolean.',{code:"INVALID_PARAMETER"})},template:l=>{if(typeof l!="object"||l===null)throw new c('"option.template" should be type: <object>.',{code:"INVALID_PARAMETER"});if(l.signup_confirmation!==void 0){if(typeof l.signup_confirmation!="string"||!l.signup_confirmation)throw new c('"option.template.signup_confirmation" should be a non-empty <string> (template message_id).',{code:"INVALID_PARAMETER"});if(!t?.signup_confirmation)throw new c('"option.signup_confirmation" is required when "option.template.signup_confirmation" is set.',{code:"INVALID_PARAMETER"})}if(l.welcome!==void 0&&(typeof l.welcome!="string"||!l.welcome))throw new c('"option.template.welcome" should be a non-empty <string> (template message_id).',{code:"INVALID_PARAMETER"});return l}});let i=t?.login||false;if(n.signup_confirmation=t?.signup_confirmation||false,n.email_subscription=t?.email_subscription||false,n.email_public&&!n.signup_confirmation)throw new c('"option.signup_confirmation" should be true if "email_public" is set to true.',{code:"INVALID_PARAMETER"});n.service=this.service,n.owner=this.owner;let s=z.bind(this)().createCognitoUser(n.username||n.email);for(let l of ["email_public","address_public","gender_public","birthdate_public","phone_number_public"])n[l]=n[l]?"1":"0";n.access_group&&(n.access_group=n.access_group.toString());let o=(await T.bind(this)("signupkey",{username:s.cognitoUsername,signup_confirmation:typeof n.signup_confirmation=="boolean"?JSON.stringify(n.signup_confirmation):n.signup_confirmation,email_subscription:n.email_subscription,template_confirmation:t?.template?.signup_confirmation||"",template_welcome:t?.template?.welcome||""})).split(":"),a=o.slice(1).join(":"),u=[new CognitoUserAttribute({Name:"custom:signup",Value:o[0]}),new CognitoUserAttribute({Name:"locale",Value:a.split("#")[1]}),new CognitoUserAttribute({Name:"custom:signup_ticket",Value:a})];for(let l in r){let g=["email_public","address_public","gender_public","birthdate_public","phone_number_public","misc","service","owner"];n[l]!==""&&(l==="username"||l==="password"||l==="access_group"||(g.includes(l)?u.push(new CognitoUserAttribute({Name:"custom:"+l,Value:n[l]})):u.push(new CognitoUserAttribute({Name:l,Value:n[l]}))));}return await z.bind(this)().signup(s.cognitoUsername,n.password,u),n.signup_confirmation?(B=s.cognitoUser,this.__request_signup_confirmation=s.cognitoUsername,"SUCCESS: The account has been created. User's signup confirmation is required."):i?mr.bind(this)({email:n.username||n.email,password:n.password}):"SUCCESS: The account has been created."}async function Yn(){await this.__connection;let e=await T.bind(this)("remove-account",{disable:this.__user.user_id},{auth:true});return await Xe.bind(this)(),e}async function Xn(e){await this.__connection;let t=h.Params(e,{email:i=>h.Email(i),code:["number","string"],new_password:i=>h.Password(i)},["email","code","new_password"]),r=t.code,n=t.new_password;return typeof r=="number"&&(r=r.toString()),new Promise(async(i,s)=>{z.bind(this)().createCognitoUser(t.email).cognitoUser.confirmPassword(r,n,{onSuccess:a=>{i("SUCCESS: New password has been set.");},onFailure:a=>{s(new c(a?.message||"Failed to reset password.",{code:a?.code||"ERROR",cause:a}));}});})}async function Zn(e,t,r){await this.__connection;let n;if(!B)throw new c("The user has to be logged in.",{code:"INVALID_REQUEST"});if(e==="email"||e==="phone_number"){if(!this.__user.hasOwnProperty(e))throw new c(`No ${e==="email"?"e-mail":"phone number"} to verify`,{code:"INVALID_REQUEST"});if(this.__user?.[`${e}_verified`])return `SUCCESS: "${e}" is verified.`;n=(t?h.Params(t,{code:"string"}):{}).code||"";}else return;let i,s=r?.template?.verification;if(s!==void 0){if(typeof s!="string"||!s)throw new c('"template.verification" should be a non-empty <string> (template message_id).',{code:"INVALID_PARAMETER"});i={template_verification:s};}return new Promise((o,a)=>{let u={onSuccess:l=>{n?z.bind(this)().getSession({refreshToken:true}).then(()=>{this.__user&&(this.__user[e+"_verified"]=true),o(`SUCCESS: "${e}" is verified.`);}).catch(g=>{a(g);}):o("SUCCESS: Verification code has been sent.");},onFailure:l=>{a(new c(l.message||"Failed to request verification code.",{code:l?.code}));}};n?B?.verifyAttribute(e,n,u):(u.inputVerificationCode=null,B?.getAttributeVerificationCode(e,u,i));})}function ei(e,t){return Zn.bind(this)("phone_number",e,t)}function ti(e,t){return Zn.bind(this)("email",e,t)}async function ri(e,t){await this.__connection;let r=h.Params(e,{email:s=>h.Email(s)},["email"]),n,i=t?.template?.verification;if(i!==void 0){if(typeof i!="string"||!i)throw new c('"template.verification" should be a non-empty <string> (template message_id).',{code:"INVALID_PARAMETER"});n={template_verification:i};}return new Promise(async(s,o)=>{z.bind(this)().createCognitoUser(r.email).cognitoUser.forgotPassword({onSuccess:u=>{s("SUCCESS: Verification code has been sent.");},onFailure:u=>{let{parsed:l,code:g}=At(u),f={UserNotFoundException:"NOT_EXISTS",InvalidParameterException:"INVALID_PARAMETER",NotAuthorizedException:"INVALID_REQUEST",LimitExceededException:"REQUEST_EXCEED",TooManyRequestsException:"REQUEST_EXCEED",CodeDeliveryFailureException:"CODE_DELIVERY_FAILURE"}[g]||l.code||g||"ERROR";o(new c(l.message,{code:f,cause:u}));}},n);})}async function ni(e){if(await this.__connection,!this.session)throw new c("User login is required.",{code:"INVALID_REQUEST"});let t=h.Params(e,{current_password:"string",new_password:"string"});if(!t?.current_password)throw new c('"current_password" is required to change password.',{code:"INVALID_PARAMETER"});if(!t?.new_password)throw new c('"new_password" is required to change password.',{code:"INVALID_PARAMETER"});return h.Password(t.current_password),h.Password(t.new_password),O.call(this)&&await In.bind(this)(t.current_password,t.new_password),new Promise((r,n)=>{B.changePassword(t.current_password,t.new_password,(i,s)=>{if(i){if(i?.code==="InvalidParameterException")n(new c("Invalid password parameter.",{code:"INVALID_PARAMETER"}));else if(i?.code==="NotAuthorizedException")n(new c("Incorrect password.",{code:"INVALID_REQUEST"}));else if(i?.code==="TooManyRequestsException"||i?.code==="LimitExceededException")n(new c("Too many attempts. Please try again later.",{code:"REQUEST_EXCEED"}));else {let{parsed:o}=At(i);n(o);}return}O.call(this)&&Tn.bind(this)().catch(o=>this.log("encryption:prune:failed",o)),r("SUCCESS: Password has been changed.");});})}async function ii(e){if(await this.__connection,!this.session)throw new c("User login is required.",{code:"INVALID_REQUEST"});let t=h.Params(e||{},{user_id:i=>h.UserId(i),email:i=>h.Email(i),address:i=>{if(!i)return "";if(typeof i=="string")return i;if(typeof i=="object")return JSON.stringify(i)},name:"string",gender:"string",birthdate:i=>i?h.Birthdate(i):"",phone_number:i=>i?h.PhoneNumber(i):"",email_public:"boolean",phone_number_public:"boolean",address_public:"boolean",gender_public:"boolean",birthdate_public:"boolean",misc:"string",picture:i=>i?h.Url(i):"",profile:i=>i?h.Url(i):"",family_name:"string",given_name:"string",middle_name:"string",nickname:"string",website:i=>i?h.Url(i):""});if(t&&typeof t=="object"&&!Object.keys(t).length)return this.user;t.email&&(t.preferred_username=this.service+"-"+G.hash(t.email));let r=[["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 i of r)if(t[i[0]]&&!this.__user[i[1]])throw new c(`${i[2]} "${i[0]}" to true.`,{code:"INVALID_REQUEST"})}let n=[];for(let i in t){if(t[i]===this.user[i]){n.push(i);continue}if(["email_public","phone_number_public","address_public","gender_public","birthdate_public","misc"].includes(i)){let o=t[i];typeof o=="boolean"&&(o=o?"1":"0"),t["custom:"+i]=o,n.push(i);}}for(let i of n)delete t[i];if(t.user_id)if(t.user_id===this.user.user_id)delete t.user_id;else return T.bind(this)("admin-edit-profile",{attributes:t},{auth:true});if(t&&typeof t=="object"&&Object.keys(t).length){let i=[];for(let s in t)i.push(new CognitoUserAttribute({Name:s,Value:t[s]}));return await new Promise((s,o)=>{B?.updateAttributes(i,(a,u)=>{a&&o([a?.code||a?.name,a?.message||"Failed to update user settings."]),s(u);});}),await z.bind(this)().getSession({refreshToken:true}),this.user}return this.user}async function si(e,t){e=j(e).data,e||(e={searchFor:"timestamp",condition:">",value:0},t||(t={}),t.ascending=false),await this.__connection;let r={user_id:i=>Array.isArray(i)?i.map(s=>h.UserId(s)):h.UserId(i),email:"string",phone_number:"string",locale:i=>{if(typeof i!="string"||typeof i=="string"&&i.length>5)throw new c('Value of "locale" should be a country code.',{code:"INVALID_PARAMETER"});return i},name:"string",address:"string",gender:"string",birthdate:i=>h.Birthdate(i),subscribers:"number",timestamp:"number",access_group:"number",approved:"string"},n=["searchFor","value"];if(e=h.Params(e,{searchFor:["user_id","name","email","phone_number","address","gender","birthdate","locale","subscribers","timestamp","access_group","approved"],condition:[">",">=","=","<","<=","gt","gte","eq","lt","lte",()=>"="],value:i=>{let s=r[e.searchFor];if(typeof s=="function")return s(i);if(typeof i!==s)throw new c(`Value does not match the type of "${e.searchFor}" index.`,{code:"INVALID_PARAMETER"});return i},range:i=>{let s=r[e.searchFor];if(typeof s=="function")return s(i);if(typeof i!==s)throw new c(`Range does not match the type of "${e.searchFor}" index.`,{code:"INVALID_PARAMETER"});return i}},n),e?.condition&&e?.condition!=="="&&e.hasOwnProperty("range"))throw new c("Conditions does not apply on range search.",{code:"INVALID_PARAMETER"});if(e.searchFor==="user_id"&&(e.condition!=="="||e.range))throw new c(`Conditions are not allowed on "${e.searchFor}"`,{code:"INVALID_PARAMETER"});if(typeof e?.value=="string"&&!e?.value)throw new c("Value should not be an empty string.",{code:"INVALID_PARAMETER"});if(typeof e?.searchFor=="string"&&!e?.searchFor)throw new c('"searchFor" should not be an empty string.',{code:"INVALID_PARAMETER"});return T.bind(this)("get-users",e,{auth:true,fetchOptions:t})}async function oi(e){await this.__connection;let t=await T.bind(this)("last-verified-email",e,{auth:true});return t.includes("SUCCESS")?(await z.bind(this)().getSession({refreshToken:true}),this.user):t}async function ai(e){return await this.__connection,e=h.Params(e,{username:h.Email,redirect:h.Url},["username"]),await T.bind(this)("request-username-change",e,{auth:true})}var Le=null,ci=typeof SubmitEvent<"u",ia=typeof HTMLFormElement<"u",et=Y(),yr=0;function ui(e){if(!e)return null;let t=Number(e);if(Number.isFinite(t))return Math.max(0,t*1e3);let r=Date.parse(e);return Number.isNaN(r)?null:Math.max(0,r-Date.now())}function br(e,t){return t>0?e/t*100:0}var li=e=>{let{auth:t,type:r,endpoints:n,stable:i}=e,s=n[0],o=n[1];if(yr++,r==="admin"){let a=Object.entries(s).filter(([u,l])=>u.includes(t?"_private":"_public")&&u!=="get_users_private"&&u!=="service_public"&&typeof l=="string").map(([,u])=>u);if(!a.length)throw new c("No available admin gateways.",{code:"INVALID_REQUEST"});return a[yr%a.length]}if(r==="record"){let a=Object.entries(o).filter(([u,l])=>u.includes(t?"record_private":"record_public")&&typeof l=="string").map(([,u])=>u);if(!a.length)throw new c("No available record gateways.",{code:"INVALID_REQUEST"});return i?a[0]:a[yr%a.length]}throw new c("Invalid gateway type.",{code:"INVALID_REQUEST"})};async function sa(e,t,r){let n=await Promise.all([this.admin_endpoint,this.record_endpoint]),i=n[0],s=n[1],o=e.split("?"),a=o.length>1?"?"+o[1]:"";switch(e=o[0],e){case "get-users":return i.get_users_private+e+a;case "service":return i.service_public+e+a;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 "delete-newsletter-group":case "newsletter-group-endpoint":case "invitation-list":case "csr":case "csr-poll":case "csr-cancel":case "csr-finalize":return li.bind(this)({auth:t,type:"admin",endpoints:n})+e+a;case "post-record":return (t?s.post_private:s.post_public)+e+a;case "get-records":return (t?s.get_private:s.get_public)+e+a;case "del-files":case "del-records":return s.del_private+e+a;case "store-subscription":case "get-vapid-public-key":case "push-notification":case "delete-subscription":case "subscription":case "get-subscription":case "get-table":case "get-tag":case "get-uniqueid":case "get-index":case "get-signed-url":case "extract-file-text":case "grid-query":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 li.bind(this)({auth:t,type:"record",endpoints:n,stable:r})+e+a;default:return h.Url(e)+a}}var Ze={};function di(){Le&&(Le.terminate(),Le=null);}async function T(e,t=null,r,n){this.log("request",{url:e,data:t,options:r,_etc:n||{}}),r=r||{};let{auth:i=false,method:s="post",bypassAwaitConnection:o=false}=r;s=s.toUpperCase();let a=null,u=t?.service||this.service,l=t?.owner||this.owner,g=null,f=await sa.bind(this)(e,!!i,!!r.stableGateway);if(!o&&(a=await this.__connection,!a))throw new c("Invalid connection. The service could have been disabled, or has a restricted CORS.",{code:"INVALID_REQUEST"});let d=r?.tokenHeaders?.idToken===true;(i||d)&&(g=await Ce.bind(this)());let p={},{fetchMore:m=false,progress:y}=r?.fetchOptions||{};if(r?.fetchOptions&&Object.keys(r.fetchOptions).length){for(let v of ["limit","startKey","ascending"])if(r.fetchOptions.hasOwnProperty(v)){if(v==="startKey"&&r.fetchOptions[v]===null)continue;p[v]=r.fetchOptions[v];}p=h.Params(p,{limit:v=>{if(typeof v!="number")throw new c("Fetch limit should be a number.",{code:"INVALID_REQUEST"});if(v>1e3)throw new c("Fetch limit should be below 1000.",{code:"INVALID_REQUEST"});return v},startKey:v=>v,ascending:"boolean"});}let _=n?.ignoreService?{}:{service:u,owner:l};Object.assign(_,p),t=j(t).data,t?t&&typeof t=="object"&&(t=Object.assign(_,t)):t=_;let w=`${s}:${i?"auth":"public"}:${e}`,b=(()=>{if(t&&typeof t=="object"&&Object.keys(t).length&&!(et&&t instanceof FormData)){let v=function(U){return typeof U=="object"&&U!==null?Object.keys(U).sort().reduce((L,V)=>(typeof U[V]=="object"&&U[V]!==null?L[V]=v(U[V]):L[V]=U[V],L),{}):U};return G.hash(w+"/"+JSON.stringify(v(t)))}return G.hash(w+"/"+u)})(),{requestKey:E,requestKeyWithStartKey:k}=oa.bind(this)({params:t,url:e,fetchMore:m,hashedParams:b});if(!E||E&&typeof E=="object")return E;if(this.log("requestKey",k),typeof k=="string"&&Ze[k]instanceof Promise)return this.log("request:returning pending",k),Ze[k];let A={Accept:"*/*"};if(Object.prototype.hasOwnProperty.call(r,"contentType")&&r.contentType!==void 0){let v=r.contentType===null?"application/x-www-form-urlencoded":r.contentType;v&&(A["Content-Type"]=v);}else A["Content-Type"]="application/json";if(g&&(A.Authorization=g),r?.tokenHeaders){let v=(V,de)=>typeof V=="string"?V:V===true?de:null,U=v(r.tokenHeaders.accessToken,this.session?.accessToken?.jwtToken||null),L=v(r.tokenHeaders.idToken,this.bearerToken||this.session?.idToken?.jwtToken||g||null);U&&(A["X-Access-Token"]=U),L&&(A["X-Id-Token"]=L);}let x={public_identifier:this.__public_identifier,service:u,owner:l};A["Content-Meta"]=JSON.stringify(x),r.revalidate&&(A["Cache-Control"]="no-cache",A.Pragma="no-cache");let C={headers:A};if(r?.responseType&&(C.responseType=r.responseType),s==="GET"){if(t){let v=[];if(et&&t instanceof FormData?v=Array.from(t.entries()).map(([U,L])=>{let V=typeof L=="string"?L:L.name;return encodeURIComponent(U)+"="+encodeURIComponent(V)}):v=Object.keys(t).map(U=>{let L=t[U];return typeof L!="string"&&(L=JSON.stringify(L)),encodeURIComponent(U)+"="+encodeURIComponent(L)}),v.length){let U=f.includes("?")?f.endsWith("?")||f.endsWith("&")?"":"&":"?";f+=U+v.join("&");}}C.body=null;}else if(et&&t instanceof FormData)C.body=t;else if(A["Content-Type"]==="application/x-www-form-urlencoded"&&t&&typeof t=="object"){let v=new URLSearchParams;for(let U of Object.keys(t)){let L=t[U];v.append(U,typeof L=="string"?L:JSON.stringify(L));}C.body=v.toString();}else typeof t=="string"?C.body=t:C.body=t?JSON.stringify(t):null;if(C.method=s,Le===null){let v={batchSize:this.requestBatchSize,breakWhenError:false,onProgress:U=>{this.onBatchProcess.forEach(L=>L(U));}};Le=new Wi(v);}return this.log("request-opt",C),new Promise((v,U)=>{Le.add([async()=>{let L=fi.bind(this)(f,C,y);Ze[k]=L;try{let V=la.bind(this)({hashedParam:E,requestKeyWithStartKey:k,url:e,fetched:await L});return delete Ze[k],this.log("request:end",V),v(V),V}catch(V){throw delete Ze[k],this.log("request:err",V),U(V),V}}]);})}function oa(e){let{params:t={},url:r,fetchMore:n=false,hashedParams:i}=e||{};if(t.startKey){if(!(typeof t.startKey=="object"&&Object.keys(t.startKey).length)&&t.startKey!=="start"&&t.startKey!=="end")throw new c(`"${t.startKey}" is invalid startKey key.`,{code:"INVALID_PARAMETER"});t.startKey==="start"&&(n=false,delete t.startKey);}if(!n){if(this.__cached_requests?.[r]?.[i]&&delete this.__cached_requests[r][i],this.__startKeyHistory?.[r]?.[i]){if(Array.isArray(this.__startKeyHistory[r][i])&&this.__startKeyHistory[r][i].length)for(let u of this.__startKeyHistory[r][i]){let l=i+G.hash(u);this.__cached_requests?.[r]&&this.__cached_requests?.[r]?.[l]&&delete this.__cached_requests[r][l];}delete this.__startKeyHistory[r][i];}return {requestKeyWithStartKey:i,requestKey:i}}if(!Array.isArray(this.__startKeyHistory?.[r]?.[i]))return {requestKeyWithStartKey:i,requestKey:i};let s=this.__startKeyHistory[r][i],o=s[s.length-1],a=i;if(o){if(o==="end")return {requestKey:{list:[],startKey:"end",endOfList:true,startKeyHistory:s},requestKeyWithStartKey:a};a+=G.hash(o),t.startKey=JSON.parse(o);}return this.__cached_requests?.[r]?.[a]?{requestKey:this.__cached_requests[r][a],requestKeyWithStartKey:a}:{requestKeyWithStartKey:a,requestKey:i}}function aa(e){let t=r=>r&&typeof r=="object"&&r.encrypted?Object.assign({},r,{data:null}):r;return Array.isArray(e)?e.map(t):e&&typeof e=="object"?Array.isArray(e.list)?Object.assign({},e,{list:e.list.map(t)}):t(e):e}function fi(e,t,r){return new Promise((n,i)=>{let s=new XMLHttpRequest;s.open(t.method||"GET",e);for(var o in t.headers||{})s.setRequestHeader(o,t.headers[o]);t.responseType&&(s.responseType=t.responseType),s.onload=()=>{if(s.status<400)if(t.responseType=="json"||t.responseType=="blob")n(s.response);else {let a=s.responseText;try{a=JSON.parse(a);}catch{}n(a);}else if(s.status===429){let a=s.getResponseHeader("Retry-After"),u=ui(a);u!==null?setTimeout(()=>{fi(e,t,r).then(n,i);},u):i("Too many requests");}else {let a=s.status,u=["INVALID_CORS","INVALID_REQUEST","SERVICE_DISABLED","INVALID_PARAMETER","ERROR","EXISTS","NOT_EXISTS"],l=t.responseType=="blob"?s.response:s.responseText;try{l=JSON.parse(l);}catch{}if(typeof l=="string"){let g=l.split(":"),f=g.splice(0,1)[0].trim(),d=g.join(":").trim();i(new c(d||l,{code:u.includes(f)?f:"ERROR"}));}else if(typeof l=="object"&&l?.message){let g=l?.code||(a?a.toString():null)||"ERROR",f=l.message,d=l?.cause;typeof f=="string"&&(f=f.trim()),i(new c(f,{cause:d,code:g}));}else i(l);}},s.onerror=()=>i("Network error"),s.onabort=()=>i("Aborted"),s.ontimeout=()=>i("Timeout"),typeof r=="function"&&(s.onprogress=a=>{r({status:"download",progress:br(a.loaded,a.total),loaded:a.loaded,total:a.total,abort:()=>s.abort()});},s.upload&&(s.upload.onprogress=a=>{r({status:"upload",progress:br(a.loaded,a.total),loaded:a.loaded,total:a.total,abort:()=>s.abort()});})),s.send(t.body);})}function la(e){let{hashedParam:t,requestKeyWithStartKey:r,url:n,fetched:i}=e;if(!i?.startKey)return i;this.__startKeyHistory.hasOwnProperty(n)||(this.__startKeyHistory[n]={}),this.__startKeyHistory[n].hasOwnProperty(t)||(this.__startKeyHistory[n][t]=[]);let s=i.startKey==="end"?"end":JSON.stringify(i.startKey);return this.__startKeyHistory[n][t].includes(s)||this.__startKeyHistory[n][t].push(s),this.__cached_requests?.[n]||(this.__cached_requests[n]={}),this.__cached_requests[n][r]=i,Object.assign({startKeyHistory:this.__startKeyHistory[n][t]},i)}async function tt(e,t){await this.__connection;let{record_id:r,service:n=this.service,progress:i}=t;if(!r)throw new c('"record_id" is required.',{code:"INVALID_PARAMETER"});if(ci&&e instanceof SubmitEvent&&(e=e.target),ia&&e instanceof HTMLFormElement&&(e=new FormData(e)),!et||!(e instanceof FormData))throw new c('"fileList" should be a FormData or HTMLFormElement.',{code:"INVALID_PARAMETER"});let o={reserved_key:Re(),service:n,request:"post"};t?.record_id&&(o.id=t.record_id);let a,u=(p,m,y)=>new Promise((_,w)=>{a=new XMLHttpRequest,a.open("POST",p),a.onload=()=>{let b=a.responseText;try{b=JSON.parse(b);}catch{}if(a.status>=200&&a.status<300)_(b);else if(a.status===429){let E=a.getResponseHeader("Retry-After"),k=ui(E);k!==null?setTimeout(()=>{u(p,m,y).then(_,w);},k):w("Too many requests");}else w(b);},a.onerror=()=>w("Network error"),a.onabort=()=>w("Aborted"),a.ontimeout=()=>w("Timeout"),a.upload&&typeof y=="function"&&(a.upload.onprogress=y),a.send(m);});function l(p){let m="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";if(p===0)return m[0];let y="";for(;p>0;)y=m[p%62]+y,p=Math.floor(p/62);return y}let g=[],f=[],d=[];for(let[p,m]of e.entries()){if(!(m instanceof File))continue;let y=await Mn.bind(this)(r,p,m),_=y.file,w=y.key,b=Object.assign({key:w+"/"+_.name,sizeKey:l(_.size),contentType:_.type||null},o),{fields:E=null,url:k,cdn:A}=await T.bind(this)("get-signed-url",b,{auth:!!this.__user});d.push(A);let D=new FormData;for(let x in E)D.append(x,E[x]);D.append("file",_);try{await u(k,D,typeof i=="function"?x=>i({status:"upload",progress:br(x.loaded,x.total),currentFile:m,completed:g,failed:f,loaded:x.loaded,total:x.total,abort:()=>a.abort()}):null),g.push(m);}catch{f.push(m);}}return {completed:g,failed:f,bin_endpoints:d}}var Rt={};function S(e){let{preventMultipleCalls:t=false}=e||{};return function(r,n,i){let s=i.value;i.value=function(...o){let a=o[0],u=true,l=null,g="",f={},d=false;if(ci&&a instanceof SubmitEvent){a.preventDefault();let w=window.location.href;l=a.target;let b=new URL(l.action);g=b.href;let E=g?g.match(/(?<=\{).*?(?=\})/g):"";if(E)for(let k of E){if(!k)continue;let A=l.querySelector(`[name="${k}"]`);if(A)if(A.type==="file")for(let D=0;D<=A.files.length-1;D++)A.files[D]&&(f[k]||(f[k]=[]),f[k].push(new Promise((x,C)=>{let v=new FileReader;v.onload=function(){x(v.result);},v.readAsDataURL(A.files[D]),v.onerror=C;})));else g=g.replace(`{${k}}`,A.value);}l.getAttribute("action")===null?u=false:d=b.href===w;}let p=async w=>{if(g)for(let b in f)f[b].length&&(g=g.replace(`{${b}}`,(await Promise.all(f[b])).join(",")));if(l&&u){let b=O.call(this)?aa(w):w;window.sessionStorage.setItem(`${this.service}:${G.hash(g)}`,JSON.stringify(b)),d?window.location.replace(g):window.location.href=g;}return w},m,y=w=>{throw w instanceof c?w.name=n+"()":w=w instanceof Error?w:new c(w,{name:n+"()"}),w},_=async()=>{try{if(m=s.bind(this)(...o),m instanceof Promise){let w=await m;return p(w)}return p(m)}catch(w){throw y(w)}};if(t){let w=`${n}:${this?.__public_identifier||""}:${this?.service||""}:${this?.owner||""}`;return Rt?.[w]||(Rt[w]=_().finally(()=>{delete Rt[w];})),Rt[w]}return _()};}}async function gi(){await this.__connection;let e=`${this.service}:${G.hash(window.location.href.split("?")[0])}`,t=window.sessionStorage.getItem(e);if(window.sessionStorage.removeItem(e),t!==null){try{t=JSON.parse(t);}catch{}return t}return null}var ca=256,ua=256,da=256,pi=256,fa="\u{10FFFF}",ga=/[\u0000-\u001F\u007F]|\u{10FFFF}/u,pa={"/":"%2F","!":"%21","*":"%2A","#":"%23"},ha={"%2F":"/","%21":"!","%2A":"*","%23":"#"};function ma(e){return e.replace(/%/g,"%25").replace(/[\/!*#]/g,r=>pa[r]||r)}function le(e){return typeof e!="string"?e:e.replace(/%(2F|21|2A|23)/gi,r=>{let n=r.toUpperCase();return ha[n]||r}).replace(/%25/gi,"%")}function fe(e,t,r={}){let{allowEmpty:n=false,maxLength:i,blockKeyDelimiters:s=false,disallowLeadingDollar:o=false,onlyAlphanumeric:a=false}=r;if(typeof e!="string")throw new c(`"${t}" should be type: <string>.`,{code:"INVALID_PARAMETER"});if(a&&/[^a-zA-Z0-9]/.test(e))throw new c(`"${t}" should only contain alphanumeric characters.`,{code:"INVALID_PARAMETER"});if(!n&&e.length===0)throw new c(`"${t}" is required.`,{code:"INVALID_PARAMETER"});if(i&&e.length>i)throw new c(`"${t}" should be <= ${i} characters.`,{code:"INVALID_PARAMETER"});if(ga.test(e)||e.includes(fa))throw new c(`"${t}" cannot include control characters or unsupported sentinel characters.`,{code:"INVALID_PARAMETER"});if(s&&(e=ma(e),i&&e.length>i))throw new c(`"${t}" should be <= ${i} characters. "/", "!", "*", "#" and "%" count as 3 characters each.`,{code:"INVALID_PARAMETER"});if(o&&e.startsWith("$"))throw new c(`"${t}" cannot start with "$".`,{code:"INVALID_PARAMETER"});return e}function Oe(e,t="table.name",r={}){return fe(e,t,{allowEmpty:r.allowEmpty===true,maxLength:ca,blockKeyDelimiters:true})}function Tt(e,t="tag",r={}){return fe(e,t,{allowEmpty:r.allowEmpty===true,maxLength:ua,blockKeyDelimiters:true})}function rt(e,t="index.name",r={}){return fe(e,t,{allowEmpty:r.allowEmpty===true,maxLength:da,blockKeyDelimiters:true,disallowLeadingDollar:true})}function hi(e,t="index.value"){return fe(e,t,{allowEmpty:true,maxLength:pi})}function _r(e){return typeof e=="string"&&e.slice(-1)==="."}function wr(e,t){return fe(e,t,{allowEmpty:true,maxLength:pi,blockKeyDelimiters:true})}function mi(e){if(!e.record_id&&!e.unique_id)return null;let t={};return e?.service&&(t.service=e.service),e?.owner&&(t.owner=e.owner),e?.record_id?t.record_id=fe(e.record_id,"record_id",{allowEmpty:false,onlyAlphanumeric:true}):e?.unique_id&&(t.unique_id=e.unique_id),t}function Er(e){if(e===void 0)return 0;if(typeof e=="number"){if(e>99||e<0)throw new c('"table.access_group" value should be within a range of 0 ~ 99.',{code:"INVALID_REQUEST"})}else if(typeof e=="string"){if(e={"*":"private",private:"private",public:0,authorized:1,admin:99}[e],e===void 0)throw new c('"table.access_group" is invalid.',{code:"INVALID_PARAMETER"})}else throw new c('"table.access_group" should be type: <number | string>.',{code:"INVALID_PARAMETER"});if(!this.__user&&e)throw new c("Unsigned users have no access to records with access group.",{code:"INVALID_REQUEST"});return e}var It=4503599627370496;function Pt(e){if(typeof e=="number"){if(e>It||e<-It)throw new c(`Number value should be within range -${It} ~ +${It}`,{code:"INVALID_PARAMETER"});return e}if(typeof e=="boolean")return e;if(typeof e=="string")return hi(e,"index.value");throw new c('"index.value" should be type: <number | boolean | string>.',{code:"INVALID_PARAMETER"})}function yi(e,t){if(!t.index||!("value"in t.index))throw new c('"index.value" is required.',{code:"INVALID_PARAMETER"});if(t.index.name==="$record_id")throw new c(`Cannot do "index.range" on ${t.index.name}`,{code:"INVALID_PARAMETER"});if(typeof t.index.value!=typeof e)throw new c('"index.range" type should match the type of "index.value".',{code:"INVALID_PARAMETER"});return typeof e=="string"?_r(t.index.name)?wr(e,"index.range"):hi(e,"index.range"):e}var St={},ya=10080*60,ba=3600,bi=2;function _a(e,t){if(!t)return String(bi);let r=Math.max(60,e-300)*1e3;return "g"+bi+"w"+Math.floor(Date.now()/r)}function wa(e){if(!this.user?.user_id)return false;let t=e[6]==="**"?"**":parseInt(e[6]),r=this.user?.access_group??-1;return !(this.user.user_id!==e[3]&&(t==="**"||r<t))}function Ea(e){if(typeof e=="string"){if(e.startsWith("!J%"))try{return JSON.parse(e.substring(3))}catch{return e}return e==="!D%{}"?{}:e==="!L%[]"?[]:e}if(e&&typeof e=="object"&&!Array.isArray(e)&&typeof e.__json__=="string"&&Object.keys(e).length===1)try{return JSON.parse(e.__json__)}catch{}return e}async function _i(e){return typeof e=="string"?e:e&&typeof e.text=="function"?await e.text():await new Promise((t,r)=>{try{let n=new FileReader;n.onload=()=>t(n.result),n.onerror=()=>r(n.error||new Error("Failed to read blob")),n.readAsText(e);}catch(n){r(n);}})}async function Se(e,t,r=false,n=false,i=false){let s={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:{}},o=false,a=[],u=null;function l(d){let p=d=="**"?"private":parseInt(d);return p=p==0?"public":p==1?"authorized":p==99?"admin":p,p}let g={ip:d=>{let p=d.split("#"),m=p[0];p.length>1&&(s.unique_id=p.slice(1).join("#")),m.slice(-1)==="R"?(s.readonly=true,m=m.slice(0,-1)):s.readonly=false,/^\d{1,3}-\d{1,3}-\d{1,3}-\d{1,3}$/.test(m)&&(m=m.split("-").join("."),o=true),s.ip=m;},rec:d=>{if(!d)return;s.record_id=d;let p=d.substring(0,d.length-9),m=se(p);s.uploaded=m;},usr:d=>{s.user_id=d;},tbl:d=>{if(d&&!s.table.name){let p=d.split("/");s.table.name=le(p[0]),s.table.access_group=l(p[2]),p?.[3]&&(s.table.subscription.is_subscription_record=true);}},usr_tbl:d=>{let p=d.split("/");s.user_id||(s.user_id=p[0]),s.table.name||(s.table.name=le(p[1]),s.table.access_group=l(p[3]),p?.[4]&&(s.table.subscription.is_subscription_record=true));},idx:d=>{if(!d)return;let p=d.split("!"),m=le(p.splice(0,1)[0]),y=Aa("!"+p.join("!"));s.index={name:m,value:y};},ref:d=>{d&&(s.reference=d.split("/")[0]);},tags:d=>{s.tags=Array.isArray(d)?d.map(p=>le(p)):d;},upd:d=>{s.updated=d;},acpt_mrf:d=>{s.source.prevent_multiple_referencing=!d;},ref_limt:d=>{s.source.referencing_limit=d;},rfd:d=>{s.referenced_count=d;},bin:async d=>{let p={},m=s?.reference||null;if(Array.isArray(d)){let y=await Promise.all(d.map(async _=>{try{let w=_.split("/").slice(3).join("/"),b=w.split("/");if(b.length<12)return null;let E=b[b.length-1],k=b[10];if(k==="__data__"&&E==="__json__.json")return {isDataFile:!0,rawUrl:_};if(nr(k,E))return {isDataFile:!0,rawUrl:_};let A=wt(k),D=b[9],x=b[8],C=l(b[6]),v=_,U=C!=="public"&&wa.call(this,b)?{expires:ba,browserCache:ya}:null;if(C!=="public"&&!i)try{v=await Pe.bind(this)(_,{dataType:"endpoint",_ref:m});}catch(V){console.error("Error getting signed url for private file:",V),v=_;}let L={access_group:C,filename:E,url:v,path:w,size:A?A.plainSize:se(D),uploaded:se(x),getFile:(V,de)=>{let ie={dataType:V||"download",progress:de,_ref:m},M=()=>Pe.bind(this)(v,Object.assign({},ie,{_update:L}));return U?Pe.bind(this)(_,Object.assign({},ie,U)).catch(()=>M()):M()}};return A&&(L.encrypted=!0,L.stored_size=se(D)),{pathKey:A?A.key:k,obj:L}}catch{return null}}));for(let _ of y)if(_&&!_.isDataFile){if(p[_.pathKey]){p[_.pathKey].push(_.obj);continue}p[_.pathKey]=[_.obj];}}s.bin=p;},prv_acs:d=>{for(let p in d)["notify_subscribers","upload_to_feed","feed_referencing_records","notify_referencing_records"].includes(p)?s.table.subscription[p]=d[p]:p==="referencing_index_restrictions"&&Array.isArray(d[p])?s.source[p]=d[p].map(y=>y&&typeof y=="object"&&typeof y.name=="string"?Object.assign({},y,{name:le(y.name)}):y):s.source[p]=d[p];},data:async d=>{let p={access_group:s.table.access_group,table_name:s.table.name,user_id:s.user_id,record_id:s.record_id,unique_id:s.unique_id,ctUrl:u},m=()=>{O.call(this)&&(s.encrypted={status:"failed",reason:"DATA_UNAVAILABLE"});},y=async w=>{if(n||!O.call(this)&&!yt(w))return w;let b=await mn.bind(this)(w,p);return b.flag&&(s.encrypted=b.flag),b.value},_=Ea(d);if(_!==d){s.data=await y(_);return}if(d&&typeof d=="object"&&!Array.isArray(d)&&typeof d.__data__=="string"&&Object.keys(d).length===1&&d.__data__.endsWith("/__data__/__json__.json")){let w=d.__data__,b=a.find(E=>E.endsWith(w))||null;if(!b&&!r&&m(),b){if(r){s.data=d;return}try{let E=await Pe.bind(this)(b,{dataType:"blob",_ref:s.reference||null}),k=await _i(E);s.data=await y(JSON.parse(k));}catch(E){console.error("Failed to fetch offloaded record data:",E),s.data=null,m();}return}}s.data=await y(d);}};if(e.record_id)return e;if(Array.isArray(e.bin))for(let d of e.bin)try{if(typeof d!="string")continue;let p=d.split("/").slice(3);p.length>=12&&p[10]==="__data__"&&p[p.length-1]==="__json__.json"&&a.push(d),p.length>=12&&nr(p[10],p[p.length-1])&&(u=d);}catch{}let f=[];for(let d in g)if(e.hasOwnProperty(d)){let p=g[d](e[d]);p instanceof Promise&&f.push(p);}return o&&(s.user_id="anonymous:"+s.user_id),await Promise.all(f),s}function Aa(e){let t=e.substring(3);switch(e.substring(0,3)){case "!S%":return t;case "!N%":let n=t.split("."),i=Number(n[0])-4503599627370496;return n.length===1?i:parseFloat(i.toString()+"."+n[1]);case "!B%":return t==="1";case "!L%":case "!D%":try{return JSON.parse(t)}catch{throw new c("Value parse error.",{code:"PARSE_ERROR"})}default:return e}}async function wi(e){let{endpoints:t}=e;if(typeof t=="string"&&(t=[t]),!Array.isArray(t))throw new c('"endpoints" should be type: array | string.',{code:"INVALID_PARAMETER"});let r=await T.bind(this)("del-files",{endpoints:t,storage:"records"},{auth:true,method:"post"}),n=[];for(let i in r)n.push(Se.bind(this)(r[i]));return Promise.all(n)}async function Pe(e,t){if(typeof e!="string")throw new c('"url" should be type: string.',{code:"INVALID_PARAMETER"});let r=e,n=e.split("?"),i=n.shift()||"",s=n.length?"?"+n.join("?"):"",o=h.Url(i);e=o+s;let a=false,u=o.split("/"),g=u[2].split("."),f=null;g.length===3&&g[1]==="skapi"&&(f=g[0],a=true);let d=u.slice(3),p=false;if(!a&&(d[0]==="auth"||d[0]==="publ"))try{h.UserId(d[2]),h.UserId(d[3]),p=d[0]=="auth",a=!0;}catch{throw new c("Invalid file url.",{code:"INVALID_PARAMETER"})}let m=f?null:d[1];if(t=h.Params(t,{expires:["number",()=>0],browserCache:["number",()=>0],refresh:["boolean",()=>false],dataType:["base64","blob","endpoint","text","info",()=>"download"],progress:["function","undefined",null],_ref:[null,"string"],_update:E=>E}),t?.dataType==="info")return {url:e,filename:d[d.length-1],fileKey:d[d.length-2],access_group:d[6]==="**"?"private":d[6]==="01"?"authorized":d[6]==="00"?"public":parseInt(d[6]),uploader:d[3],record_id:d[4]==="records"?d[5]:"N/A",filesize:se(d[9]),uploaded:se(d[8])};let y=e.split("/").slice(-1)[0],_=t.expires;if(_){if(!a)throw new c("Expires option can only be used on skapi cdn endpoints.",{code:"INVALID_PARAMETER"});if(_<0)throw new c('"config.expires" should be > 0. (seconds)',{code:"INVALID_PARAMETER"});let E={request:f?"get-host":"get",id:f||d[5],key:r.split("?")[0],expires:_};m&&(E.service=m);let k=t.browserCache,A={auth:true};if(k){if(k<0)throw new c('"config.browserCache" should be > 0. (seconds)',{code:"INVALID_PARAMETER"});A.method="get",A.stableGateway=true,E.browser_cache=k;let D=this.session?.idToken?.payload?.sub||this.user?.user_id;D&&(E.uid=D),E.nocache=_a(_,t.refresh);}e=(await T.bind(this)("get-signed-url",E,A)).url;}else if(p){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 z.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(x){throw this.log("getFile:new token error",x),new c("User login is required.",{code:"INVALID_REQUEST"})}}let k=this.bearerToken||this.session?.idToken?.jwtToken;if(!k||!this.user?.user_id)throw new c("User login is required.",{code:"INVALID_REQUEST"});e+=`${e.includes("?")?"&":"?"}t=${encodeURIComponent(k)}`;let A=d[6]==="**"?"**":parseInt(d[6]),D=this.user?.access_group??-1;if(this.user.user_id!==d[3]&&(A==="**"||D<A)){let x=d[5];if(this.__private_access_key[x]&&typeof this.__private_access_key[x]=="string")e+=`&p=${encodeURIComponent(this.__private_access_key[x])}`;else if(this.owner!==this.host)try{let C=await this.requestPrivateRecordAccessKey({record_id:x,reference_id:t?._ref});e+=`&p=${encodeURIComponent(C)}`;}catch{}}}if((O.call(this)?gr(e):null)&&t?.dataType!=="endpoint"&&t?.dataType!=="info"){let E=await T.bind(this)(e,null,{method:"get",contentType:null,responseType:"blob",fetchOptions:{progress:t?.progress}},{ignoreService:true}),k=await Fn.bind(this)(e,E);if(t?.dataType==="blob")return k;if(t?.dataType==="text")return await _i(k);if(t?.dataType==="base64")return await new Promise((x,C)=>{let v=new FileReader;v.onloadend=()=>x(v.result),v.onerror=()=>C(v.error),v.readAsDataURL(k);});let A=URL.createObjectURL(k),D=document.createElement("a");return D.href=A,document.body.appendChild(D),D.setAttribute("download",y),D.click(),document.body.removeChild(D),setTimeout(()=>URL.revokeObjectURL(A),6e4),null}if(t?.dataType==="endpoint")return t._update&&(t._update.url=e),e;if(t?.dataType==="download"){let E=document.createElement("a");return E.href=e,document.body.appendChild(E),E.setAttribute("download",y),E.target="_blank",E.click(),document.body.removeChild(E),null}return new Promise(async(E,k)=>{try{let A=await T.bind(this)(e,null,{method:"get",contentType:null,responseType:t?.dataType==="text"?"text":"blob",fetchOptions:{progress:t?.progress}},{ignoreService:!0});if(t?.dataType==="base64"){let D=new FileReader;D.onloadend=()=>E(D.result),D.readAsDataURL(A);}else E(A);}catch(A){if(t?.browserCache&&!t?.refresh)try{E(await Pe.bind(this)(r,Object.assign({},t,{refresh:!0})));return}catch(D){k(D);return}k(A);}})}function kt(e,t){return `${e||this.service}/${t||this.owner}`}function Ar(e,t){let r=this.__my_unique_ids[e];return r?r[t]:void 0}function Ei(e,t,r){this.__my_unique_ids[e]||(this.__my_unique_ids[e]={}),this.__my_unique_ids[e][t]=r;}function Ra(e,t){this.__my_unique_ids[e]&&delete this.__my_unique_ids[e][t];}function Ai(e,t){return !t||t.table===void 0?e:Object.assign({},e,{table:t.table})}async function nt(e){if(await this.__connection,!this.__user&&this.connection?.opt?.require_login===true)throw new c(`This project requires users to sign in before reading its database, so "${e}" is not available to a signed-out visitor.`,{code:"REQUIRE_LOGIN"})}async function Ri(e,t=false){e=j(e,{ignoreEmpty:true}).data||{};let r=kt.bind(this)(e?.service,e?.owner),n="",i=mi(e);if(i){if(e=i,n=e.record_id||e.unique_id,typeof n=="string"){typeof this.__private_access_key?.[n]=="string"&&(e.private_key=this.__private_access_key?.[n]||void 0);let s=Ar.bind(this)(r,n);s&&(t?Ra.bind(this)(r,n):e.record_id=s);}}else {let s=await W.bind(this)(),o=e?.reference,a=false;typeof o=="object"&&Object.keys(o).length&&(o?.record_id||o?.unique_id?(n=o.record_id||o.unique_id,n&&typeof this.__private_access_key?.[n]=="string"&&(e.private_key=this.__private_access_key?.[n]||void 0),e.reference=n):o?.user_id&&(a=o.user_id===this.user?.user_id,e.reference=o.user_id)),typeof e?.table=="string"&&(e.table={name:e.table,access_group:0}),e.index&&e.index.hasOwnProperty("range")&&e.index.hasOwnProperty("condition")&&delete e.index.range;let u=l=>({table:{name:g=>Oe(g,"table.name"),access_group:Er.bind(this),subscription:g=>h.UserId(g,'User ID in "subscription"')},reference:"string",index:{name:["$updated","$uploaded","$referenced_count","$user_id",g=>rt(g,"index.name")],value:g=>{let f={$updated:"number",$uploaded:"number",$referenced_count:"number",$user_id:h.UserId};if(f.hasOwnProperty(l.index.name)){let d=f[l.index.name];if(typeof d=="function")return d(g);if(d!==typeof g)throw new c(`"index.value" should be type: ${d}.`,{code:"INVALID_PARAMETER"});return g}return typeof g=="string"&&!g?"":typeof g=="string"&&_r(l.index.name)?wr(g,"index.value"):Pt(g)},condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq"],range:g=>yi(g,l)},tag:g=>{if(g==null)return g;if(typeof g=="string")return Tt(g,"tag");throw new c('"tag" should be type: string.',{code:"INVALID_PARAMETER"})},private_key:"string"});e=h.Params(e||{},u(e),a||s?[]:["table"],{ignoreEmpty:true});}return {query:e,is_reference_fetch:n}}async function Ii(e,t){await this.__connection,await nt.call(this,"getRecords");let r=await Ri.bind(this)(e),n=r.is_reference_fetch,i=await T.bind(this)("get-records",r.query,{fetchOptions:t,auth:!!this.__user,method:this.__user?"post":"get"});n&&i?.reference_private_key&&typeof i.reference_private_key=="string"&&(this.__private_access_key[n]=i.reference_private_key);let s=[];for(let o in i.list)s.push(Se.bind(this)(i.list[o]));return i.list=await Promise.all(s),i}function Ti(e){let t="",r=[],n=kt.bind(this)(e?.service,e?.owner),i=h.Params(e||{},{record_id:o=>{let a=typeof o=="string"?Ar.bind(this)(n,o):void 0;return a||fe(o,"record_id",{allowEmpty:false})},unique_id:["string",null],readonly:"boolean",table:{name:o=>Oe(o,"table.name"),subscription:[null,{is_subscription_record:"boolean",upload_to_feed:"boolean",notify_subscribers:"boolean",feed_referencing_records:"boolean",notify_referencing_records:"boolean"}],access_group:Er.bind(this)},source:{referencing_limit:o=>{if(o===null)return null;if(typeof o=="number"){if(0>o)throw new c('"reference_limit" should be >= 0',{code:"INVALID_PARAMETER"});if(o>4503599627370546)throw new c('"reference_limit" should be <= 4503599627370546',{code:"INVALID_PARAMETER"});return o}throw new c('"reference_limit" should be type: <number | null>',{code:"INVALID_PARAMETER"})},prevent_multiple_referencing:"boolean",can_remove_referencing_records:"boolean",only_granted_can_reference:"boolean",allow_granted_to_grant_others:"boolean",referencing_index_restrictions:o=>{if(o===void 0)return;if(!o||Array.isArray(o)&&!o.length)return null;let a={name:l=>rt(l,'"name" in "index_restrictions"'),value:l=>Pt(l),condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne",()=>null],range:l=>{if(l!==null&&typeof o.value!=typeof l)throw new c('Index restriction "range" type should match the type of "value".',{code:"INVALID_PARAMETER"});if(!o.hasOwnProperty("value"))throw new c('Index restriction "value" is required.',{code:"INVALID_PARAMETER"});return l}};Array.isArray(o)||(o=[o]);let u=o.map(l=>h.Params(l,a,["name"]));if(u.length)for(let l of u)l.condition&&l.hasOwnProperty("range")&&delete l.range;return u}},reference:o=>{if(o===null)return {record_id:null};if(o){if(typeof o=="string"){t=o;let a=Ar.bind(this)(n,o);return a||o}if(typeof o!="object")throw new c('"reference" should be type: <string | object>.',{code:"INVALID_PARAMETER"});return h.Params(o,{unique_id:"string",record_id:a=>a==null?a:(t=a,typeof this.__private_access_key?.[a]=="string"&&(e.reference_private_key=this.__private_access_key[a]||void 0),fe(a,"reference.record_id",{allowEmpty:false,onlyAlphanumeric:true}))})}},index:[null,{name:o=>rt(o,"index.name"),value:o=>Pt(o)}],tags:o=>{if(o==null)return o;if(typeof o=="string"&&(o=o.split(",").map(a=>a.trim())),!Array.isArray(o))throw new c('"tag" should be type: <string | string[]>.',{code:"INVALID_PARAMETER"});return o.map(a=>Tt(a,"tag"))},remove_bin:o=>{if(!o)return null;let a=[];if(Array.isArray(o))for(let u of o)if(typeof u=="string")a.push(u.split("?")[0]);else if(u.url&&u.size&&u.filename){let g=u.url.split("/").slice(0,3).join("/")+"/"+u.path;a.push(g);}else throw new c('"remove_bin" should be type: <string[] | BinaryFile[] | null>',{code:"INVALID_PARAMETER"});else throw new c('"remove_bin" should be type: <string[] | BinaryFile[] | null>',{code:"INVALID_PARAMETER"});return a},progress:"function",data:o=>o},[],{precall:o=>{let a=o?.data||{};if(!a?.record_id&&!a.table)throw new c('"table.name" is required.',{code:"INVALID_PARAMETER"});typeof a.table=="string"&&(a.table={name:a.table},a?.record_id||(a.table.access_group=0)),o.files&&(r=o.files);}}),s=e.progress||null;if(delete i.progress,!this.__user){let o=!!(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 c("Public users cannot update existing records.",{code:"INVALID_REQUEST"});if(i.table.access_group!=="public"&&i.table.access_group!==0)throw new c("Public users can only post records to public tables.",{code:"INVALID_REQUEST"});if(o)throw new c("Public users cannot post subscription records.",{code:"INVALID_REQUEST"});if(i.remove_bin)throw new c("Public users cannot remove files from records.",{code:"INVALID_REQUEST"});if(i.unique_id)throw new c("Public users cannot set unique_id for records.",{code:"INVALID_REQUEST"})}return {config:i,progress:s,is_reference_post:t,files:r}}async function Pi(e){if(await this.__connection,!Array.isArray(e)||!e.length)throw new c('"params" should be a non-empty array.',{code:"INVALID_PARAMETER"});let t=[],r,n,i=null,s={},a={_is_bulk_:await Promise.all(e.map(async(p,m)=>{if(!p||typeof p!="object"||Array.isArray(p))throw new c(`"params[${m}]" should be type: <object>.`,{code:"INVALID_PARAMETER"});let y=Ti.bind(this)(p),_=y.config;if(O.call(this)){let w=Object.prototype.hasOwnProperty.call(_,"data"),b=await ir.bind(this)(_.data,Ai(p,_),w);b.encrypted&&(_.data=b.send,s[m]=b.plain);}if(y.is_reference_post&&t.push(y.is_reference_post),typeof _.progress=="function"&&i===null&&(i=_.progress),_.service!==void 0){if(r===void 0)r=_.service;else if(r!==_.service)throw new c('All bulk params should share the same "service" value.',{code:"INVALID_PARAMETER"})}if(_.owner!==void 0){if(n===void 0)n=_.owner;else if(n!==_.owner)throw new c('All bulk params should share the same "owner" value.',{code:"INVALID_PARAMETER"})}return delete _.progress,delete _.service,delete _.owner,_})),service:"",owner:""};r!==void 0&&(a.service=r),n!==void 0&&(a.owner=n);let u={auth:!!this.__user,method:"post"},l={};Object.keys(l).length&&Object.assign(u,{fetchOptions:l});let g=await T.bind(this)("post-record",a,u),f=await Promise.all(g.map((p,m)=>Se.bind(this)(p,"called from postRecord",false,s.hasOwnProperty(m))));for(let p=0;p<f.length;p++)s.hasOwnProperty(p)&&f[p]&&!f[p].error&&(f[p].data=s[p],f[p].encrypted={status:"encrypted"});let d=kt.bind(this)(r,n);for(let p=0;p<g.length;p++){let m=g[p],y=f[p];if(m&&typeof m=="object"&&m.error&&y&&!y.record_id&&(y.error=m.error),typeof m?.reference_private_key=="string")for(let _ of t)this.__private_access_key[_]=m.reference_private_key;y?.unique_id&&Ei.bind(this)(d,y.unique_id,y.record_id);}return f}async function Rr(e,t,r){if(await this.__connection,!t)throw new c('"config" argument is required.',{code:"INVALID_PARAMETER"});let n=Ti.bind(this)(t),i=n.config,s=n.progress,o=n.is_reference_post,a={auth:!!this.__user,method:"post"},u=[],l=j(e);r&&Array.isArray(r)&&r.length&&(u=u.concat(r)),l.files&&Array.isArray(l.files)&&l.files.length&&(u=u.concat(l.files));let g=t?.data!==void 0?t.data:l.data,f=g!==void 0,d=await ir.bind(this)(g,Ai(t,i),f),p=null;p=Object.assign({},i),delete p.data,d.omit||(p.data=d.send);let m={};if(typeof s=="function"&&(m.progress=s),Object.keys(m).length&&Object.assign(a,{fetchOptions:m}),d.files==="decrypt"&&t?.record_id){let b=await pr.bind(this)(t.record_id,"decrypt",s);if(b.length){let E=p.remove_bin;p.remove_bin=Array.isArray(E)?E.concat(b):b;}}if(d.spill&&t?.record_id){let b=new FormData;if(b.append(Ye,new File([d.spill],"payload.bin",{type:"application/octet-stream"})),await tt.bind(this)(b,{record_id:t.record_id}),d.retireCt){let E=p.remove_bin,k=[d.retireCt];p.remove_bin=Array.isArray(E)?E.concat(k):k;}}let y=await T.bind(this)("post-record",p,a);if(d.encrypted&&y?.rec&&pn.bind(this)(y.rec,d.dek),d.files==="encrypt"&&y?.rec)try{let b=await pr.bind(this)(y.rec,"encrypt",s);b.length&&await Rr.bind(this)(void 0,{record_id:y.rec,remove_bin:b});}catch(b){console.error("Failed to encrypt existing attachments after making the record private:",b);}if(Y()&&u.length){let b=new FormData;for(let A of u)b.append(A.name,A.file,A.file.name);let E={record_id:y.rec,progress:s};i.hasOwnProperty("service")&&(E.service=i.service);let{bin_endpoints:k}=await tt.bind(this)(b,E);y.bin?y.bin.push(...k):y.bin=k;}o&&typeof y?.reference_private_key=="string"&&(this.__private_access_key[o]=y.reference_private_key);let _=!!y&&y.data&&typeof y.data=="object"&&!Array.isArray(y.data)&&typeof y.data.__data__=="string"&&y.data.__data__.endsWith("/__data__/__json__.json"),w=await Se.bind(this)(y,"called from postRecord",true,d.encrypted);if(_&&(w.data=l.data),d.encrypted&&(w.data=d.plain,w.encrypted={status:"encrypted",recipients:Object.keys(d.send.k||{})}),w.unique_id){let b=kt.bind(this)(i?.service,i?.owner);Ei.bind(this)(b,w.unique_id,w.record_id),Y()&&(this.__uniqueIdsPersistTimer!==null&&clearTimeout(this.__uniqueIdsPersistTimer),this.__uniqueIdsPersistTimer=setTimeout(()=>{this.__uniqueIdsPersistTimer=null;try{window.sessionStorage.setItem(`${b}:uniqueids`,JSON.stringify(this.__my_unique_ids[b]||{}));}catch{}},500));}return w}async function Si(e,t){await nt.call(this,"getTables");let r=await T.bind(this)("get-table",h.Params(e||{},{table:i=>Oe(i,"table",{allowEmpty:true}),condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}),Object.assign({auth:!!this.__user},{fetchOptions:t})),n={cnt_rec:"number_of_records",tbl:"table",srvc:"service",grp_:"number_of_records_in_access_group_"};if(Array.isArray(r?.list))for(let i of r.list){for(let s in n){if(s==="grp_"){for(let o in i)if(o.startsWith("grp_")){let a=o.substring(4);a==="pv"?a="private":a==="00"?a="public":a==="01"?a="authorized":a==="99"&&(a="admin"),i[`number_of_records_in_access_group_${a}`]=i[o],delete i[o];}}i.hasOwnProperty(s)&&(i[n[s]]=i[s],delete i[s]);}typeof i.table=="string"&&(i.table=le(i.table));}return r}async function ki(e,t){if(await nt.call(this,"getIndexes"),!e?.table)throw new c('"table" is required.',{code:"INVALID_PARAMETER"});let r=h.Params(e||{},{table:s=>Oe(s,"table",{allowEmpty:true}),index:s=>rt(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:s=>{if(e?.order?.by==="index_name"&&typeof s=="string")return fe(s,"order.value",{allowEmpty:true,maxLength:256,blockKeyDelimiters:true});if(typeof s!="string"&&typeof s!="number"&&typeof s!="boolean")throw new c('"order.value" should be type: <string | number | boolean>.',{code:"INVALID_PARAMETER"});return s},condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}},["table"]);if(r.hasOwnProperty("order")){if(!r.order?.by)throw new c('"order.by" is required.',{code:"INVALID_PARAMETER"});if(r.order.hasOwnProperty("condition")&&!r.order.hasOwnProperty("value"))throw new c('"value" is required for "condition".',{code:"INVALID_PARAMETER"});if(r.hasOwnProperty("index")&&r.index.substring(r.index.length-1)!==".")throw new c('"index" should be a parent index name of the compound index when using "order.by"',{code:"INVALID_PARAMETER"})}let n=await T.bind(this)("get-index",r,Object.assign({auth:!!this.__user},{fetchOptions:t})),i={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(n?.list)&&(n.list=n.list.map(s=>{let o=s.idx.split("/"),a={table:le(o[1]),index:le(o[2]),number_of_records:s.cnt_rec};for(let u in i)Object.prototype.hasOwnProperty.call(s,u)&&(a[i[u]]=s[u]);return a})),n}async function vi(e,t){await nt.call(this,"getTags");let r=await T.bind(this)("get-tag",h.Params(e||{},{table:n=>Oe(n,"table",{allowEmpty:true}),tag:n=>Tt(n,"tag",{allowEmpty:true}),condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}),Object.assign({auth:!!this.__user},{fetchOptions:t}));return Array.isArray(r?.list)&&(r.list=r.list.map(n=>{let i=n.tag.split("/");return {table:le(i[1]),tag:le(i[0]),number_of_records:n.cnt_rec}})),r}async function Ni(e,t){await nt.call(this,"getUniqueId");let r=await T.bind(this)("get-uniqueid",h.Params(e||{},{unique_id:"string",condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}),Object.assign({auth:!!this.__user},{fetchOptions:t}));if(Array.isArray(r?.list))for(let n in r.list){let i=r.list[n];r.list[n]={unique_id:i.unq,record_id:i.rec};}return r}async function Ui(e,t){await this.__connection;let r=await Ri.bind(this)(e,true),n=r.is_reference_fetch,i=await T.bind(this)("del-records",r.query,{auth:true,fetchOptions:t});return n&&typeof i?.reference_private_key=="string"&&(this.__private_access_key[n]=i.reference_private_key),Array.isArray(i?.list)&&(i.list=await Promise.all(i.list.map(async s=>{if(!s||typeof s!="object")return s;try{return await Se.bind(this)(s,"called from deleteRecords",!0,!1,!0)}catch{return s}}))),i?.message||i}async function xi(e){if(O.call(this)){let t=typeof e.user_id=="string"?[e.user_id]:e.user_id;Array.isArray(t)&&t.length&&await fr.bind(this)(e.record_id,t);}return Oi.bind(this)({record_id:e.record_id,user_id:e.user_id,execute:"add"})}async function Di(e){let t=await Oi.bind(this)({record_id:e.record_id,user_id:e.user_id||null,execute:"remove"});if(O.call(this)){let r=typeof e.user_id=="string"?[e.user_id]:e.user_id;await vn.bind(this)(e.record_id,Array.isArray(r)&&r.length?r:null);}return t}async function Ci(e,t){let r={record_id:e.record_id||void 0,user_id:e.user_id||void 0,execute:"list"};if(!r.record_id&&!r.user_id)throw new c("Either record_id or user_id must be provided.",{code:"INVALID_PARAMETER"});if(r.user_id)if(typeof r.user_id=="string")h.UserId(r.user_id),r.user_id=[r.user_id];else if(Array.isArray(r.user_id))for(let s of r.user_id)h.UserId(s);else throw new c("user_id should be type: <string | string[]>",{code:"INVALID_PARAMETER"});let n=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),i=await T.bind(this)("grant-private-access",r,{auth:true,fetchOptions:t});return i.list=i.list.map(n),i}function Li(e){let t=e.record_id,r=e.reference_id||void 0;if(!t)throw new c("Record ID is required.",{code:"INVALID_PARAMETER"});if(typeof t!="string")throw new c("Record ID should be type: <string | string[]>",{code:"INVALID_PARAMETER"});if(r&&typeof r!="string")throw new c("Reference ID should be type: <string>",{code:"INVALID_PARAMETER"});if(typeof this.__private_access_key[t]=="string")return Promise.resolve(this.__private_access_key[t]);if(St[t])return St[t];let n=T.bind(this)("request-private-access-key",{record_id:t,reference_id:r},{auth:true}).then(i=>{let s=typeof i=="string"?i:i?.private_key;if(typeof s!="string")throw new c("Invalid private access key response.",{code:"ERROR"});return this.__private_access_key[t]=s,s}).finally(()=>{delete St[t];});return St[t]=n,n}function Oi(e){e.execute;let r=h.Params(e,{record_id:"string",user_id:n=>{if(!n)throw new c("User ID is required.",{code:"INVALID_PARAMETER"});let i=n;if(typeof i=="string"&&(i=[i]),i.length>100)throw new c("Cannot process more than 100 users at once.",{code:"INVALID_REQUEST"});for(let s of i)h.UserId(s,'User ID in "user_id"');return i},execute:["add","remove"]},["execute","record_id","user_id"]);return r.user_id||(r.user_id=null),T.bind(this)("grant-private-access",r,{auth:true})}var N={},H={},ce={},pe={},ge={},vt={},Nt={};function Mi(e,t,r){e[t]||(e[t]=[]),e[t].push(r);}async function Ut(e,t,r){let n=[];if(e[t]){for(let i of e[t])if(i){let s=r(i);s instanceof Promise&&(s=await s),n.push(s);}delete e[t];}return n}async function Tr(e,t){if(!this?.session?.accessToken?.jwtToken)throw new c("Access token is required.",{code:"INVALID_PARAMETER"});let r=await this.__socket;async function n(i,s,o){this.log("answerSdpOffer from",s),await N[s].setRemoteDescription(new RTCSessionDescription(i));let a=await N[s].createAnswer();await N[s].setLocalDescription(a),o.send(JSON.stringify({action:"rtc",uid:s,content:{sdpanswer:a},token:this.session.accessToken.jwtToken}));}N?.[t]?e?(await Ut(Nt,t,i=>n.bind(this)(i,t,r)),await n.bind(this)(e,t,r)):await Ut(Nt,t,i=>n.bind(this)(i,t,r)):e&&Mi(Nt,t,e);}async function Pr(e,t){if(this.log("receiveIceCandidate",e),N?.[t]&&N[t]?.remoteDescription&&N[t]?.remoteDescription?.type){if(!e)return Ut(vt,t,r=>N[t].addIceCandidate(r));await Ut(vt,t,r=>N[t].addIceCandidate(r)),await N[t].addIceCandidate(e);}else Mi(vt,t,e);}async function ue(e){if(typeof window>"u"||window._runningInNodeJS)throw new c("WebRTC is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});h.Params(e,{cid:s=>{if(typeof s!="string")throw new c('"cid" should be type: <string>.',{code:"INVALID_PARAMETER"});if(s&&s.slice(0,4)!=="cid:")throw new c('"cid" should be a valid connection id.',{code:"INVALID_PARAMETER"});return s},close:"boolean"});let t=await this.__socket,{cid:r,close_all:n=false}=e||{};if(!n&&!r)throw new c('"cid" is required.',{code:"INVALID_PARAMETER"});let i=s=>{if(!s)throw new c('"cid" is required.',{code:"INVALID_PARAMETER"});if(delete Nt[s],delete vt[s],H[s]&&Object.values(H[s]).forEach(o=>{o.readyState!=="closed"&&o.close();}),delete H[s],N?.[s]){N[s].connectionState!=="closed"&&(N[s].close(),t.send(JSON.stringify({action:"rtc",uid:s,content:{hungup:this.user.user_id},token:this.session.accessToken.jwtToken})));let o={type:"connectionstatechange",target:N[s],timestamp:new Date().toISOString(),state:N[s].connectionState,iceState:N[s].iceConnectionState,signalingState:N[s].signalingState};ge[s]&&ge[s](o),this.log("closeRTC",o);}delete ge[s],delete pe[s],delete ce[s],delete N[s];};if(n)for(let s in N)i(s);else i(r);this.log("Cleaning up media stream..."),this.__mediaStream&&(this.__mediaStream.getTracks().forEach(s=>{s.stop();}),this.__mediaStream=null);}async function Fi(e){if(e instanceof MediaStream)return e;if(!e.video&&!e.audio){let t=new MediaStream,r=document.createElement("canvas");r.width=1,r.height=1;let i=r.captureStream().getVideoTracks()[0];return t.addTrack(i),t}return window.navigator.mediaDevices.getUserMedia(e)}async function qi(e,t){if(typeof window>"u"||window._runningInNodeJS)throw new c("WebRTC is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(typeof t!="function")throw new c("Callback is required.",{code:"INVALID_PARAMETER"});if(!this?.session?.accessToken?.jwtToken)throw new c("Access token is required.",{code:"INVALID_PARAMETER"});e=h.Params(e,{cid:o=>{if(typeof o!="string")throw new c('"cid" should be type: <string>.',{code:"INVALID_PARAMETER"});if(o&&o.slice(0,4)!=="cid:")throw new c('"cid" should be a valid connection id.',{code:"INVALID_PARAMETER"});return o},ice:["string",()=>"stun:stun.skapi.com:3468"],media:o=>o,channels:["text-chat","file-transfer","video-chat","voice-chat","gaming",{ordered:"boolean",maxPacketLifeTime:"number",maxRetransmits:"number",protocol:"string"},()=>[{ordered:true,maxPacketLifeTime:10,protocol:"default"}]]},["cid"]);let{cid:r,ice:n}=e;if(!(e?.media instanceof MediaStream)&&(e?.media?.video||e?.media?.audio)&&window.location.hostname!=="localhost"&&window.location.protocol!=="https:")throw new c("Media stream is only supported on either localhost or https.",{code:"INVALID_REQUEST"});let i=this.__socket?await this.__socket:this.__socket;if(!i)throw new c("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});if(i.readyState!==1)throw new c("Realtime connection is not ready.",{code:"INVALID_REQUEST"});let s={iceServers:[{urls:n}]};N?.[r]||(N[r]=new RTCPeerConnection(s)),e?.media&&(this.__mediaStream=await Fi(e.media),this.__mediaStream.getTracks().forEach(o=>{N[r].addTrack(o,this.__mediaStream);})),ge[r]=t,H[r]||(H[r]={});for(let o=0;o<e.channels.length;o++){let a=e.channels[o];if(typeof a=="string")switch(a){case "text-chat":a={ordered:true,maxRetransmits:10,protocol:"text-chat"};break;case "file-transfer":a={ordered:false,maxPacketLifeTime:3e3,protocol:"file-transfer"};break;case "video-chat":a={ordered:true,maxRetransmits:10,protocol:"video-chat"};break;case "voice-chat":a={ordered:true,maxRetransmits:10,protocol:"voice-chat"};break;case "gaming":a={ordered:false,maxPacketLifeTime:100,protocol:"gaming"};break;default:a={ordered:true,maxRetransmits:10,protocol:"default"};break}let u=a.protocol||"default";if(Object.keys(H[r]).includes(u))throw new c(`Data channel with the protocol "${u}" already exists.`,{code:"INVALID_REQUEST"});let l=N[r].createDataChannel(u,a);H[r][u]=l;}for(let o in H[r]){let a=H[r][o];ji.bind(this)(r,a);}return $i.bind(this)(r,["onnegotiationneeded"]),await Ir.bind(this)(r),{hangup:()=>ce[r]&&ce[r](false),connection:new Promise(o=>{ce[r]=(a=>{if(this.log("receiver picked up the call",r),!a)return ue.bind(this)({cid:r}),null;N[r].onnegotiationneeded=()=>{this.log("onnegotiationneeded",`sending offer to "${r}".`),Ir.bind(this)(r),ge[r]&&ge[r]({type:"negotiationneeded",target:N[r],timestamp:new Date().toISOString(),signalingState:N[r].signalingState,connectionState:N[r].iceConnectionState,gatheringState:N[r].iceGatheringState});},o({target:N[r],channels:H[r],hangup:()=>ue.bind(this)({cid:r}),media:this.__mediaStream});}).bind(this);})}}function Vi(e){return async(t,r)=>{t=t||{},t=j(t).data;let n=e.sender_cid,i=await this.__socket;if(!pe[n])return null;if(typeof r!="function")throw new c("Callback is required.",{code:"INVALID_PARAMETER"});if(!(t?.media instanceof MediaStream)&&(t?.media?.video||t?.media?.audio)&&window.location.hostname!=="localhost"&&window.location.protocol!=="https:")throw new c("Media stream is only supported on either localhost or https.",{code:"INVALID_REQUEST"});let{ice:s="stun:stun.skapi.com:3468"}=t;return N?.[n]||(N[n]=new RTCPeerConnection({iceServers:[{urls:s}]})),t?.media&&(this.__mediaStream=await Fi(t.media),this.__mediaStream.getTracks().forEach(o=>{N[n].addTrack(o,this.__mediaStream);})),delete pe[n],ge[n]=r,H[n]||(H[n]={}),N[n].ondatachannel=o=>{this.log("ondatachannel",`received data channel "${o.channel.label}".`);let a=o.channel;H[n][a.label]=a,ji.bind(this)(n,a);},$i.bind(this)(n,["onnegotiationneeded"]),await Tr.bind(this)(null,n),await Pr.bind(this)(null,n),i.send(JSON.stringify({action:"rtc",uid:n,content:{pickup:this.user.user_id},token:this.session.accessToken.jwtToken})),{target:N[n],channels:H[n],hangup:()=>ue.bind(this)({cid:n}),media:this.__mediaStream}}}async function Ir(e){if(!this?.session?.accessToken?.jwtToken)throw new c("Access token is required.",{code:"INVALID_PARAMETER"});this.log("sendOffer",e);let t=await this.__socket,r=await N[e].createOffer();await N[e].setLocalDescription(r);let n=N[e].localDescription;this.log("rtcSdpOffer to",n),t.send(JSON.stringify({action:"rtc",uid:e,content:{sdpoffer:n},token:this.session.accessToken.jwtToken}));}async function Ia(e,t){if(!this?.session?.accessToken?.jwtToken)throw new c("Access token is required.",{code:"INVALID_PARAMETER"});this.log("sendIceCandidate to",t);let r=await this.__socket;if(!e.candidate){this.log("candidate-end","all ice candidates have been sent");return}let n=ge[t]||(()=>{}),i=e.candidate;this.log("ice gathering state set to",N[t].iceGatheringState),n({type:"icecandidate",target:N[t],timestamp:new Date().toISOString(),candidate:e.candidate.candidate,sdpMid:e.candidate.sdpMid,sdpMLineIndex:e.candidate.sdpMLineIndex,usernameFragment:e.candidate.usernameFragment,protocol:e.candidate.protocol,gatheringState:N[t].iceGatheringState,connectionState:N[t].iceConnectionState}),r.send(JSON.stringify({action:"rtc",uid:t,content:{candidate:i},token:this.session.accessToken.jwtToken}));}function $i(e,t){let r=new Set(t),n=ge[e]||(o=>{}),i=N[e],s={ontrack:o=>{n({type:"track",target:i,timeStamp:o.timeStamp,streams:o.streams,track:o.track});},onicecandidate:o=>{Ia.bind(this)(o,e),o.candidate?n({type:"icecandidate",target:i,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:i.iceGatheringState,connectionState:i.iceConnectionState}):n({type:"icecandidateend",target:i,timestamp:new Date().toISOString()});},onicecandidateerror:o=>{n({type:"icecandidateerror",target:i,timestamp:new Date().toISOString(),errorCode:o.errorCode,errorText:o.errorText,url:o.url,hostCandidate:o.hostCandidate,gatheringState:i.iceGatheringState,connectionState:i.iceConnectionState});},oniceconnectionstatechange:()=>{n({type:"iceconnectionstatechange",target:i,timestamp:new Date().toISOString(),state:i.iceConnectionState,gatheringState:i.iceGatheringState,signalingState:i.signalingState});},onicegatheringstatechange:()=>{n({type:"icegatheringstatechange",target:i,timestamp:new Date().toISOString(),state:i.iceGatheringState,connectionState:i.iceConnectionState,signalingState:i.signalingState});},onsignalingstatechange:()=>{n({type:"signalingstatechange",target:i,timestamp:new Date().toISOString(),state:i.signalingState,connectionState:i.iceConnectionState,gatheringState:i.iceGatheringState});},onnegotiationneeded:()=>{Ir.bind(this)(e),n({type:"negotiationneeded",target:i,timestamp:new Date().toISOString(),signalingState:i.signalingState,connectionState:i.iceConnectionState,gatheringState:i.iceGatheringState});},onconnectionstatechange:()=>{n({type:"connectionstatechange",target:i,timestamp:new Date().toISOString(),state:i.connectionState,iceState:i.iceConnectionState,signalingState:i.signalingState});let o=i.connectionState;(o==="disconnected"||o==="failed"||o==="closed")&&ue.bind(this)({cid:e});}};for(let[o,a]of Object.entries(s))r.has(o)||(i[o]=a);}function ji(e,t,r){let n=new Set(r),i=ge[e]||(o=>{}),s={onmessage:o=>{let a={type:o.type,target:t,timeStamp:o.timeStamp,data:o.data,lastEventId:o.lastEventId,origin:o.origin,readyState:t.readyState,bufferedAmount:t.bufferedAmount};this.log(`${t.label}: message`,o.data),i(a);},onerror:o=>{let a={type:o.type,target:t,timeStamp:o.timeStamp,error:o.error.message,errorCode:o.error.errorDetail,readyState:t.readyState,label:t.label};this.log(`${t.label}: error`,o.error.message),i(a);},onclose:o=>{let a={type:o.type,target:t,timeStamp:o.timeStamp,readyState:t.readyState,label:t.label,id:t.id};this.log(`${t.label}: closed`,null),i(a),H[e]&&(delete H[e][t.label],Object.keys(H[e]).length===0&&ue.bind(this)({cid:e}));},onbufferedamountlow:o=>{let a={target:t,bufferedAmount:t.bufferedAmount,bufferedAmountLowThreshold:t.bufferedAmountLowThreshold,type:o.type,timeStamp:o.timeStamp};this.log(`${t.label}: bufferedamountlow`,t.bufferedAmount),i(a);},onopen:o=>{this.log("dataChannel",`data channel: "${t.label}" is open and ready to send messages.`);let a={type:o.type,target:t,timeStamp:o.timeStamp,readyState:t.readyState,label:t.label,id:t.id,ordered:t.ordered,maxRetransmits:t.maxRetransmits,protocol:t.protocol};i(a);}};for(let[o,a]of Object.entries(s))n.has(o)||(t[o]=a);}var _e;function Bi(){return _e}var Ae=null,it=true,Me=0;async function Ta(){if(typeof window>"u"||window._runningInNodeJS)throw new c("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.getProfile(),!this.session)throw new c("No access.",{code:"INVALID_REQUEST"});let e=await this.record_endpoint;return new WebSocket(e.websocket_private+"?token="+this.session.accessToken.jwtToken)}var Sr=null;async function xt(){if(typeof window>"u"||window._runningInNodeJS)throw new c("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});it=true;let e=this.__socket?await this.__socket:this.__socket;ue.bind(this)({close_all:true}),_e&&qe.bind(this)({group:null}),Me=0,Ae&&(Ae.terminate(),Ae=null);try{e&&e.close();}catch{}return window.removeEventListener("visibilitychange",Sr),this.__socket=null,null}async function Fe(e,t=50,r){if(typeof window>"u"||window._runningInNodeJS)throw new c("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(typeof e!="function")throw new c("Callback must be a function.",{code:"INVALID_REQUEST"});if(r==="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(it&&(Sr=()=>{!document.hidden&&!it&&Fe.bind(this)(e,0,"reconnect");},this.__socket instanceof Promise))return this.__socket;Ae&&(Ae.terminate(),Ae=null);let n={value:null};return this.__socket=new Promise(async(i,s)=>{let o=a=>{this.__socket===n.value&&(this.__socket=null),s(a);};try{await Ce.bind(this)();}catch(a){o(a);return}setTimeout(async()=>{try{let a=await Ta.bind(this)();a.onopen=()=>{it=!1,Me=0,r!=="reconnect"&&window.addEventListener("visibilitychange",Sr),this.log("realtime onopen","Connected to WebSocket server."),e({type:"success",message:"Connected to WebSocket server."}),_e&&a.send(JSON.stringify({action:"joinRoom",rid:_e,token:this.session.accessToken.jwtToken}));let u=`
|
|
206
|
+
var co=Object.defineProperty;var uo=Object.getOwnPropertyDescriptor;var ke=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var I=(e,t,r,n)=>{for(var i=uo(t,r),s=e.length-1,o;s>=0;s--)(o=e[s])&&(i=(o(t,r,i))||i);return i&&co(t,r,i),i};function $r(e){let r=(typeof globalThis<"u"?globalThis:void 0)?.process;if(r&&typeof r.getBuiltinModule=="function")try{return r.getBuiltinModule(e)}catch{}try{if(typeof ke=="function")return ke(e)}catch{}return null}var qt,Vt,$t=()=>qt!==void 0?qt:qt=$r("fs"),jt=()=>Vt!==void 0?Vt:Vt=$r("path"),me=typeof globalThis<"u"?globalThis:void 0,dt=me?.window;function fo(e){if(Buffer)return Buffer.from(e).toString("base64");let t="",r=new Uint8Array(e),n=32768;for(let i=0;i<r.length;i+=n){let s=r.subarray(i,i+n);t+=String.fromCharCode.apply(null,Array.from(s));}if(typeof btoa=="function")return btoa(t);throw new Error("No base64 encoder available in this environment.")}if(dt)dt.global=dt,dt.global._runningInNodeJS=false;else if(me&&(me.global=me,typeof me.window>"u")){class e{constructor(){this.result=null;this.error=null;this.onload=null;this.onloadend=null;this.onerror=null;}readAsDataURL(n){n.arrayBuffer().then(i=>{let s=fo(i),o=n.type||"application/octet-stream";this.result=`data:${o};base64,${s}`,this.onload&&this.onload({target:this}),this.onloadend&&this.onloadend({target:this});}).catch(i=>{this.error=i,this.onerror&&this.onerror({target:this});});}readAsArrayBuffer(n){n.arrayBuffer().then(i=>{this.result=i,this.onload&&this.onload({target:this}),this.onloadend&&this.onloadend({target:this});}).catch(i=>{this.error=i,this.onerror&&this.onerror({target:this});});}readAsText(n,i="utf-8"){n.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});});}}me.FileReader=e;class t{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(n,i){this._method=n,this._url=i,this.readyState=1;}setRequestHeader(n,i){this._headers[n]=i;}getResponseHeader(n){return null}abort(){this._aborted=true,this.onabort&&this.onabort({});}send(n){if(this._aborted)return;let i={method:this._method,headers:this._headers};n&&this._method!=="GET"&&this._method!=="HEAD"&&(i.body=n),fetch(this._url,i).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);});}}me.XMLHttpRequest=t,me.window={_runningInNodeJS:true,alert:r=>console.error("[Alert]",r),sessionStorage:{getItem:r=>null,setItem:(r,n)=>{},removeItem:r=>{}},localStorage:{getItem:r=>{let n=$t(),i=jt();if(!n||!i)return null;try{let s=i.resolve(process.cwd(),"states","localStorage",`${r}.skapi`);return n.existsSync(s)?n.readFileSync(s,"utf8"):null}catch{return null}},setItem:(r,n)=>{let i=$t(),s=jt();if(!(!i||!s))try{let o=s.resolve(process.cwd(),"states","localStorage");i.existsSync(o)||i.mkdirSync(o,{recursive:!0});let a=s.resolve(o,`${r}.skapi`);i.writeFileSync(a,n,"utf8");}catch{}},removeItem:r=>{let n=$t(),i=jt();if(!(!n||!i))try{let s=i.resolve(process.cwd(),"states","localStorage",`${r}.skapi`);n.existsSync(s)&&n.unlinkSync(s);}catch{}}},location:{href:"",origin:"",hostname:"",protocol:"",replace:r=>{}},navigator:{userAgent:`nodejs/${me?.process?.versions?.node||"unknown"}`,mediaDevices:{getUserMedia:async r=>{throw new Error("getUserMedia is not supported in Node.js environment.")}}},addEventListener:()=>{},removeEventListener:()=>{}};}var l=class extends Error{constructor(t,r){if(Array.isArray(t)&&t.length<=2){let n=t[1];if(t.length>2)for(let i=2;i<t.length&&typeof t[i]=="string";i++)n+=t[i];super((n||"Something went wrong.").trim()),this.name=r?.name||"SKAPI",this.code=r?.code||t[0]||"ERROR",r?.cause&&(this.cause=r.cause);}else super((t?.message||(typeof t=="string"?t:"Something went wrong.")).trim()),typeof t=="string"?(this.name=r?.name||"SKAPI",this.code=r?.code||"ERROR",r?.cause&&(this.cause=r.cause)):t instanceof Error?(this.cause=t,this.name=t.name,t.hasOwnProperty("code")&&(this.code=t.code)):typeof t=="object"&&t?.code&&t?.message&&(this.name=r?.name||"SKAPI",this.code=r?.code||"ERROR",this.cause=t?.cause);}};var ye="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Bt=BigInt(ye.length),go=2*1024*1024,po=["aud","cognito:username","event_id","exp","iat","iss","jti","origin_jti","secret_key","token_use"],jr={auth_time:"log",sub:"user_id"},Wr=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f","g","h","i","j","k","l"],Qr=["us31","us72","ap51","ap22","ap41","eu71","ap21","us32","us71","af51","ap31","ap43","ap23","ap42","ca01","eu01","eu72","eu51","eu73","eu11","me51","sa31"],Br=typeof TextEncoder<"u"?new TextEncoder:null;function ho(){if(typeof globalThis<"u")return globalThis.Buffer}function K(e){if(Br)return Br.encode(e);let t=unescape(encodeURIComponent(e)),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}function Kt(e){if(e instanceof Uint8Array)return e;if(typeof e=="string")return K(e);if(typeof ArrayBuffer<"u"&&e instanceof ArrayBuffer)return new Uint8Array(e);if(typeof ArrayBuffer<"u"&&ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);if(Array.isArray(e))return Uint8Array.from(e);let t=ho();if(t)return new Uint8Array(t.from(e));throw new Error("No byte conversion available in this environment.")}var R=class R{static hash(t){typeof t!="string"&&(console.warn("coercing non-string value to empty string"),t="");let r=R.sb(t),n=1732584193,i=-271733879,s=-1732584194,o=271733878,a,d,u,g;for(let f=0;f<r.length;f+=16)a=n,d=i,u=s,g=o,n=R.ff(n,i,s,o,r[f],7,-680876936),o=R.ff(o,n,i,s,r[f+1],12,-389564586),s=R.ff(s,o,n,i,r[f+2],17,606105819),i=R.ff(i,s,o,n,r[f+3],22,-1044525330),n=R.ff(n,i,s,o,r[f+4],7,-176418897),o=R.ff(o,n,i,s,r[f+5],12,1200080426),s=R.ff(s,o,n,i,r[f+6],17,-1473231341),i=R.ff(i,s,o,n,r[f+7],22,-45705983),n=R.ff(n,i,s,o,r[f+8],7,1770035416),o=R.ff(o,n,i,s,r[f+9],12,-1958414417),s=R.ff(s,o,n,i,r[f+10],17,-42063),i=R.ff(i,s,o,n,r[f+11],22,-1990404162),n=R.ff(n,i,s,o,r[f+12],7,1804603682),o=R.ff(o,n,i,s,r[f+13],12,-40341101),s=R.ff(s,o,n,i,r[f+14],17,-1502002290),i=R.ff(i,s,o,n,r[f+15],22,1236535329),n=R.gg(n,i,s,o,r[f+1],5,-165796510),o=R.gg(o,n,i,s,r[f+6],9,-1069501632),s=R.gg(s,o,n,i,r[f+11],14,643717713),i=R.gg(i,s,o,n,r[f],20,-373897302),n=R.gg(n,i,s,o,r[f+5],5,-701558691),o=R.gg(o,n,i,s,r[f+10],9,38016083),s=R.gg(s,o,n,i,r[f+15],14,-660478335),i=R.gg(i,s,o,n,r[f+4],20,-405537848),n=R.gg(n,i,s,o,r[f+9],5,568446438),o=R.gg(o,n,i,s,r[f+14],9,-1019803690),s=R.gg(s,o,n,i,r[f+3],14,-187363961),i=R.gg(i,s,o,n,r[f+8],20,1163531501),n=R.gg(n,i,s,o,r[f+13],5,-1444681467),o=R.gg(o,n,i,s,r[f+2],9,-51403784),s=R.gg(s,o,n,i,r[f+7],14,1735328473),i=R.gg(i,s,o,n,r[f+12],20,-1926607734),n=R.hh(n,i,s,o,r[f+5],4,-378558),o=R.hh(o,n,i,s,r[f+8],11,-2022574463),s=R.hh(s,o,n,i,r[f+11],16,1839030562),i=R.hh(i,s,o,n,r[f+14],23,-35309556),n=R.hh(n,i,s,o,r[f+1],4,-1530992060),o=R.hh(o,n,i,s,r[f+4],11,1272893353),s=R.hh(s,o,n,i,r[f+7],16,-155497632),i=R.hh(i,s,o,n,r[f+10],23,-1094730640),n=R.hh(n,i,s,o,r[f+13],4,681279174),o=R.hh(o,n,i,s,r[f],11,-358537222),s=R.hh(s,o,n,i,r[f+3],16,-722521979),i=R.hh(i,s,o,n,r[f+6],23,76029189),n=R.hh(n,i,s,o,r[f+9],4,-640364487),o=R.hh(o,n,i,s,r[f+12],11,-421815835),s=R.hh(s,o,n,i,r[f+15],16,530742520),i=R.hh(i,s,o,n,r[f+2],23,-995338651),n=R.ii(n,i,s,o,r[f],6,-198630844),o=R.ii(o,n,i,s,r[f+7],10,1126891415),s=R.ii(s,o,n,i,r[f+14],15,-1416354905),i=R.ii(i,s,o,n,r[f+5],21,-57434055),n=R.ii(n,i,s,o,r[f+12],6,1700485571),o=R.ii(o,n,i,s,r[f+3],10,-1894986606),s=R.ii(s,o,n,i,r[f+10],15,-1051523),i=R.ii(i,s,o,n,r[f+1],21,-2054922799),n=R.ii(n,i,s,o,r[f+8],6,1873313359),o=R.ii(o,n,i,s,r[f+15],10,-30611744),s=R.ii(s,o,n,i,r[f+6],15,-1560198380),i=R.ii(i,s,o,n,r[f+13],21,1309151649),n=R.ii(n,i,s,o,r[f+4],6,-145523070),o=R.ii(o,n,i,s,r[f+11],10,-1120210379),s=R.ii(s,o,n,i,r[f+2],15,718787259),i=R.ii(i,s,o,n,r[f+9],21,-343485551),n=R.ad(n,a),i=R.ad(i,d),s=R.ad(s,u),o=R.ad(o,g);return R.rh(n)+R.rh(i)+R.rh(s)+R.rh(o)}static rh(t){let r="";for(let n=0;n<=3;n++)r+=R.alphabet.charAt(t>>n*8+4&15)+R.alphabet.charAt(t>>n*8&15);return r}static ad(t,r){let n=(t&65535)+(r&65535);return (t>>16)+(r>>16)+(n>>16)<<16|n&65535}static rl(t,r){return t<<r|t>>>32-r}static cm(t,r,n,i,s,o){return R.ad(R.rl(R.ad(R.ad(r,t),R.ad(i,o)),s),n)}static ff(t,r,n,i,s,o,a){return R.cm(r&n|~r&i,t,r,s,o,a)}static gg(t,r,n,i,s,o,a){return R.cm(r&i|n&~i,t,r,s,o,a)}static hh(t,r,n,i,s,o,a){return R.cm(r^n^i,t,r,s,o,a)}static ii(t,r,n,i,s,o,a){return R.cm(n^(r|~i),t,r,s,o,a)}static sb(t){let r,n=(t.length+8>>6)+1,i=new Array(n*16);for(r=0;r<n*16;r++)i[r]=0;for(r=0;r<t.length;r++)i[r>>2]|=t.charCodeAt(r)<<r%4*8;return i[r>>2]|=128<<r%4*8,i[n*16-2]=t.length*8,i}};R.alphabet="0123456789abcdef";var Z=R;function zr(e){if(e===0)return ye[0];let t="";for(;e>0;)t=ye[e%62]+t,e=Math.floor(e/62);return t}function se(e){return e.split("").reverse().reduce((t,r,n)=>t+ye.indexOf(r)*62**n,0)}function Te(e=6){let t="",r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n=r.length,i=0;for(;i<e;)t+=r.charAt(Math.floor(Math.random()*n)),i+=1;return t}function Ht(){return typeof window>"u"||!!window?._runningInNodeJS}function J(){return !Ht()&&typeof document<"u"&&typeof document.createElement=="function"}function ft(e){let t;try{t=JSON.stringify(e);}catch{throw new l("Invalid data type.",{code:"INVALID_REQUEST"})}if(new Blob([t]).size>go)throw new l("Data should not exceed 2MB",{code:"INVALID_REQUEST"})}function Kr(e){return e===""||e==="on"||e==="true"}function Hr(e){return e==="false"}function Gr(e,t,r){t.name&&r(e,t.name,t.value);}var gt=J(),mo=typeof SubmitEvent<"u",yo=typeof HTMLFormElement<"u";function j(e,t,r){let n={},i=[];function s(d,u,g){if(t?.ignoreEmpty&&g==="")return;if(t?.nullIfEmpty&&g===""&&(g=null),typeof r=="function"){let p=r(u,g);p!==void 0&&(g=p);}let f=u.split("[").map(p=>{let h=p.replace("]",""),m=Number(h);return !isNaN(m)&&!h.includes(".")?h=m:(h[0]==='"'&&h[h.length-1]==='"'||h[0]==="'"&&h[h.length-1]==="'")&&(h=h.replace(/"/g,"").replace(/'/g,"")),h}),c=d;if(typeof f[0]=="number")throw new l("Form key cannot start with an array index.",{code:"INVALID_REQUEST"});for(let p=0;p<f.length;p++){let h=f[p];p<f.length-1?(c[h]===void 0&&(typeof f[p+1]=="number"?c[h]=[]:c[h]={}),c=c[h]):c[h]===void 0?c[h]=g:Array.isArray(c[h])?c[h].push(g):c[h]=[c[h],g];}}function o(d,u,g){if(g instanceof File)d.push({name:u,file:g});else if(g instanceof FileList&&g&&g.length>0)for(let f=0;f<=g.length-1;f++){let c=g.item(f);c&&d.push({name:u,file:c});}}let a=d=>{d.name&&(d.type==="number"?d.value&&s(n,d.name,Number(d.value)):d.type==="checkbox"||d.type==="radio"?d.checked?d.type==="checkbox"&&d.value===""||Kr(d.value)?s(n,d.name,true):Hr(d.value)?s(n,d.name,false):d.value&&s(n,d.name,d.value):d.type==="checkbox"&&(Kr(d.value)?s(n,d.name,false):Hr(d.value)&&s(n,d.name,true)):d.type==="file"?d.files&&d.files.length>0&&o(i,d.name,d.files):s(n,d.name,d.value));};if(gt&&(e instanceof HTMLInputElement||e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement))return a(e),ft(n),{data:n,files:i};if(gt&&e instanceof FormData){for(let d of e.entries()){let u=d[0],g=d[1];if(g instanceof File||g instanceof FileList)o(i,u,g);else if(g instanceof Blob){let f=g;if(f.type==="application/json")try{let c=JSON.parse(f.text());s(n,u,c);}catch{s(n,u,f);}}else s(n,u,g);}return ft(n),{data:n,files:i}}if(gt&&mo&&e instanceof SubmitEvent&&(e=e.target),gt&&yo&&e instanceof HTMLFormElement){let d=e.querySelectorAll("input"),u=e.querySelectorAll("select"),g=e.querySelectorAll("textarea");for(let f=0;f<u.length;f++)Gr(n,u[f],s);for(let f=0;f<g.length;f++)Gr(n,g[f],s);for(let f=0;f<d.length;f++)a(d[f]);return ft(n),{data:n,files:i}}return ft(e),{data:e,files:i}}function je(e){let t={};for(let r in e){let n=e[r];if(!po.includes(r))if(jr[r])t[jr[r]]=n;else if(r.includes("custom:"))t[r.replace("custom:","")]=n;else if(r==="address"){let i=n;if(i&&typeof i=="object"&&Object.keys(i).length){if(i?.formatted)try{t[r]=JSON.parse(i.formatted);}catch{t[r]=i.formatted;}}else t[r]=i;}else t[r]=n;}for(let r of ["address_public","birthdate_public","email_public","gender_public","phone_number_public","access_group"])r.includes("_public")?t.hasOwnProperty(r.split("_")[0])?t[r]=t.hasOwnProperty(r)?!!Number(t[r]):false:delete t[r]:t[r]=t.hasOwnProperty(r)?Number(t[r]):0;for(let r of ["email","phone_number"])t.hasOwnProperty(r)?t[r+"_verified"]=t[r+"_verified"]===true:delete t[r+"_verified"];return t}function Gt(e){if(e=Io(e),e.split("-").length===7){let t=e.split("-"),r,n;try{r=Qr[Wr.indexOf(t[1][0])],n=t.slice(2).join("-");}catch{throw new Error("INVALID_PARAMETER: Service ID is invalid: "+e)}if(!r)throw new Error("INVALID_PARAMETER: Service ID is invalid: "+e);return {service:r+t[0]+t[1].slice(1),owner:n}}return {service:e,owner:""}}function Wt(e,t){let r=Qr.indexOf(e.slice(0,4)),n=Wr[r],s=`${e.slice(4,-4)}-${n}${e.slice(-4)}-${t}`;return To(s)}function bo(e){let t=0n;for(let r of e){let n=ye.indexOf(r);if(n<0)throw new Error(`INVALID_PARAMETER: Invalid base62 character: ${r}`);t=t*Bt+BigInt(n);}return t}function _o(e,t=1){if(e<0n)throw new Error("INVALID_PARAMETER: Negative values are not supported.");if(e===0n)return "0".repeat(Math.max(1,t));let r="",n=e;for(;n>0n;){let i=Number(n%Bt);r=ye[i]+r,n/=Bt;}return r.length<t&&(r="0".repeat(t-r.length)+r),r}function wo(e){if(e===0n)return Uint8Array.from([0]);let t=[],r=e;for(;r>0n;)t.push(Number(r&0xffn)),r>>=8n;return t.reverse(),Uint8Array.from(t)}function Eo(e){let t=0n;for(let r of e)t=(t<<8n)+BigInt(r);return t}function Ao(e){let t=String(e).replace(/-/g,"");if(!/^[0-9a-fA-F]{32}$/.test(t))throw new Error("INVALID_PARAMETER: Invalid UUID format.");let r=new Uint8Array(16);for(let n=0;n<16;n++)r[n]=parseInt(t.slice(n*2,n*2+2),16);return r}function Ro(e){let t=Array.from(Kt(e),r=>r.toString(16).padStart(2,"0")).join("");return [t.slice(0,8),t.slice(8,12),t.slice(12,16),t.slice(16,20),t.slice(20)].join("-")}function To(e){let t=String(e);if(t.split("-").length===2)return t;let r=t.match(/^([0-9A-Za-z]+)-([0-9A-Za-z]+)-([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/);if(!r)throw new Error("INVALID_PARAMETER: Input must match <base62>-<base62>-<uuid>.");let[,n,i,s]=r;if(n.length<2)throw new Error("INVALID_PARAMETER: The first part must contain at least 2 characters.");if(i.length>=ye.length)throw new Error("INVALID_PARAMETER: The middle section is too long to encode.");let o=n.slice(0,2),a=n.slice(2),d=i+o,u=ye[i.length]+a+d,g=Ao(s),f=_o(Eo(g));return `${u}-${f}`}function Io(e){let t=String(e);if(t.split("-").length!==2)return t;let r=t.split("-");if(r.length!==2||!r[0]||!r[1])throw new Error("INVALID_PARAMETER: Corrupt compressed token: "+t);let[n,i]=r,s=ye.indexOf(n[0]);if(s<0)throw new Error("INVALID_PARAMETER: Corrupt compressed token: "+t);let o=n.slice(1),a=s+2;if(o.length<a)throw new Error("INVALID_PARAMETER: Corrupt compressed token: "+t);let d=o.slice(0,o.length-a),u=o.slice(o.length-a),g=u.slice(s),f=u.slice(0,s),c=g+d;if(!/^[0-9A-Za-z]+$/.test(c)||!/^[0-9A-Za-z]+$/.test(f))throw new Error("INVALID_PARAMETER: Corrupt compressed token: "+t);let p=bo(i),h=wo(p);if(h.length>16)throw new Error("INVALID_PARAMETER: Corrupt compressed token: "+t);let m=new Uint8Array(16);m.set(h,16-h.length);let w=Ro(m);return `${c}-${f}-${w}`}function Be(e){if(typeof TextDecoder<"u")return new TextDecoder().decode(e);let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return decodeURIComponent(escape(t))}function Qt(...e){let t=0;for(let i of e)t+=i.length;let r=new Uint8Array(t),n=0;for(let i of e)r.set(i,n),n+=i.length;return r}function So(e,t="User ID"){let r=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;if(e){if(typeof e!="string")throw new l(`${t} should be type: string.`,{code:"INVALID_PARAMETER"});if(!e.match(r))throw new l(`${t} is invalid.`,{code:"INVALID_PARAMETER"})}else throw new l(`${t} is empty.`,{code:"INVALID_PARAMETER"});return e}function ko(e){if(e&&(typeof e!="string"||e.charAt(0)!=="+"||isNaN(Number(e.substring(1)))))throw new l('"phone_number" is invalid. The format should be "+00123456789". Type: string.',{code:"INVALID_PARAMETER"});return e||""}function vo(e){if(e){if(typeof e!="string")throw new l('"birthdate" is invalid. The format should be "yyyy-mm-dd". Type: string.',{code:"INVALID_PARAMETER"});{let t=new RegExp(/([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))/);if(e.length!==10||e.split("-").length!==3||!t.test(e))throw new l('"birthdate" is invalid. The format should be "yyyy-mm-dd". Type: string.',{code:"INVALID_PARAMETER"})}}return e||""}function No(e){if(e){if(typeof e!="string")throw new l('"password" should be type: string.',{code:"INVALID_PARAMETER"});if(e.length<6)throw new l('"password" should be at least 6 characters.',{code:"INVALID_PARAMETER"});if(e.length>60)throw new l('"password" can be up to 60 characters max.',{code:"INVALID_PARAMETER"})}else throw new l('"password" is required.',{code:"INVALID_PARAMETER"});return e}function Do(e,t="email"){if(e){if(typeof e!="string")throw new l(`"${t}"should be type: string.`,{code:"INVALID_PARAMETER"});if(e.length<5)throw new l(`"${t}" should be at least 5 characters.`,{code:"INVALID_PARAMETER"});if(/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/.test(e)&&(e=e.trim(),e.split("@")[1].split(".").length>=2))return e.toLowerCase()}else throw new l(`"${t}" is required.`,{code:"INVALID_PARAMETER"});throw new l(`"${e}" is an invalid email.`,{code:"INVALID_PARAMETER"})}function xo(e){let t=typeof window<"u",r=(()=>{let i=t&&window.location.origin||null;return i&&i.slice(-1)==="/"&&(i=i.slice(0,-1)),i})(),n=i=>{if(typeof i=="string"){if(i==="*")return "*";{let s=i.trim();if(s[0]==="/"&&r){if(r.slice(0,5)==="file:")throw new l(`"${i}" is an invalid url. Relative URL does not work on local file system. Use full URL string.`,{code:"INVALID_PARAMETER"});s=r+s;}else if(s[0]==="."&&r){if(r.slice(0,5)==="file:")throw new l(`"${i}" is an invalid url. Relative URL does not work on local file system. Use full URL string.`,{code:"INVALID_PARAMETER"});let a=t?window.location.href.split("?")[0]:"";a.slice(-1)!=="/"&&(a+="/"),s=a+s.slice(1);}let o;try{o=new URL(s);}catch{throw new l(`"${i}" is an invalid url.`,{code:"INVALID_PARAMETER"})}if(o.protocol)return o.href}}throw new l(`"${i}" is an invalid url.`,{code:"INVALID_PARAMETER"})};return Array.isArray(e)?e.map(i=>n(i)):n(e)}var Uo=/^[a-z0-9]{2,20}$/,Co=/[a-z]/,Oo=/^[0-9]+e[0-9]+$/,Lo=["tp","admin","public","authorized","newsletter","forward","all","true","false","null"];function Fo(e,t){if(e==null){if(t?.allowNull)return null;throw new l('"group" is required.',{code:"INVALID_PARAMETER"})}if(!t?.nameOnly){if(e==="public")return 0;if(e==="authorized")return 1;if(typeof e=="number"){if(!Number.isInteger(e)||e<0||e>99)throw new l('"group" should be an integer between 0 and 99.',{code:"INVALID_PARAMETER"});return e}}if(typeof e!="string"||!Uo.test(e)||!Co.test(e)||Oo.test(e)||Lo.includes(e))throw new l("Newsletter group name must be 2-20 lowercase alphanumeric characters, contain a letter, and not be a reserved name.",{code:"INVALID_PARAMETER"});return e}function Mo(e,t,r=[],n){let i=j(e,n),s=i.data;t.service="string",t.owner="string";let o={};for(let a in t)if(s&&typeof s=="object"&&!Array.isArray(s)&&s.hasOwnProperty(a))if(typeof s[a]=="function")o[a]=s[a];else try{o[a]=JSON.parse(JSON.stringify(s[a]));}catch{o[a]=s[a];}n?.precall&&n.precall({data:o,files:i?.files||[]});try{return Po(o,t,r)}catch(a){throw new l(a.message,{code:"INVALID_PARAMETER"})}}var y={UserId:So,PhoneNumber:ko,Birthdate:vo,Password:No,Email:Do,Url:xo,newsletterGroup:Fo,Params:Mo};var Y="skapi.enc.v1",Xr=6e5,Ke=12,pt=null,ve=null;function Zr(){return new l("Encryption requires Web Crypto, which needs a secure context (https, or localhost) in the browser, or Node 18 or newer. A page served over plain http has crypto.getRandomValues but crypto.subtle is undefined.",{code:"NOT_SUPPORTED"})}function en(){if(ve)return ve;let e=typeof globalThis<"u"?globalThis:void 0;if(e?.crypto?.subtle&&typeof e.crypto.getRandomValues=="function")return ve=e.crypto,ve;try{let t=typeof globalThis<"u"?globalThis:void 0,r=null;if(t?.process&&typeof t.process.getBuiltinModule=="function"&&(r=t.process.getBuiltinModule("crypto")),!r&&typeof ke=="function"&&(r=ke("crypto")),r?.webcrypto?.subtle)return ve=r.webcrypto,ve}catch{}throw Zr()}function re(){if(pt)return pt;let e=en();if(!e.subtle)throw Zr();return pt=e.subtle,pt}function Jt(){try{return re(),!0}catch{return false}}function X(e){let t=en(),r=new Uint8Array(e),n=65536;for(let i=0;i<e;i+=n)t.getRandomValues(r.subarray(i,Math.min(i+n,e)));return r}function q(e){let t=Kt(e),r;if(typeof Buffer<"u"&&typeof Buffer.from=="function")r=Buffer.from(t).toString("base64");else if(typeof btoa=="function"){let n="";for(let s=0;s<t.length;s+=32768)n+=String.fromCharCode.apply(null,Array.from(t.subarray(s,s+32768)));r=btoa(n);}else throw new l("No base64 encoder available in this environment.",{code:"NOT_SUPPORTED"});return r.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function $(e){if(typeof e!="string")throw new l("Expected a base64url string.",{code:"INVALID_PARAMETER"});let t=e.replace(/-/g,"+").replace(/_/g,"/"),r=t.length%4;if(r===2)t+="==";else if(r===3)t+="=";else if(r===1)throw new l("Malformed base64url string.",{code:"INVALID_PARAMETER"});if(typeof Buffer<"u"&&typeof Buffer.from=="function"){let n=Buffer.from(t,"base64");return new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}if(typeof atob=="function"){let n=atob(t),i=new Uint8Array(n.length);for(let s=0;s<n.length;s++)i[s]=n.charCodeAt(s);return i}throw new l("No base64 decoder available in this environment.",{code:"NOT_SUPPORTED"})}async function ht(e){let t=await re().digest("SHA-256",e);return new Uint8Array(t)}async function We(e,t,r,n){let i=re(),s=await i.importKey("raw",e,"HKDF",false,["deriveBits"]),o=await i.deriveBits({name:"HKDF",hash:"SHA-256",salt:t,info:r},s,n*8);return new Uint8Array(o)}async function De(e,t,r,n){let i=re(),s=K(e.normalize("NFC")),o=await i.importKey("raw",s,"PBKDF2",false,["deriveBits"]),a=new Uint8Array(await i.deriveBits({name:"PBKDF2",salt:t,iterations:r,hash:"SHA-256"},o,256)),d=await We(a,t,n,32);M(a),M(s);let u=await oe(d);return M(d),u}async function oe(e){return re().importKey("raw",e,{name:"AES-GCM"},false,["encrypt","decrypt"])}async function tn(){let e=X(32),t=await oe(e);return {bytes:e,key:t}}async function ne(e,t,r){let n=X(Ke),i=await re().encrypt({name:"AES-GCM",iv:n,additionalData:r,tagLength:128},e,t);return {iv:n,ct:new Uint8Array(i)}}async function ae(e,t,r,n){let i=await re().decrypt({name:"AES-GCM",iv:t,additionalData:n,tagLength:128},e,r);return new Uint8Array(i)}var mt={name:"ECDH",namedCurve:"P-256"};async function rn(){let e=re(),t=await e.generateKey(mt,true,["deriveBits"]),r=new Uint8Array(await e.exportKey("raw",t.publicKey)),n=new Uint8Array(await e.exportKey("pkcs8",t.privateKey)),i=await Yt(n);return {pubRaw:r,pkcs8:n,priv:i}}async function Yt(e){return re().importKey("pkcs8",e,mt,false,["deriveBits"])}async function nn(e){if(e.length!==65||e[0]!==4)throw new l("Malformed public key: expected a 65 byte uncompressed P-256 point.",{code:"INVALID_PARAMETER"});return re().importKey("raw",e,mt,false,[])}async function Xt(e){return q(await ht(e))}async function sn(e,t,r,n){let i=re(),s=await nn(e),o=await i.generateKey(mt,true,["deriveBits"]),a=new Uint8Array(await i.deriveBits({name:"ECDH",public:s},o.privateKey,256)),d=await We(a,new Uint8Array(32),r,32);M(a);let u=await oe(d);M(d);let{iv:g,ct:f}=await ne(u,t,n);return {epk:new Uint8Array(await i.exportKey("raw",o.publicKey)),iv:g,ct:f}}async function on(e,t,r,n,i,s){let o=re(),a=await nn(t),d=new Uint8Array(await o.deriveBits({name:"ECDH",public:a},e,256)),u=await We(d,new Uint8Array(32),i,32);M(d);let g=await oe(u);return M(u),ae(g,r,n,s)}function M(e){e&&e.length&&e.fill(0);}function qo(e,t){if(e.length!==t.length)return false;let r=0;for(let n=0;n<e.length;n++)r|=e[n]^t[n];return r===0}function Zt(e){return K(JSON.stringify(e))}function Qe(e,t,r){return Qt(e,new Uint8Array([0]),K(t),new Uint8Array([0]),K(r))}var Ie="0123456789ABCDEFGHJKMNPQRSTVWXYZ",He=16,Jr=26,Yr=28;function an(e){let t=2166136261;for(let r=0;r<e.length;r++)t^=e[r],t=t*16777619>>>0;return t&1023}function ln(e){if(e.length!==He)throw new l(`A recovery code needs exactly ${He} bytes.`,{code:"INVALID_PARAMETER"});let t="",r=0,n=0;for(let s=0;s<e.length;s++)for(r=r<<8|e[s],n+=8;n>=5;)n-=5,t+=Ie[r>>n&31];n>0&&(t+=Ie[r<<5-n&31]);let i=an(e);return t+=Ie[i>>5&31]+Ie[i&31],(t.match(/.{1,4}/g)||[]).join("-")}function cn(e){if(typeof e!="string")throw new l("Recovery code should be a string.",{code:"INVALID_PARAMETER"});let t=e.toUpperCase().replace(/[\s\-_]/g,"").replace(/O/g,"0").replace(/[IL]/g,"1");if(t.length!==Yr)throw new l(`That does not look like a recovery code: expected ${Yr} characters, got ${t.length}.`,{code:"ENCRYPTION_BAD_RECOVERY_CODE"});let r=t.slice(0,Jr),n=t.slice(Jr),i=0,s=0,o=[];for(let u=0;u<r.length;u++){let g=Ie.indexOf(r[u]);if(g<0)throw new l(`That does not look like a recovery code: "${r[u]}" is not a valid character.`,{code:"ENCRYPTION_BAD_RECOVERY_CODE"});i=i<<5|g,s+=5,s>=8&&(s-=8,o.push(i>>s&255));}let a=new Uint8Array(o.slice(0,He)),d=an(a);if(n!==Ie[d>>5&31]+Ie[d&31])throw new l("That recovery code has a typo in it: the check characters do not match.",{code:"ENCRYPTION_BAD_RECOVERY_CODE"});return a}async function er(e,t,r){let n=await We(e,t,r,32),i=await oe(n);return M(n),i}var zt=[83,75,69,78,67,70],un=2,Ge=56,dn=16,Vo=4*1024*1024;function tr(e){if(!e||e.length<Ge)return false;for(let t=0;t<zt.length;t++)if(e[t]!==zt[t])return false;return true}function Pe(e,t,r){e[t]=r>>>24&255,e[t+1]=r>>>16&255,e[t+2]=r>>>8&255,e[t+3]=r&255;}function Ne(e,t){return (e[t]<<24>>>0)+(e[t+1]<<16)+(e[t+2]<<8)+e[t+3]}function $o(e,t,r){let n=Math.floor(r/4294967296);Pe(e,t,n),Pe(e,t+4,r>>>0);}function jo(e,t){return Ne(e,t)*4294967296+Ne(e,t+4)}async function fn(e,t,r,n,i,s){let o=K(`${Y}|binfile|${r}|${n}|${i}|${s}`),a=await We(e,t,o,32),d=await oe(a);return M(a),d}async function gn(e){return (await ht(Qt(K(`${Y}|dekid`),e))).subarray(0,8)}function pn(e,t,r){return Zt([`${Y}|binchunk`,q(e),t,r])}function Bo(e,t,r,n,i,s){let o=new Uint8Array(Ge+s.length);return o.set(zt,0),o[6]=un,o[7]=s.length?1:0,Pe(o,8,e),Pe(o,12,t),o.set(r,16),$o(o,32,n),o.set(i,40),Pe(o,48,s.length),Pe(o,52,0),s.length&&o.set(s,Ge),o}async function hn(e,t,r,n,i=Vo){let s=X(dn),o=await fn(e,s,r.service,r.owner,r.recordOwner,r.recordId),a=await gn(e),d=n?K(JSON.stringify(n)):new Uint8Array(0);if(d.length>4096)throw new l("Encrypted file metadata is too large.",{code:"INVALID_PARAMETER"});let u=t.length===0?1:Math.ceil(t.length/i),g=Bo(i,u,s,t.length,a,d),f=await ht(g),c=[],p=g.length;for(let w=0;w<u;w++){let b=t.subarray(w*i,Math.min((w+1)*i,t.length)),_=await ne(o,b,pn(f,w,u));c.push(_),p+=4+_.iv.length+_.ct.length;}let h=new Uint8Array(p);h.set(g,0);let m=g.length;for(let w of c)Pe(h,m,w.iv.length+w.ct.length),m+=4,h.set(w.iv,m),m+=w.iv.length,h.set(w.ct,m),m+=w.ct.length;return h}function Ko(e){if(!tr(e))throw new l("This file is not an encrypted skapi file.",{code:"INVALID_PARAMETER"});let t=Ne(e,48),r=Ge+t;if(e.length<r)throw new l("Encrypted file header is truncated.",{code:"INVALID_REQUEST"});let n=null;return t&&(n=JSON.parse(Be(e.subarray(Ge,r)))),{version:e[6],chunkBytes:Ne(e,8),count:Ne(e,12),fileId:e.subarray(16,16+dn),plainLen:jo(e,32),dekId:e.subarray(40,48),meta:n,headerLen:r}}async function mn(e,t,r){let n=Ko(t);if(n.version!==un)throw new l(`This file was encrypted by a different version of the SDK (container v${n.version}).`,{code:"NOT_SUPPORTED"});if(!n.count||!n.chunkBytes)throw new l("Encrypted file header is malformed.",{code:"INVALID_PARAMETER"});let i=await gn(e);if(!qo(i,n.dekId))throw new l("This file was encrypted under a previous data key for this record, so it can no longer be opened. It was most likely left behind by an interrupted access change.",{code:"ENCRYPTION_FILE_STALE_KEY"});let s=await fn(e,n.fileId,r.service,r.owner,r.recordOwner,r.recordId),o=await ht(t.subarray(0,n.headerLen)),a=[],d=n.headerLen,u=0;for(let c=0;c<n.count;c++){if(d+4>t.length)throw new l("Encrypted file is truncated.",{code:"INVALID_REQUEST"});let p=Ne(t,d);if(d+=4,p<Ke+16||d+p>t.length)throw new l("Encrypted file is truncated.",{code:"INVALID_REQUEST"});let h=await ae(s,t.subarray(d,d+Ke),t.subarray(d+Ke,d+p),pn(o,c,n.count));d+=p,a.push(h),u+=h.length;}let g=new Uint8Array(u),f=0;for(let c of a)g.set(c,f),f+=c.length;return {bytes:g,meta:n.meta}}var Ho="__skapi__keyring",ze="__skapi_enc__",bn=1,Go="skapi-enc",Ae="keys",nr=new WeakMap;function _n(e){if(!e)return null;if(e===true&&(e={}),typeof e!="object")throw new l('"options.encryption" should be a boolean or an object.',{code:"INVALID_PARAMETER"});let t=typeof e.iterations=="number"?e.iterations:Xr;if(t<1e5)throw new l('"encryption.iterations" must be at least 100000.',{code:"INVALID_PARAMETER"});let r=e.trustPolicy==="strict"?"strict":"tofu";return {enabled:true,iterations:t,trustPolicy:r,persistDevice:e.persistDevice!==false,minPasswordLength:typeof e.minPasswordLength=="number"?e.minPasswordLength:0,withheld:e.withheld==="sentinel"?"sentinel":"null",recovery:e.recovery==="none"?"none":"code",table:typeof e.table=="string"&&e.table?e.table:Ho}}function L(){return nr.get(this)||null}function wn(e){if(!e){nr.delete(this);return}nr.set(this,{cfg:e,status:"locked",reason:"NO_SESSION_KEY",user_id:"",scope:"",mk:null,ikPriv:null,pubRaw:null,fpr:"",keyringRecordId:"",pins:{},dek:new Map,roll:new Set,passthrough:new Map,rawRead:false,ready:null,unlocking:false,pendingRecoveryCode:"",peerPub:new Map,peerInflight:new Map});}function ir(){let e=L.call(this);if(e){e.user_id&&hr.call(this,e).catch(()=>{}),e.ready=null,e.unlocking=false,e.pendingRecoveryCode="";for(let[,t]of e.dek)M(t.bytes);e.dek.clear(),e.roll.clear(),e.passthrough.clear(),e.peerPub.clear(),e.peerInflight.clear(),e.pins={},e.mk=null,e.ikPriv=null,e.pubRaw=null,e.fpr="",e.keyringRecordId="",e.user_id="",e.status="locked",e.reason="NO_SESSION_KEY";}}function En(){let e=L.call(this);return e?{status:e.status,reason:e.status==="unlocked"?void 0:e.reason,user_id:e.user_id||void 0,fingerprint:e.fpr||void 0}:{status:"disabled"}}function An(e,t){return typeof t=="string"&&t===e.cfg.table}function xe(){return `${this.service}/${this.owner}`}function sr(e,t,r,n){let[i,s]=e.split("/");return Zt([Y,i,s,t,r,n])}function Rn(e,t,r,n,i){let[s,o]=e.split("/");return K(`${Y}|dekwrap|${s}|${o}|${t}|${r}|${n}|${i}`)}function or(e){return e.anch==="uid"?e.uid:e.anch==="rid"?e.rid:""}function bt(e){return !!e&&typeof e=="object"&&!Array.isArray(e)&&typeof e[ze]=="number"&&typeof e.ct=="string"&&typeof e.iv=="string"&&typeof e.own=="string"&&typeof e.anch=="string"&&!!e.k&&typeof e.k=="object"&&!Array.isArray(e.k)}var Tn="__skapi_no_access__";function ee(e,t,r){if(e.withheld!=="sentinel")return null;let n={[Tn]:true,reason:t};return r&&(n.recipients=r),Object.freeze(n)}function ar(e){return !!e&&typeof e=="object"&&e[Tn]===true}var Wo=256*1024,Xe="__skenc_ct__",In="payload.bin",Qo=`/${Xe}/${In}`;function lr(e,t){return e===Xe&&t===In}async function zo(e,t,r){let n=t?.table,i=typeof n=="string"?n:n?.name;if(n&&(typeof n=="string"||n.access_group!==void 0))return {group:typeof n=="string"?0:yn(n.access_group),table:i,record:null};if(!r)return {group:n?.access_group!==void 0?yn(n.access_group):0,table:i,record:null};let s=e.dek.get(r);if(s)return {group:s.access_group,table:i,record:null};let o=await Ee.call(this,r);if(!o)throw new l(`Record "${r}" not found.`,{code:"NOT_EXISTS"});return {group:o.table.access_group,table:o.table.name,record:o}}function Jo(e){return this.getFile(e,{dataType:"blob"})}async function Ee(e){let t=/^[a-zA-Z0-9]+$/.test(e)?{record_id:e}:{unique_id:e};return (await this.getRecords(t,{limit:1}))?.list?.[0]||null}function yn(e){return e==="private"||e==="*"||e==="**"?"private":e==="public"?0:e==="authorized"?1:e==="admin"?99:typeof e=="number"?e:0}function rr(e,t,r){let n=this.user?.user_id;if(!(!e||!e.user_id||!n||e.user_id===n))throw new l(`Record "${t}" belongs to another user (${e.user_id}), so ${r} would either seal it under the wrong key or strand its contents. Encryption only operates on records you own, no matter what access level you hold.`,{code:"ENCRYPTION_NOT_RECORD_OWNER"})}async function cr(e,t,r){let n=L.call(this);if(!n)return {send:e,plain:e,encrypted:false,omit:false};let i=t?.record_id||"",s=i,o=t?.unique_id||"";if(i&&n.passthrough.has(i)){let F=n.passthrough.get(i);return n.passthrough.delete(i),{send:F,plain:e,encrypted:true,omit:false}}let{group:a,table:d,record:u}=await zo.call(this,n,t,s);if(a!=="private"){let F=true;if(!r&&i){let Q=u||await Ee.call(this,i);if(Q&&Q.encrypted){if(rr.call(this,Q,i,"making it non-private"),Q.encrypted.status==="failed")throw new l(`Cannot make record "${i}" non-private: its current contents could not be decrypted (${Q.encrypted.reason}), so they cannot be written back in the clear. Unlock encryption, or supply the record's data with the access group change.`,{code:"ENCRYPTION_LOCKED"});let $e=!!Q.bin&&Object.keys(Q.bin).some(ut=>(Q.bin[ut]||[]).some(Vr=>Vr&&Vr.encrypted));if(!$e&&s){let ut=n.dek.get(s);ut&&(M(ut.bytes),n.dek.delete(s));}return {send:Q.data,plain:Q.data,encrypted:false,omit:false,files:$e?"decrypt":void 0}}}let z=u;i&&!z&&(z=await Ee.call(this,i).catch(()=>null)),z&&z.encrypted&&rr.call(this,z,i,"making it non-private");let ct=!!z&&!!z.bin&&Object.keys(z.bin).some(Q=>(z.bin[Q]||[]).some($e=>$e&&$e.encrypted));if(ct&&(F=false),F&&s){let Q=n.dek.get(s);Q&&(M(Q.bytes),n.dek.delete(s));}return {send:e,plain:e,encrypted:false,omit:!r,files:ct?"decrypt":void 0}}if(An(n,d))return {send:e,plain:e,encrypted:false,omit:false};if(n.ready&&!n.unlocking)try{await n.ready;}catch{}if(!r)return {send:e,plain:e,encrypted:false,omit:true};if(ar.call(this,e))throw new l("This record's data could not be decrypted by this session, so it cannot be written back. Writing it would replace the record with the placeholder.",{code:"ENCRYPTION_CANNOT_REWRITE_WITHHELD"});if(n.status!=="unlocked"||!n.mk)throw new l("Encryption is enabled but locked, so this private record cannot be written. Call unlockEncryption({ password }) first, or the user must log in with their password.",{code:"ENCRYPTION_LOCKED"});if(e&&typeof e=="object"&&!Array.isArray(e)&&Object.prototype.hasOwnProperty.call(e,ze))throw new l(`"${ze}" is a reserved key in record data.`,{code:"INVALID_PARAMETER"});if(t?.service&&t.service!==this.service||t?.owner&&t.owner!==this.owner)throw new l("Encrypted records cannot be written to another project. The encryption key is derived per project, so a record written under one service and read under another could never be decrypted. Construct a separate Skapi instance for that project.",{code:"INVALID_REQUEST"});let g=this.user?.user_id;if(!g)throw new l("User login is required to write an encrypted record.",{code:"INVALID_REQUEST"});let f=xe.call(this),c=false;if(i&&n.roll.has(i)){c=true,n.roll.delete(i);let F=n.dek.get(i);n.dek.delete(i),F&&M(F.bytes);}let p=u;i&&!p&&!n.dek.has(i)&&(p=await Ee.call(this,i).catch(()=>null)),p&&rr.call(this,p,i,"making it private");let h=!!p&&!p.encrypted&&!!p.bin&&Object.keys(p.bin).some(F=>(p.bin[F]||[]).some(z=>z&&!z.encrypted)),m=null;if(i&&!c&&(m=n.dek.get(i)||null,!m)){let F=p||u||await Ee.call(this,i);if(F&&(s=F.record_id||i,m=n.dek.get(s)||null,!o&&F.unique_id&&(o=F.unique_id),!m&&F.encrypted?.status==="failed"))throw new l(`Cannot update encrypted record "${i}": its current contents could not be decrypted (${F.encrypted.reason}), so its existing key wraps cannot be preserved. Updating anyway would revoke everyone it is shared with.`,{code:"ENCRYPTION_LOCKED"})}s===i&&m&&m.rid&&(s=m.rid),!o&&m&&m.anch==="uid"&&m.uid&&(o=m.uid);let w,b,_;if(m){if(m.own&&m.own!==g)throw new l(`Record "${i}" belongs to another user (${m.own}). Encryption only operates on records you own.`,{code:"ENCRYPTION_NOT_RECORD_OWNER"});w=m.bytes,b=m.key,_=Object.assign({},m.recipients);}else {let F=await tn();w=F.bytes,b=F.key,_={};}let E=o?"uid":s?"rid":"new",S=E==="uid"?o:E==="rid"?s:"",A=sr(f,g,E,S),N=Qe(A,g,"mk"),x=await ne(n.mk,w,N);_[g]={t:"mk",iv:q(x.iv),ct:q(x.ct)},m&&(m.anch!==E||or(m)!==S)&&(_=await Yo.call(this,n,w,_,f,g,E,S,A));let C=K(JSON.stringify(e===void 0?null:e)),v=await ne(b,C,A);M(C);let U={[ze]:bn,enc:"A256GCM",kw:"ECDH-ES+A256GCM",anch:E,uid:o,rid:s,own:g,iv:q(v.iv),ct:q(v.ct),k:_},O,V,de=U.ct;s&&de.length>Wo&&(O=$(de),U.ct="",U.ct_ref=Qo,m&&m.ctRef&&(V=m.ctRef));let ie=JSON.stringify(U).length;if(ie>2*1024*1024)throw new l(`Encrypted record data is too large: once encrypted and base64 encoded it becomes ${ie} bytes, over the ${2*1024*1024} byte limit. Encryption costs about 33% plus roughly 230 bytes per additional recipient.`,{code:"ENCRYPTED_DATA_TOO_LARGE"});return s&&n.dek.set(s,{bytes:w,key:b,recipients:_,anch:E,uid:o,rid:s,own:g,access_group:"private"}),{send:U,plain:e,encrypted:true,omit:false,spill:O,retireCt:V,dek:{bytes:w,key:b,recipients:_,anch:E,uid:o,rid:s,own:g,access_group:"private"},files:h?"encrypt":void 0}}function Pn(e,t){let r=L.call(this);!r||!t||!e||r.dek.has(e)||r.dek.set(e,Object.assign({},t,{rid:e}));}async function Yo(e,t,r,n,i,s,o,a){let d=Object.keys(r).filter(f=>f!==i);if(!d.length)return r;let u=await mr.call(this,d),g={[i]:r[i]};for(let f of d){let c=u[f];c&&(g[f]=await Sn.call(this,t,c,n,o,i,f,a));}return g}async function Sn(e,t,r,n,i,s,o){let a=Rn(r,n,i,s,t.fpr),d=Qe(o,s,t.fpr),u=await sn(t.pubRaw,e,a,d);return {t:"ecdh",epk:q(u.epk),iv:q(u.iv),ct:q(u.ct),fpr:t.fpr}}async function kn(e,t){if(!bt(e))return {value:e};if(t.access_group!=="private")return {value:e};let r=L.call(this);if(!r)return {value:null,flag:{status:"failed",reason:"ENCRYPTION_DISABLED"}};if(r.rawRead)return {value:e};if(An(r,t.table_name))return {value:e};if(e[ze]!==bn)return {value:ee(r.cfg,"UNSUPPORTED_VERSION"),flag:{status:"failed",reason:"UNSUPPORTED_VERSION"}};if(r.ready&&!r.unlocking)try{await r.ready;}catch{}if(e.own!==t.user_id)return {value:ee(r.cfg,"BINDING_MISMATCH"),flag:{status:"failed",reason:"BINDING_MISMATCH"}};if(e.uid&&t.unique_id&&e.uid!==t.unique_id)return {value:ee(r.cfg,"BINDING_MISMATCH"),flag:{status:"failed",reason:"BINDING_MISMATCH"}};if(e.rid&&t.record_id&&e.rid!==t.record_id)return {value:ee(r.cfg,"BINDING_MISMATCH"),flag:{status:"failed",reason:"BINDING_MISMATCH"}};let n=this.user?.user_id,i=n?e.k[n]:null;if(!i)return {value:ee(r.cfg,"NOT_A_RECIPIENT",Object.keys(e.k)),flag:{status:"failed",reason:"NOT_A_RECIPIENT",recipients:Object.keys(e.k)}};if(r.status!=="unlocked"||!r.mk)return {value:ee(r.cfg,"NO_SESSION_KEY"),flag:{status:"failed",reason:"NO_SESSION_KEY"}};let s=xe.call(this),o=or(e),a=sr(s,e.own,e.anch,o),d;try{if(i.t==="mk")d=await ae(r.mk,$(i.iv),$(i.ct),Qe(a,n,"mk"));else if(i.t==="ecdh"){if(!r.ikPriv)return {value:ee(r.cfg,"NO_SESSION_KEY"),flag:{status:"failed",reason:"NO_SESSION_KEY"}};d=await on(r.ikPriv,$(i.epk),$(i.iv),$(i.ct),Rn(s,o,e.own,n,i.fpr),Qe(a,n,i.fpr));}else return {value:ee(r.cfg,"UNSUPPORTED_VERSION"),flag:{status:"failed",reason:"UNSUPPORTED_VERSION"}}}catch{return {value:ee(r.cfg,"BAD_KEY"),flag:{status:"failed",reason:"BAD_KEY"}}}let u;try{if(e.ct_ref){if(!t.ctUrl)return M(d),{value:ee(r.cfg,"DATA_UNAVAILABLE"),flag:{status:"failed",reason:"DATA_UNAVAILABLE"}};let p=await Jo.call(this,t.ctUrl);u=new Uint8Array(await p.arrayBuffer());}else u=$(e.ct);}catch{return M(d),{value:ee(r.cfg,"DATA_UNAVAILABLE"),flag:{status:"failed",reason:"DATA_UNAVAILABLE"}}}let g,f;try{f=await oe(d),g=await ae(f,$(e.iv),u,a);}catch{return M(d),{value:ee(r.cfg,"CORRUPT"),flag:{status:"failed",reason:"CORRUPT"}}}let c;try{c=JSON.parse(Be(g));}catch{return M(g),M(d),{value:ee(r.cfg,"CORRUPT"),flag:{status:"failed",reason:"CORRUPT"}}}if(M(g),t.record_id){let p=r.dek.get(t.record_id);p?(p.bytes=d,p.key=f,p.recipients=e.k,p.anch=e.anch,p.uid=e.uid,p.own=e.own,p.access_group="private",p.ctRef=e.ct_ref||""):r.dek.set(t.record_id,{bytes:d,key:f,recipients:e.k,anch:e.anch,uid:e.uid,rid:t.record_id,own:e.own,access_group:"private",ctRef:e.ct_ref||""});}else M(d);return {value:c,flag:{status:"encrypted",recipients:Object.keys(e.k)}}}function Je(e,t){let[r,n]=e.split("/");return K(`${Y}|kek|${r}|${n}|${t}`)}function Ye(e,t,r,n){let[i,s]=e.split("/");return K(`${Y}|mk|${i}|${s}|${t}|PBKDF2-SHA256|${r}|${n}`)}function vn(e,t){let[r,n]=e.split("/");return K(`${Y}|recovery|${r}|${n}|${t}`)}function Nn(e,t,r){let[n,i]=e.split("/");return K(`${Y}|rk|${n}|${i}|${t}|HKDF-SHA256|${r}`)}function Dn(e,t){let[r,n]=e.split("/");return K(`${Y}|self|${r}|${n}|${t}`)}function xn(e,t){let[r,n]=e.split("/");return K(`${Y}|ik|${r}|${n}|${t}`)}async function _t(e){let r=((await this.getRecords({table:{name:e.cfg.table,access_group:"private"},index:{name:"$user_id",value:this.user.user_id,condition:"="}},{limit:2}))?.list||[]).filter(n=>n.user_id===this.user.user_id);return r.length?(r.sort((n,i)=>n.uploaded-i.uploaded),r[0]):null}async function ur(e,t,r){let n=X(He),i=ln(n),s=X(16),o=q(s),a=await er(n,s,vn(e,t)),d=await ne(a,r,Nn(e,t,o));return M(n),{code:i,wrap:{id:q(X(6)),p:"recovery",kdf:{a:"HKDF-SHA256",s:o},iv:q(d.iv),ct:q(d.ct),created:Date.now()}}}async function Xo(e,t,r,n){let i=cn(n),s=(r||[]).filter(o=>o.p==="recovery");s.sort((o,a)=>(a.created||0)-(o.created||0));for(let o of s)try{let a=await er(i,$(o.kdf.s),vn(e,t)),d=await ae(a,$(o.iv),$(o.ct),Nn(e,t,o.kdf.s));return M(i),d}catch{}return M(i),null}async function Zo(e,t,r,n,i){let s=X(16),o=q(s),a=await De(n,s,e.cfg.iterations,Je(t,r)),d=await ne(a,i,Ye(t,r,e.cfg.iterations,o));return {id:q(X(6)),p:"password",kdf:{a:"PBKDF2-SHA256",it:e.cfg.iterations,s:o},iv:q(d.iv),ct:q(d.ct),created:Date.now()}}async function ea(e,t){let r=this.user.user_id,n=e.scope,i=X(16),s=q(i),o=await De(t,i,e.cfg.iterations,Je(n,r)),a=X(32),d=await ne(o,a,Ye(n,r,e.cfg.iterations,s)),u=await oe(a),g=await rn(),f=await ne(u,g.pkcs8,xn(n,r));M(g.pkcs8);let c=null;e.cfg.recovery==="code"&&(c=await ur(n,r,a));let p=await ne(u,a,Dn(n,r));M(a);let h=await Xt(g.pubRaw),m=Date.now(),w=[{id:q(X(6)),p:"password",kdf:{a:"PBKDF2-SHA256",it:e.cfg.iterations,s},iv:q(d.iv),ct:q(d.ct),created:m}];c&&w.push(c.wrap);let b={v:1,alg:"ECDH-P-256",user_id:r,wraps:w,ik:{iv:q(f.iv),ct:q(f.ct)},self:{iv:q(p.iv),ct:q(p.ct)},pub:q(g.pubRaw),fpr:h,pins:null,created:m,updated:m};await this.postRecord({v:1,alg:"ECDH-P-256",user_id:r,pub:q(g.pubRaw),fpr:h,created:m},{table:{name:e.cfg.table,access_group:"authorized"},index:{name:"pubkey",value:r}});let _=await this.postRecord(b,{table:{name:e.cfg.table,access_group:"private"}}),E=await _t.call(this,e);if(E&&E.record_id!==_.record_id){await Un.call(this,e,E,t);return}e.mk=u,e.ikPriv=g.priv,e.pubRaw=g.pubRaw,e.fpr=h,e.keyringRecordId=_.record_id,c&&(e.pendingRecoveryCode=c.code),e.user_id=r,e.pins={},e.status="unlocked",e.reason="";}async function Un(e,t,r){let n=this.user.user_id,i=e.scope,s=t.data;if(t.user_id!==n||s&&s.user_id&&s.user_id!==n)throw new l("The encryption keyring does not belong to this user.",{code:"ENCRYPTION_KEYRING_CORRUPT"});let a=(Array.isArray(s?.wraps)?s.wraps:[]).filter(g=>g.p==="password");if(!a.length)throw new l("The keyring has no password wrap.",{code:"ENCRYPTION_KEYRING_CORRUPT"});a.sort((g,f)=>(f.created||0)-(g.created||0));let d=null;for(let g of a)try{let f=$(g.kdf.s),c=await De(r,f,g.kdf.it,Je(i,n));d=await ae(c,$(g.iv),$(g.ct),Ye(i,n,g.kdf.it,g.kdf.s));break}catch{}if(!d)throw new l("Incorrect password: the encryption keyring could not be opened.",{code:"ENCRYPTION_BAD_PASSWORD"});let u=await oe(d);M(d),await dr.call(this,e,t,u);}async function dr(e,t,r){let n=this.user.user_id,i=t.data,s=await ae(r,$(i.ik.iv),$(i.ik.ct),xn(e.scope,n)),o=await Yt(s);M(s);let a={};if(i.pins&&typeof i.pins=="object"&&i.pins.ct)try{let d=await ae(r,$(i.pins.iv),$(i.pins.ct),K(`${Y}|pins|${e.scope}|${n}`));a=JSON.parse(Be(d)),M(d);}catch{a={};}e.mk=r,e.ikPriv=o,e.pubRaw=$(i.pub),e.fpr=i.fpr,e.keyringRecordId=t.record_id,e.user_id=n,e.pins=a,e.status="unlocked",e.reason="";}async function wt(e){let t=L.call(this);if(!t||!this.user?.user_id)return;if(!Jt()){t.status="locked",t.reason="NO_WEB_CRYPTO";return}if(this.user?.is_openid){t.status="locked",t.reason="OPENID_UNSUPPORTED";return}if(t.cfg.minPasswordLength&&e.length<t.cfg.minPasswordLength){t.status="locked",t.reason="WEAK_PASSWORD";return}t.scope=xe.call(this);let r=await _t.call(this,t);r?await Un.call(this,t,r,e):await ea.call(this,t,e),t.cfg.persistDevice&&await Mn.call(this,t).catch(()=>{});}async function Cn(e){await this.__connection;let t=L.call(this);if(!t)throw new l("Encryption is not enabled for this instance.",{code:"INVALID_REQUEST"});if(!this.user?.user_id)throw new l("User login is required.",{code:"INVALID_REQUEST"});if(!e?.password||typeof e.password!="string")throw new l('"password" is required.',{code:"INVALID_PARAMETER"});if(await wt.call(this,e.password),t.status!=="unlocked")throw new l(`Encryption could not be unlocked: ${t.reason}`,{code:"ENCRYPTION_LOCKED"});return {status:t.status}}async function On(e){let t=L.call(this);return t?(e?.forgetDevice&&await hr.call(this,t).catch(()=>{}),ir.call(this),this.__cached_requests={},{status:t.status}):{status:"disabled"}}async function Ln(e,t){let r=L.call(this);if(!r)return;if(r.status!=="unlocked"||!r.mk)throw new l("Encryption must be unlocked before changing the password, or the encryption keyring would be left wrapped under a password that no longer exists. Call unlockEncryption({ password }) first.",{code:"ENCRYPTION_LOCKED"});let i=(await this.getRecords({record_id:r.keyringRecordId},{limit:1}))?.list?.[0];if(!i)throw new l("The encryption keyring could not be read, so the password change was stopped before it could strand it.",{code:"ENCRYPTION_KEYRING_CORRUPT"});let s=this.user.user_id,o=i.data,a=(o.wraps||[]).filter(m=>m.p==="password");a.sort((m,w)=>(w.created||0)-(m.created||0));let d=null;for(let m of a)try{let w=await De(e,$(m.kdf.s),m.kdf.it,Je(r.scope,s));d=await ae(w,$(m.iv),$(m.ct),Ye(r.scope,s,m.kdf.it,m.kdf.s));break}catch{}if(!d)throw new l("Incorrect current password: the encryption keyring was not re-wrapped.",{code:"ENCRYPTION_BAD_PASSWORD"});let u=X(16),g=q(u),f=await De(t,u,r.cfg.iterations,Je(r.scope,s)),c=await ne(f,d,Ye(r.scope,s,r.cfg.iterations,g));M(d);let p=Date.now(),h=(o.wraps||[]).concat([{id:q(X(6)),p:"password",kdf:{a:"PBKDF2-SHA256",it:r.cfg.iterations,s:g},iv:q(c.iv),ct:q(c.ct),created:p}]);await this.postRecord(Object.assign({},o,{wraps:h,updated:p}),{record_id:r.keyringRecordId});}async function Fn(){let e=L.call(this);if(!e||e.status!=="unlocked"||!e.keyringRecordId)return;let r=(await this.getRecords({record_id:e.keyringRecordId},{limit:1}))?.list?.[0];if(!r)return;let n=r.data,i=(n.wraps||[]).filter(o=>o.p==="password").sort((o,a)=>(a.created||0)-(o.created||0)),s=(n.wraps||[]).filter(o=>o.p!=="password");i.length<=1||await this.postRecord(Object.assign({},n,{wraps:[i[0]].concat(s),updated:Date.now()}),{record_id:e.keyringRecordId});}function fr(){return typeof indexedDB<"u"&&!!indexedDB}function gr(){return new Promise((e,t)=>{let r=indexedDB.open(Go,1);r.onupgradeneeded=()=>{let n=r.result;n.objectStoreNames.contains(Ae)||n.createObjectStore(Ae);},r.onsuccess=()=>e(r.result),r.onerror=()=>t(r.error);})}function pr(e){return `${e.scope}#${this.user?.user_id}`}async function Mn(e){if(!fr()||!e.mk)return;let t=await gr();await new Promise((r,n)=>{let i=t.transaction(Ae,"readwrite");i.objectStore(Ae).put({mk:e.mk,keyringRecordId:e.keyringRecordId,saved:Date.now()},pr.call(this,e)),i.oncomplete=()=>r(),i.onerror=()=>n(i.error);}),t.close();}async function ta(e){if(!fr())return null;let t=await gr(),r=await new Promise((n,i)=>{let o=t.transaction(Ae,"readonly").objectStore(Ae).get(pr.call(this,e));o.onsuccess=()=>n(o.result||null),o.onerror=()=>i(o.error);});return t.close(),r&&r.mk?r:null}async function hr(e){if(!fr())return;let t=await gr();await new Promise((r,n)=>{let i=t.transaction(Ae,"readwrite");i.objectStore(Ae).delete(pr.call(this,e)),i.oncomplete=()=>r(),i.onerror=()=>n(i.error);}),t.close();}function qn(){let e=L.call(this);!e||e.ready||(e.unlocking=true,e.ready=ra.bind(this)().catch(()=>false).then(()=>{e.unlocking=false;}));}async function ra(){let e=L.call(this);if(!e||!this.user?.user_id||!e.cfg.persistDevice||!Jt())return false;e.scope=xe.call(this);try{let t=await ta.call(this,e);if(!t)return !1;let r=await _t.call(this,e);return r?(await dr.call(this,e,r,t.mk),!0):(await hr.call(this,e).catch(()=>{}),!1)}catch{return e.status="locked",e.reason="NO_SESSION_KEY",false}}async function mr(e){let t=L.call(this);if(!t)throw new l("Encryption is not enabled for this instance.",{code:"INVALID_REQUEST"});let r={},n=[],i=false;for(let s of e){let o=t.peerPub.get(s);o?r[s]=o:n.push(s);}return await Promise.all(n.map(async s=>{let o=t.peerInflight.get(s);o||(o=(async()=>{let u=((await this.getRecords({table:{name:t.cfg.table,access_group:"authorized"},index:{name:"$user_id",value:s,condition:"="}},{limit:10}))?.list||[]).filter(p=>p.user_id===s&&p.data?.pub);if(!u.length)return null;u.sort((p,h)=>h.uploaded-p.uploaded);let g=$(u[0].data.pub),f=await Xt(g),c=t.pins[s];if(c&&c!==f)throw new l(`The public key for user "${s}" has changed since it was first seen. This is expected if they reset their account, and is what a key substitution attack also looks like. Verify the new fingerprint out of band, then call pinPeerKey({ user_id, fingerprint }).`,{code:"ENCRYPTION_PEER_KEY_CHANGED"});if(!c){if(t.cfg.trustPolicy==="strict")throw new l(`No pinned key for user "${s}" and trustPolicy is "strict". Pin it first with pinPeerKey().`,{code:"ENCRYPTION_PEER_NOT_PINNED"});t.pins[s]=f,i=true;}return {pubRaw:g,fpr:f}})().finally(()=>t.peerInflight.delete(s)),t.peerInflight.set(s,o));let a=await o;a&&t.peerPub.set(s,a),r[s]=a;})),i&&await Bn.call(this,t).catch(()=>{}),r}async function Vn(e,t){let r=xe.call(this),n=e.dek.get(t);if(n)return {entry:n,scope:r};let i=await Ee.call(this,t);if(!i)throw new l(`Record "${t}" not found.`,{code:"NOT_EXISTS"});if(i.encrypted?.status==="failed"&&i.encrypted.reason==="DATA_UNAVAILABLE")throw new l(`Cannot change sharing on record "${t}": its data could not be read, so whether it is encrypted is unknown. Retry once the record reads normally.`,{code:"ENCRYPTION_DATA_UNAVAILABLE"});if(!i.encrypted)return null;if(i.user_id!==this.user?.user_id)throw new l("Only the record owner can share or revoke an encrypted record, because adding or removing a key wrap means writing the record.",{code:"ENCRYPTION_GRANT_REQUIRES_OWNER"});let s=e.dek.get(i.record_id)||e.dek.get(t);if(!s)throw new l(`Cannot change sharing on record "${t}": its data could not be decrypted`+(i.encrypted.reason?` (${i.encrypted.reason})`:"")+".",{code:"ENCRYPTION_LOCKED"});return {entry:s,scope:r}}async function yr(e,t){let r=L.call(this);if(!r)return;let n=await Vn.call(this,r,e);if(!n)return;let{entry:i,scope:s}=n,o=this.user.user_id;if(i.own!==o)throw new l("Only the record owner can share an encrypted record, because adding a key wrap means writing the record.",{code:"ENCRYPTION_GRANT_REQUIRES_OWNER"});let a=await mr.call(this,t),d=t.filter(c=>!a[c]);if(d.length)throw new l(`These users have no encryption key yet, so they cannot be given access: ${d.join(", ")}. A user's key is created the first time they log in with encryption enabled.`,{code:"ENCRYPTION_RECIPIENT_HAS_NO_KEY"});let u=or(i),g=sr(s,i.own,i.anch,u),f=Object.assign({},i.recipients);for(let c of t)c!==o&&(f[c]=await Sn.call(this,i.bytes,a[c],s,u,i.own,c,g));await ia.call(this,r,e,i,f);}async function $n(e,t){let r=L.call(this);if(!r)return;let n=await Vn.call(this,r,e);if(!n)return;let{entry:i}=n,s=this.user.user_id;if(i.own!==s)throw new l("Only the record owner can revoke access to an encrypted record.",{code:"ENCRYPTION_GRANT_REQUIRES_OWNER"});let o=Object.keys(i.recipients).filter(u=>u===s?true:t?!t.includes(u):false).filter(u=>u!==s),a=await Ee.call(this,e);if(!a)throw new l(`Record "${e}" not found.`,{code:"NOT_EXISTS"});na(a,e);let d={};if(o.length){d=await mr.call(this,o);let u=o.filter(g=>!d[g]);if(u.length)throw new l(`Cannot revoke on record "${e}": these users keep access but their encryption keys could not be read, so re-sharing after the key roll would fail and lock them out: ${u.join(", ")}.`,{code:"ENCRYPTION_RECIPIENT_HAS_NO_KEY"})}r.roll.add(a.record_id||e),await this.postRecord(a.data,{record_id:a.record_id||e,table:{name:a.table.name,access_group:"private"}}),o.length&&await yr.call(this,a.record_id||e,o);}function na(e,t){if(e?.encrypted?.status==="failed")throw new l(`Cannot change sharing on record "${t}": its current data could not be read (${e.encrypted.reason}), so re-writing the record would destroy it.`,{code:"ENCRYPTION_DATA_UNAVAILABLE"})}async function ia(e,t,r,n){let i=await sa.call(this,t);if(!i)throw new l(`Cannot change sharing on record "${t}": its stored envelope could not be read.`,{code:"ENCRYPTION_DATA_UNAVAILABLE"});r.recipients=n,e.dek.set(t,r);let s=Object.assign({},i,{k:n});e.passthrough.set(t,s),await this.postRecord(void 0,{record_id:t});}async function sa(e){let t=L.call(this);if(!t)return null;t.rawRead=true;let r;try{r=(await this.getRecords({record_id:e},{limit:1}))?.list?.[0];}finally{t.rawRead=false;}return r&&bt(r.data)?r.data:null}async function jn(e){let t=L.call(this);if(!t||t.status!=="unlocked")throw new l("Encryption is locked.",{code:"ENCRYPTION_LOCKED"});t.pins[e.user_id]=e.fingerprint,t.peerPub.delete(e.user_id),await Bn.call(this,t);}async function Bn(e){if(!e.mk||!e.keyringRecordId)return;let r=(await this.getRecords({record_id:e.keyringRecordId},{limit:1}))?.list?.[0];if(!r)return;let n=await ne(e.mk,K(JSON.stringify(e.pins)),K(`${Y}|pins|${e.scope}|${e.user_id}`));await this.postRecord(Object.assign({},r.data,{pins:{iv:q(n.iv),ct:q(n.ct)},updated:Date.now()}),{record_id:e.keyringRecordId});}function Kn(){let e=L.call(this);if(!e||!e.pendingRecoveryCode)return null;let t=e.pendingRecoveryCode;return e.pendingRecoveryCode="",t}async function Hn(e){await this.__connection;let t=L.call(this);if(!t)throw new l("Encryption is not enabled for this instance.",{code:"INVALID_REQUEST"});if(!this.user?.user_id)throw new l("User login is required. Reset the password and log in first, then use the recovery code.",{code:"INVALID_REQUEST"});if(!e?.code||typeof e.code!="string")throw new l('"code" is required.',{code:"INVALID_PARAMETER"});t.scope=xe.call(this);let r=this.user.user_id,n=await _t.call(this,t);if(!n)throw new l("This account has no encryption keyring, so there is nothing to recover.",{code:"NOT_EXISTS"});let i=await Xo(t.scope,r,n.data?.wraps||[],e.code);if(!i)throw new l("That recovery code did not open the keyring. Check it against the copy you saved when encryption was set up.",{code:"ENCRYPTION_BAD_RECOVERY_CODE"});let s=await oe(i);await dr.call(this,t,n,s);let o=false,a=null,d=(n.data?.wraps||[]).slice();if(e.password&&(d=d.filter(u=>u.p!=="password"),d.push(await Zo(t,t.scope,r,e.password,i)),o=true),t.cfg.recovery==="code"){let u=await ur(t.scope,r,i);d=d.filter(g=>g.p!=="recovery"),d.push(u.wrap),a=u.code;}return M(i),await this.postRecord(Object.assign({},n.data,{wraps:d,updated:Date.now()}),{record_id:n.record_id}),t.cfg.persistDevice&&await Mn.call(this,t).catch(()=>{}),{status:t.status,repaired:o,recoveryCode:a}}async function Gn(){await this.__connection;let e=L.call(this);if(!e)throw new l("Encryption is not enabled for this instance.",{code:"INVALID_REQUEST"});if(e.status!=="unlocked"||!e.mk)throw new l("Encryption must be unlocked to issue a recovery code. Only someone who can already decrypt can create one.",{code:"ENCRYPTION_LOCKED"});if(e.cfg.recovery!=="code")throw new l('Recovery codes are disabled for this instance ("recovery" is "none").',{code:"INVALID_REQUEST"});let r=(await this.getRecords({record_id:e.keyringRecordId},{limit:1}))?.list?.[0];if(!r)throw new l("The encryption keyring could not be read.",{code:"ENCRYPTION_KEYRING_CORRUPT"});let n=r.data?.self;if(!n||!n.ct)throw new l("This keyring predates recovery-code rotation and cannot issue a new code. Use unlockWithRecoveryCode() with the existing code, which issues a replacement.",{code:"ENCRYPTION_KEYRING_CORRUPT"});let i=await ae(e.mk,$(n.iv),$(n.ct),Dn(e.scope,e.user_id)),s=await ur(e.scope,e.user_id,i);M(i);let o=(r.data.wraps||[]).filter(a=>a.p!=="recovery").concat([s.wrap]);return await this.postRecord(Object.assign({},r.data,{wraps:o,updated:Date.now()}),{record_id:e.keyringRecordId}),{recoveryCode:s.code}}var yt="__skenc__",Wn="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function oa(e){if(e===0)return "0";let t="";for(;e>0;)t=Wn[e%62]+t,e=Math.floor(e/62);return t}function aa(e){let t=0;for(let r of e){let n=Wn.indexOf(r);if(n<0)return NaN;t=t*62+n;}return t}function Et(e){if(typeof e!="string")return null;let t=e.lastIndexOf(yt);if(t<0)return null;let r=aa(e.slice(t+yt.length));return Number.isFinite(r)?{key:e.slice(0,t),plainSize:r}:null}function br(e){try{let t=String(e).split("?")[0].split("/").slice(3);if(t.length<12||t[4]!=="records"||t[7]!=="bin")return null;let r=Et(t[10]);return r?{recordId:t[5],recordOwner:t[3],filename:t[t.length-1],plainSize:r.plainSize}:null}catch{return null}}function Qn(e,t){return {service:this.service,owner:this.owner,recordOwner:t,recordId:e}}async function zn(e,t,r){let n=L.call(this);if(!n||!e)return {key:t,file:r,encrypted:false};let i=n.dek.get(e);if(!i)return {key:t,file:r,encrypted:false};if(Et(t))throw new l(`"${yt}" is reserved in an upload form key.`,{code:"INVALID_PARAMETER"});if(t===Xe)return {key:t,file:r,encrypted:false};let s=new Uint8Array(await r.arrayBuffer()),o={n:r.name,t:r.type||"",lm:r.lastModified||0},a=await hn(i.bytes,s,Qn.call(this,e,i.own),o);return M(s),{key:`${t}${yt}${oa(r.size)}`,file:new File([a],r.name,{type:"application/octet-stream"}),encrypted:true}}async function Jn(e,t){let r=L.call(this),n=br(e);if(!r||!n)return t;let i=r.dek.get(n.recordId);if(!i)throw new l(`Cannot open this file: the data key for record "${n.recordId}" is not available. Read the record first, and make sure encryption is unlocked.`,{code:"ENCRYPTION_LOCKED"});let s=new Uint8Array(await t.arrayBuffer());if(!tr(s))throw new l("This file is marked as encrypted but its contents are not an encrypted container.",{code:"ENCRYPTION_FILE_CORRUPT"});let o=await mn(i.bytes,s,Qn.call(this,n.recordId,n.recordOwner)),a=o.meta&&o.meta.t||"application/octet-stream";return new Blob([o.bytes],{type:a})}function la(e){let t=[];for(let r in e?.bin||{})for(let n of e.bin[r]||[])n&&n.encrypted&&t.push({formKey:r,url:n.url,filename:n.filename});return t}function ca(e){let t=[];for(let r in e?.bin||{})for(let n of e.bin[r]||[])n&&!n.encrypted&&t.push({formKey:r,url:n.url,filename:n.filename});return t}async function _r(e,t,r){let n=L.call(this);if(!n)return [];let i=await Ee.call(this,e);if(!i)return [];let s=t==="decrypt"?la(i):ca(i);if(!s.length)return [];let o=[],a=new FormData,d=false;for(let u of s){let g=i.bin[u.formKey].find(c=>c.url===u.url);if(!g||typeof g.getFile!="function")continue;let f=await g.getFile("blob");f&&(a.append(u.formKey,new File([f],u.filename,{type:f.type||"application/octet-stream"})),o.push(u.url),d=true);}if(!d)return [];if(t==="decrypt"){let u=n.dek.get(e);u&&(M(u.bytes),n.dek.delete(e));}return await this.uploadFiles(a,{record_id:e,progress:r}),o}var B=null;function Tt(e){let t={tkid:"ticket_id",cond:"condition",stmp:"timestamp",upd:"updated",acts:"actions",actn:"action",cnt:"count",ttl:"time_to_live",plch:"placeholder",hash:"hash",desc:"description",pmc:"limit_per_user",fail:"failed"},r={};for(let n in e)if(n==="tkid"){let i=e[n].split("#");if(i.length===1){r.ticket_id=i[0];continue}r.ticket_id=i[1],r.consume_id=i[2],r.user_id=i.slice(3).join("#");let s=i[2].slice(-4);if(r.is_test=s===":CHK",!e.stmp){let o=i[2].slice(0,-4);/^[0-9]+$/.test(o)?r.timestamp=parseInt(o,10):r.timestamp=se(i[2].slice(0,-4));}}else t[n]?r[t[n]]=e[n]:r[n]=e[n];return r}async function Xn(e){if(!e?.ticket_id)throw new l("Ticket ID is required.",{code:"INVALID_PARAMETER"});if(!/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(e.ticket_id))throw new l('Invalid "ticket_id". Use letters, digits, "_" and "-" (up to 64 chars, starting with a letter or digit).',{code:"INVALID_PARAMETER"});if(!e.method)throw new l('Method is required. Should be either "GET" or "POST"',{code:"INVALID_PARAMETER"});let t=String(e.method).toUpperCase();if(t!=="GET"&&t!=="POST")throw new l('Method should be either "GET" or "POST".',{code:"INVALID_PARAMETER"});let r=!!e.auth;if(r&&t==="GET")throw new l("Signed-in consumption is POST only.",{code:"INVALID_PARAMETER"});await this.__connection;let n=r?"tpa":t==="GET"?"tg":"tp",i=`https://${this.service.slice(0,4)}.${this.customApiDomain}/${n}/${this.service}/${e.ticket_id}`,s=await k.bind(this)(i,e.data||{},{method:t,auth:r},{ignoreService:true});if(s&&typeof s=="object"&&s.stage)throw new l(s.message,{code:s.code,cause:s});return !s||typeof s!="object"?s:Tt(s)}async function Zn(e,t){await this.__connection;let r=await k.bind(this)("ticket",Object.assign({exec:"list"},e||{}),{auth:true,fetchOptions:t});return r.list=r.list.map(Tt),r}async function ei(e,t){await this.__connection;let r=await k.bind(this)("ticket",Object.assign({exec:"consumed"},e||{}),{auth:true,fetchOptions:t});return r.list=r.list.map(Tt),r}async function ti(e){let t=await k.bind(this)("register-ticket",Object.assign({exec:"reg"},e),{auth:true});return t&&typeof t=="object"&&t.ticket&&(t.ticket=Tt(t.ticket)),t}async function ri(e){return k.bind(this)("register-ticket",Object.assign({exec:"unreg"},e),{auth:true})}var ha=3600;async function Ce(){if(await this.__connection,this.session){let e=Math.floor(Date.now()/1e3),r=this.session.getIdToken().getExpiration();if(r<e+ha){this.log("request:requesting new token",null);try{await G.bind(this)().getSession({refreshToken:!0}),this.log("request:received new tokens",{exp:this.session?.idToken?.payload?.exp,currentTime:e,expiresIn:r-e,token:this.session?.accessToken?.jwtToken,refreshToken:this.session?.refreshToken?.token});}catch(n){throw this.log("request:new token error",n),new l("User login is required.",{code:"INVALID_REQUEST"})}}else this.log("request:tokens",{exp:this.session.idToken.payload.exp,currentTime:e,expiresIn:r-e,token:this.session.accessToken.jwtToken,refreshToken:this.session.refreshToken.token});return this.session?.idToken?.jwtToken}else throw this.log("request:no session",null),be.bind(this)(),new l("User login is required.",{code:"INVALID_REQUEST"})}function Yn(e,t){return new Promise((r,n)=>{t.refreshSession(e.getRefreshToken(),(i,s)=>{this.log("getSession:refreshSessionCallback",{refreshErr:i,refreshedSession:s}),i?(be.bind(this)(),n(i)):s.isValid()?r(s):(be.bind(this)(),n(new l("Invalid session.",{code:"INVALID_REQUEST"})));});})}function G(){if(!this.userPool)throw new l("User pool is missing",{code:"INVALID_REQUEST"});let e=()=>{let s=B.getSignInUserSession().getIdToken().payload||null,o=je(s);return this.log("normalized user attribute",o),this.__user=o,o},t=async s=>new Promise((o,a)=>{this.log("getSession:option",s);let{refreshToken:d=false,skipUserUpdateEventTrigger:u=false}=s||{};if(d&&u&&(u=false),B=this.userPool.getCurrentUser(),!B){this.log("getSession:cognitoUser",B),be.bind(this)(),a(null);return}let g=f=>{let c=f.getIdToken().payload;if(this.log("getSession:respond:sessionAttribute",c),c["custom:service"]!==this.service)throw this.log("getSession:respond","invalid service, signing out"),be.bind(this)(),new l("Invalid session.",{code:"INVALID_REQUEST"});return this.session=f,e(),u||this._runOnUserUpdateListeners(this.user),this.session};B.getSession((f,c)=>{if(this.log("getSession:getSessionCallback",{err:f,session:c}),!c){be.bind(this)(),a(new l("Current session does not exist.",{code:"INVALID_REQUEST"}));return}if(f){Yn.bind(this)(c,B).then(b=>o(g(b))).catch(a);return}let p=Math.floor(Date.now()/1e3),h=c.getIdToken(),m=h.getExpiration(),w=m<p;if(this.log("getSession:currentTime",p),this.log("getSession:idTokenExp",m),this.log("getSession:isExpired",w),this.log("getSession:existingBearerToken",this.bearerToken),this.bearerToken=h.getJwtToken(),w||d||!c.isValid())Yn.bind(this)(c,B).then(b=>o(g(b))).catch(a);else try{o(g(c));}catch(b){a(b);}});}),r=(s,o)=>{let a=o||s.includes(this.service+"-")?s:this.service+"-"+Z.hash(s);return {cognitoUser:new CognitoUser({Username:a,Pool:this.userPool}),cognitoUsername:a}};return {getSession:t,authenticateUser:(s,o,a=false,d=false)=>new Promise((u,g)=>{this.__request_signup_confirmation=null,this.__disabledAccount=null;let f=r(s,a),c=f.cognitoUsername,p=new AuthenticationDetails({Username:c,Password:o});f.cognitoUser.authenticateUser(p,{newPasswordRequired:(h,m)=>{this.__disabledAccount=null,this.__request_signup_confirmation=c,h["custom:signup_ticket"]==="PASS"||h["custom:signup_ticket"]==="MEMBER"||h["custom:signup_ticket"]==="OIDPASS"?f.cognitoUser.completeNewPasswordChallenge(o,{},{onSuccess:w=>{B=f.cognitoUser,t().then(async b=>{if(L.call(this))try{await wt.bind(this)(o);}catch(_){this.log("encryption:ensureKeyring:failed",_);}u(this.user);});},onFailure:w=>{g(new l(w.message||"Failed to authenticate user.",{code:w.code}));}}):g(new l("User's signup confirmation is required.",{code:"SIGNUP_CONFIRMATION_NEEDED"}));},onSuccess:h=>t({skipUserUpdateEventTrigger:true}).then(async m=>{if(this.__disabledAccount=null,L.call(this))try{await wt.bind(this)(o);}catch(w){this.log("encryption:ensureKeyring:failed",w);}this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user),u(this.user);}),onFailure:h=>{let m=[],{parsed:w,code:b}=Rt(h),_=typeof h?.message=="string"?h.message:"";if(b==="NotAuthorizedException"?_.includes("User is disabled.")?(this.__disabledAccount=c,m=["This account is disabled.","USER_IS_DISABLED"]):d?m=["The account already exists.","ACCOUNT_EXISTS"]:m=["Incorrect username or password.","INCORRECT_USERNAME_OR_PASSWORD"]:b==="UserNotFoundException"?m=["Incorrect username or password.","INCORRECT_USERNAME_OR_PASSWORD"]:b==="UserNotConfirmedException"?(this.__request_signup_confirmation=c,m=["User's signup confirmation is required.","SIGNUP_CONFIRMATION_NEEDED"]):(b==="TooManyRequestsException"||b==="LimitExceededException")&&(m=["Too many attempts. Please try again later.","REQUEST_EXCEED"]),w.code==="SIGNUP_CONFIRMATION_NEEDED"&&(this.__request_signup_confirmation=c),m.length){let E=m[1],S=m[0];g(new l(S,{code:E,cause:h}));}else g(w);}});}),createCognitoUser:r,signup:(s,o,a)=>new Promise((d,u)=>{this.userPool.signUp(s,o,a,null,(g,f)=>{if(g){let{parsed:c,code:p}=Rt(g),h=[];p==="UsernameExistsException"?h=["The account already exists.","EXISTS"]:p==="InvalidPasswordException"?h=["Invalid password. Password must be at least 6 characters.","INVALID_PARAMETER"]:p==="InvalidParameterException"?h=[c.message||"Invalid parameter.","INVALID_PARAMETER"]:p==="TooManyRequestsException"||p==="LimitExceededException"?h=["Too many attempts. Please try again later.","REQUEST_EXCEED"]:p==="CodeDeliveryFailureException"?h=["Failed to deliver verification code.","CODE_DELIVERY_FAILURE"]:p==="UserLambdaValidationException"&&(h=[c.message||"Signup validation failed.",c.code==="EXISTS"?"EXISTS":"INVALID_REQUEST"]),h.length?u(new l(h[0],{code:h[1],cause:g})):u(c);return}d(f);});})}}function Rt(e){let t=typeof e?.code=="string"&&e.code.trim()?e.code.trim():"ERROR",n=((typeof e?.message=="string"?e.message:typeof e=="string"?e:"An error occurred.")||"An error occurred.").trim();n||(n="An error occurred.");let i=n.match(/#([A-Za-z0-9_]+)\s*:\s*([\s\S]+)/),s=i?.[1]?.trim()||t,o=i?.[2]?.trim()||n;return {parsed:new l(o,{code:s,cause:e}),code:t}}async function ni(e){await this.__authConnection;let t=e?.refreshToken||false;if(!t)return this.user;try{return await G.bind(this)().getSession(Object.assign({skipUserUpdateEventTrigger:!t,refreshToken:t},e)),this.user}catch{return null}}async function ii(e){await this.__connection,e=y.Params(e,{token:"string",id:"string",merge:o=>{if(o===void 0)return false;if(typeof o=="string")return [o];if(Array.isArray(o)){for(let a of o)if(typeof a!="string")throw new l('"merge" array items should be type: <string>.',{code:"INVALID_PARAMETER"})}if(typeof o!="boolean"&&!Array.isArray(o))throw new l('"merge" should be type: <boolean | string[]>.',{code:"INVALID_PARAMETER"});return o},template:o=>{if(typeof o!="object"||o===null)throw new l('"template" should be type: <object>.',{code:"INVALID_PARAMETER"});if(o.welcome!==void 0&&(typeof o.welcome!="string"||!o.welcome))throw new l('"template.welcome" should be a non-empty <string> (template message_id).',{code:"INVALID_PARAMETER"});return o}});let t={token:e.token,id:e.id,merge:e.merge};e.template?.welcome&&(t.template_welcome=e.template.welcome);let r=await k.bind(this)("openid-logger",t),n=r.logger.split("#"),i=this.service+"-"+n[0],s=n[1];return {userProfile:await G.bind(this)().authenticateUser(i,s,true,true),openid:r.openid}}function ma(e){let t=typeof globalThis<"u"?globalThis:void 0;if(t?.Buffer)return t.Buffer.from(e,"base64").toString("utf8");if(typeof atob=="function"){let r=atob(e),n=new Uint8Array(r.length);for(let i=0;i<r.length;i++)n[i]=r.charCodeAt(i);return typeof TextDecoder<"u"?new TextDecoder().decode(n):r}throw new Error("No base64 decoder available in this environment")}function ya(e){let t=e.split(".");if(t.length!==3)throw new Error("Invalid JWT format");let n=t[1].replace(/-/g,"+").replace(/_/g,"/"),i=ma(n);return JSON.parse(i)}async function si(e){await this.__authConnection,this.log("loginWithToken:params",e),e=y.Params(e,{idToken:"string",accessToken:"string",refreshToken:"string"},["idToken"]);let t=ya(e.idToken);if(this.log("loginWithToken:idTokenPayload",t),t["custom:service"]!==this.service)throw new l("Token does not belong to this service.",{code:"INVALID_REQUEST"});let r=Math.floor(Date.now()/1e3);if(t.exp&&t.exp<r)throw new l("Token has expired.",{code:"INVALID_REQUEST"});if(this.__user=je(t),this.session=null,e.accessToken&&e.refreshToken)try{if(this.session=new CognitoUserSession({IdToken:new CognitoIdToken({IdToken:e.idToken}),AccessToken:new CognitoAccessToken({AccessToken:e.accessToken}),RefreshToken:new CognitoRefreshToken({RefreshToken:e.refreshToken})}),this.log("loginWithToken:session",this.session),this.log("loginWithToken:CognitoUser",CognitoUser),this.log("loginWithToken:userPool",this.userPool),CognitoUser&&this.userPool){this.log("loginWithToken:cognito:username",t["cognito:username"]);let n={Username:t["cognito:username"],Pool:this.userPool};this.log("loginWithToken:cognitoUserParams",n),B=new CognitoUser(n),B.setSignInUserSession(this.session),this.log("loginWithToken:cognitoUserRestored",{cognitoUserType:typeof B,cognitoUserKeys:Object.keys(B||{}),cognitoUser:B});}}catch(n){this.log("loginWithToken:err",n);try{this.log("loginWithToken:err:stringified",JSON.stringify(n));}catch{this.log("loginWithToken:err:stringifyFail",String(n));}try{let i=Object.keys(n||{}),s=Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(n||{}):[],o=Object.getOwnPropertyDescriptors?Object.getOwnPropertyDescriptors(n||{}):{};this.log("loginWithToken:createSessionError:allKeys",{keys:i,symbols:s,descriptors:o});}catch(i){this.log("loginWithToken:createSessionError:allKeysFail",String(i));}}return this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user),this.user}async function W(){return await this.__connection,this.__user?.service===this.service?this.__user?.owner===this.host:(await Ze.bind(this)(),false)}async function be(e=false){let t=null;B&&(e?t=new Promise((n,i)=>{B.globalSignOut({onSuccess:s=>{this.log("globalSignOut:success",s),n(s);},onFailure:s=>{this.log("globalSignOut:error",s),i(s);}});}):B.signOut()),ir.bind(this)();let r={session:null,__startKeyHistory:{},__cached_requests:{},__user:null};t&&(t=await t);for(let n in r)this[n]=r[n];return this._runOnUserUpdateListeners(null),this._runOnLoginListeners(null),t}async function Ze(e){await this.__connection;let{data:t}=j(e);return await be.bind(this)(t?.global),"SUCCESS: The user has been logged out."}async function oi(){if(!this.__request_signup_confirmation)throw new l("Least one login attempt is required.",{code:"INVALID_REQUEST"});return await k.bind(this)("confirm-signup",{username:this.__request_signup_confirmation})}async function ai(e=false){if(typeof e=="string")e=y.Url(e);else if(typeof e!="boolean")throw new l("Argument should be type: <boolean | string>.",{code:"INVALID_REQUEST"});if(!this.__disabledAccount)throw new l("Least one signin attempt of disabled account is required.",{code:"INVALID_REQUEST"});return await k.bind(this)("recover-account",{username:this.__disabledAccount,redirect:e}),"SUCCESS: Recovery e-mail has been sent."}async function wr(e){let t=y.Params(e,{username:"string",email:"string",password:"string"},["password"]);await this.__authConnection;let r=null;if(t.email)try{r=y.Email(t.email);}catch{t.username=t.email,delete t.email;}if(!t.username&&!t.email)throw new l('Least one of "username" or "email" is required.',{code:"INVALID_PARAMETER"});let n=t.username||t.email;try{return await G.bind(this)().authenticateUser(n,t.password)}catch(i){if((i?.code==="UserNotFoundException"||i?.code==="NotAuthorizedException")&&r&&r!==n)return await G.bind(this)().authenticateUser(r,t.password);throw i}}async function li(e,t){await this.__authConnection;let r={username:"string",password:u=>y.Password(u),email:u=>y.Email(u),name:"string",address:u=>{if(!u)return "";if(typeof u=="string")return u;if(typeof u=="object")return JSON.stringify(u)},gender:"string",birthdate:u=>u?y.Birthdate(u):"",phone_number:u=>u?y.PhoneNumber(u):"",email_public:["boolean",()=>false],address_public:["boolean",()=>false],gender_public:["boolean",()=>false],birthdate_public:["boolean",()=>false],phone_number_public:["boolean",()=>false],access_group:"number",misc:"string",picture:u=>u?y.Url(u):"",profile:u=>u?y.Url(u):"",family_name:"string",given_name:"string",middle_name:"string",nickname:"string",website:u=>u?y.Url(u):""},n=y.Params(e||{},r,["email","password"]);await Ze.bind(this)(),t=y.Params(t||{},{email_subscription:u=>{if(typeof u!="boolean")throw new l('"option.email_subscription" should be type: <boolean>.',{code:"INVALID_PARAMETER"});if(!t?.signup_confirmation)throw new l('"option.signup_confirmation" is required for email subscription.',{code:"INVALID_PARAMETER"});return u},signup_confirmation:u=>{let g=u;if(typeof u=="string")g=y.Url(u);else if(typeof u=="boolean")g=u;else throw new l('"option.signup_confirmation" should be type: <string | boolean>.',{code:"INVALID_PARAMETER"});if(g&&!n.email)throw new l('"email" is required for signup confirmation.',{code:"INVALID_PARAMETER"});return g},login:u=>{if(typeof u=="boolean"){if(t.signup_confirmation&&u)throw new l('"login" is not allowed when "option.signup_confirmation" is true.',{code:"INVALID_PARAMETER"});return u}throw new l('"option.login" should be type: boolean.',{code:"INVALID_PARAMETER"})},template:u=>{if(typeof u!="object"||u===null)throw new l('"option.template" should be type: <object>.',{code:"INVALID_PARAMETER"});if(u.signup_confirmation!==void 0){if(typeof u.signup_confirmation!="string"||!u.signup_confirmation)throw new l('"option.template.signup_confirmation" should be a non-empty <string> (template message_id).',{code:"INVALID_PARAMETER"});if(!t?.signup_confirmation)throw new l('"option.signup_confirmation" is required when "option.template.signup_confirmation" is set.',{code:"INVALID_PARAMETER"})}if(u.welcome!==void 0&&(typeof u.welcome!="string"||!u.welcome))throw new l('"option.template.welcome" should be a non-empty <string> (template message_id).',{code:"INVALID_PARAMETER"});return u}});let i=t?.login||false;if(n.signup_confirmation=t?.signup_confirmation||false,n.email_subscription=t?.email_subscription||false,n.email_public&&!n.signup_confirmation)throw new l('"option.signup_confirmation" should be true if "email_public" is set to true.',{code:"INVALID_PARAMETER"});n.service=this.service,n.owner=this.owner;let s=G.bind(this)().createCognitoUser(n.username||n.email);for(let u of ["email_public","address_public","gender_public","birthdate_public","phone_number_public"])n[u]=n[u]?"1":"0";n.access_group&&(n.access_group=n.access_group.toString());let o=(await k.bind(this)("signupkey",{username:s.cognitoUsername,signup_confirmation:typeof n.signup_confirmation=="boolean"?JSON.stringify(n.signup_confirmation):n.signup_confirmation,email_subscription:n.email_subscription,template_confirmation:t?.template?.signup_confirmation||"",template_welcome:t?.template?.welcome||""})).split(":"),a=o.slice(1).join(":"),d=[new CognitoUserAttribute({Name:"custom:signup",Value:o[0]}),new CognitoUserAttribute({Name:"locale",Value:a.split("#")[1]}),new CognitoUserAttribute({Name:"custom:signup_ticket",Value:a})];for(let u in r){let g=["email_public","address_public","gender_public","birthdate_public","phone_number_public","misc","service","owner"];n[u]!==""&&(u==="username"||u==="password"||u==="access_group"||(g.includes(u)?d.push(new CognitoUserAttribute({Name:"custom:"+u,Value:n[u]})):d.push(new CognitoUserAttribute({Name:u,Value:n[u]}))));}return await G.bind(this)().signup(s.cognitoUsername,n.password,d),n.signup_confirmation?(B=s.cognitoUser,this.__request_signup_confirmation=s.cognitoUsername,"SUCCESS: The account has been created. User's signup confirmation is required."):i?wr.bind(this)({email:n.username||n.email,password:n.password}):"SUCCESS: The account has been created."}async function ci(){await this.__connection;let e=await k.bind(this)("remove-account",{disable:this.__user.user_id},{auth:true});return await Ze.bind(this)(),e}async function ui(e){await this.__connection;let t=y.Params(e,{email:i=>y.Email(i),code:["number","string"],new_password:i=>y.Password(i)},["email","code","new_password"]),r=t.code,n=t.new_password;return typeof r=="number"&&(r=r.toString()),new Promise(async(i,s)=>{G.bind(this)().createCognitoUser(t.email).cognitoUser.confirmPassword(r,n,{onSuccess:a=>{i("SUCCESS: New password has been set.");},onFailure:a=>{s(new l(a?.message||"Failed to reset password.",{code:a?.code||"ERROR",cause:a}));}});})}async function di(e,t,r){await this.__connection;let n;if(!B)throw new l("The user has to be logged in.",{code:"INVALID_REQUEST"});if(e==="email"||e==="phone_number"){if(!this.__user.hasOwnProperty(e))throw new l(`No ${e==="email"?"e-mail":"phone number"} to verify`,{code:"INVALID_REQUEST"});if(this.__user?.[`${e}_verified`])return `SUCCESS: "${e}" is verified.`;n=(t?y.Params(t,{code:"string"}):{}).code||"";}else return;let i,s=r?.template?.verification;if(s!==void 0){if(typeof s!="string"||!s)throw new l('"template.verification" should be a non-empty <string> (template message_id).',{code:"INVALID_PARAMETER"});i={template_verification:s};}return new Promise((o,a)=>{let d={onSuccess:u=>{n?G.bind(this)().getSession({refreshToken:true}).then(()=>{this.__user&&(this.__user[e+"_verified"]=true),o(`SUCCESS: "${e}" is verified.`);}).catch(g=>{a(g);}):o("SUCCESS: Verification code has been sent.");},onFailure:u=>{a(new l(u.message||"Failed to request verification code.",{code:u?.code}));}};n?B?.verifyAttribute(e,n,d):(d.inputVerificationCode=null,B?.getAttributeVerificationCode(e,d,i));})}function fi(e,t){return di.bind(this)("phone_number",e,t)}function gi(e,t){return di.bind(this)("email",e,t)}async function pi(e,t){await this.__connection;let r=y.Params(e,{email:s=>y.Email(s)},["email"]),n,i=t?.template?.verification;if(i!==void 0){if(typeof i!="string"||!i)throw new l('"template.verification" should be a non-empty <string> (template message_id).',{code:"INVALID_PARAMETER"});n={template_verification:i};}return new Promise(async(s,o)=>{G.bind(this)().createCognitoUser(r.email).cognitoUser.forgotPassword({onSuccess:d=>{s("SUCCESS: Verification code has been sent.");},onFailure:d=>{let{parsed:u,code:g}=Rt(d),f={UserNotFoundException:"NOT_EXISTS",InvalidParameterException:"INVALID_PARAMETER",NotAuthorizedException:"INVALID_REQUEST",LimitExceededException:"REQUEST_EXCEED",TooManyRequestsException:"REQUEST_EXCEED",CodeDeliveryFailureException:"CODE_DELIVERY_FAILURE"}[g]||u.code||g||"ERROR";o(new l(u.message,{code:f,cause:d}));}},n);})}async function hi(e){if(await this.__connection,!this.session)throw new l("User login is required.",{code:"INVALID_REQUEST"});let t=y.Params(e,{current_password:"string",new_password:"string"});if(!t?.current_password)throw new l('"current_password" is required to change password.',{code:"INVALID_PARAMETER"});if(!t?.new_password)throw new l('"new_password" is required to change password.',{code:"INVALID_PARAMETER"});return y.Password(t.current_password),y.Password(t.new_password),L.call(this)&&await Ln.bind(this)(t.current_password,t.new_password),new Promise((r,n)=>{B.changePassword(t.current_password,t.new_password,(i,s)=>{if(i){if(i?.code==="InvalidParameterException")n(new l("Invalid password parameter.",{code:"INVALID_PARAMETER"}));else if(i?.code==="NotAuthorizedException")n(new l("Incorrect password.",{code:"INVALID_REQUEST"}));else if(i?.code==="TooManyRequestsException"||i?.code==="LimitExceededException")n(new l("Too many attempts. Please try again later.",{code:"REQUEST_EXCEED"}));else {let{parsed:o}=Rt(i);n(o);}return}L.call(this)&&Fn.bind(this)().catch(o=>this.log("encryption:prune:failed",o)),r("SUCCESS: Password has been changed.");});})}async function mi(e){if(await this.__connection,!this.session)throw new l("User login is required.",{code:"INVALID_REQUEST"});let t=y.Params(e||{},{user_id:i=>y.UserId(i),email:i=>y.Email(i),address:i=>{if(!i)return "";if(typeof i=="string")return i;if(typeof i=="object")return JSON.stringify(i)},name:"string",gender:"string",birthdate:i=>i?y.Birthdate(i):"",phone_number:i=>i?y.PhoneNumber(i):"",email_public:"boolean",phone_number_public:"boolean",address_public:"boolean",gender_public:"boolean",birthdate_public:"boolean",misc:"string",picture:i=>i?y.Url(i):"",profile:i=>i?y.Url(i):"",family_name:"string",given_name:"string",middle_name:"string",nickname:"string",website:i=>i?y.Url(i):""});if(t&&typeof t=="object"&&!Object.keys(t).length)return this.user;let r=[["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 i of r)if(t[i[0]]&&!this.__user[i[1]])throw new l(`${i[2]} "${i[0]}" to true.`,{code:"INVALID_REQUEST"})}let n=[];for(let i in t){if(t[i]===this.user[i]){n.push(i);continue}if(["email_public","phone_number_public","address_public","gender_public","birthdate_public","misc"].includes(i)){let o=t[i];typeof o=="boolean"&&(o=o?"1":"0"),t["custom:"+i]=o,n.push(i);}}for(let i of n)delete t[i];if(t.user_id)if(t.user_id===this.user.user_id)delete t.user_id;else return k.bind(this)("admin-edit-profile",{attributes:t},{auth:true});if(t&&typeof t=="object"&&Object.keys(t).length){let i=[];for(let s in t)i.push(new CognitoUserAttribute({Name:s,Value:t[s]}));return await new Promise((s,o)=>{B?.updateAttributes(i,(a,d)=>{a&&o([a?.code||a?.name,a?.message||"Failed to update user settings."]),s(d);});}),await G.bind(this)().getSession({refreshToken:true}),this.user}return this.user}async function yi(e,t){e=j(e).data,e||(e={searchFor:"timestamp",condition:">",value:0},t||(t={}),t.ascending=false),await this.__connection;let r={user_id:i=>Array.isArray(i)?i.map(s=>y.UserId(s)):y.UserId(i),email:"string",phone_number:"string",locale:i=>{if(typeof i!="string"||typeof i=="string"&&i.length>5)throw new l('Value of "locale" should be a country code.',{code:"INVALID_PARAMETER"});return i},name:"string",address:"string",gender:"string",birthdate:i=>y.Birthdate(i),subscribers:"number",timestamp:"number",access_group:"number",approved:"string"},n=["searchFor","value"];if(e=y.Params(e,{searchFor:["user_id","name","email","phone_number","address","gender","birthdate","locale","subscribers","timestamp","access_group","approved"],condition:[">",">=","=","<","<=","gt","gte","eq","lt","lte",()=>"="],value:i=>{let s=r[e.searchFor];if(typeof s=="function")return s(i);if(typeof i!==s)throw new l(`Value does not match the type of "${e.searchFor}" index.`,{code:"INVALID_PARAMETER"});return i},range:i=>{let s=r[e.searchFor];if(typeof s=="function")return s(i);if(typeof i!==s)throw new l(`Range does not match the type of "${e.searchFor}" index.`,{code:"INVALID_PARAMETER"});return i}},n),e?.condition&&e?.condition!=="="&&e.hasOwnProperty("range"))throw new l("Conditions does not apply on range search.",{code:"INVALID_PARAMETER"});if(e.searchFor==="user_id"&&(e.condition!=="="||e.range))throw new l(`Conditions are not allowed on "${e.searchFor}"`,{code:"INVALID_PARAMETER"});if(typeof e?.value=="string"&&!e?.value)throw new l("Value should not be an empty string.",{code:"INVALID_PARAMETER"});if(typeof e?.searchFor=="string"&&!e?.searchFor)throw new l('"searchFor" should not be an empty string.',{code:"INVALID_PARAMETER"});return k.bind(this)("get-users",e,{auth:true,fetchOptions:t})}async function bi(e){await this.__connection;let t=await k.bind(this)("last-verified-email",e,{auth:true});return t.includes("SUCCESS")?(await G.bind(this)().getSession({refreshToken:true}),this.user):t}var Oe=null,wi=typeof SubmitEvent<"u",_a=typeof HTMLFormElement<"u",tt=J(),Er=0;function Ei(e){if(!e)return null;let t=Number(e);if(Number.isFinite(t))return Math.max(0,t*1e3);let r=Date.parse(e);return Number.isNaN(r)?null:Math.max(0,r-Date.now())}function Ar(e,t){return t>0?e/t*100:0}var _i=e=>{let{auth:t,type:r,endpoints:n,stable:i}=e,s=n[0],o=n[1];if(Er++,r==="admin"){let a=Object.entries(s).filter(([d,u])=>d.includes(t?"_private":"_public")&&d!=="get_users_private"&&d!=="service_public"&&typeof u=="string").map(([,d])=>d);if(!a.length)throw new l("No available admin gateways.",{code:"INVALID_REQUEST"});return a[Er%a.length]}if(r==="record"){let a=Object.entries(o).filter(([d,u])=>d.includes(t?"record_private":"record_public")&&typeof u=="string").map(([,d])=>d);if(!a.length)throw new l("No available record gateways.",{code:"INVALID_REQUEST"});return i?a[0]:a[Er%a.length]}throw new l("Invalid gateway type.",{code:"INVALID_REQUEST"})};async function wa(e,t,r){let n=await Promise.all([this.admin_endpoint,this.record_endpoint]),i=n[0],s=n[1],o=e.split("?"),a=o.length>1?"?"+o[1]:"";switch(e=o[0],e){case "get-users":return i.get_users_private+e+a;case "service":return i.service_public+e+a;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 "send-inquiry":case "register-newsletter-group":case "delete-newsletter-group":case "newsletter-group-endpoint":case "invitation-list":case "csr":case "csr-poll":case "csr-cancel":case "csr-finalize":return _i.bind(this)({auth:t,type:"admin",endpoints:n})+e+a;case "post-record":return (t?s.post_private:s.post_public)+e+a;case "get-records":return (t?s.get_private:s.get_public)+e+a;case "del-files":case "del-records":return s.del_private+e+a;case "store-subscription":case "get-vapid-public-key":case "push-notification":case "delete-subscription":case "subscription":case "get-subscription":case "get-table":case "get-tag":case "get-uniqueid":case "get-index":case "get-signed-url":case "extract-file-text":case "grid-query":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 _i.bind(this)({auth:t,type:"record",endpoints:n,stable:r})+e+a;default:return y.Url(e)+a}}var et={};function Ai(){Oe&&(Oe.terminate(),Oe=null);}async function k(e,t=null,r,n){this.log("request",{url:e,data:t,options:r,_etc:n||{}}),r=r||{};let{auth:i=false,method:s="post",bypassAwaitConnection:o=false}=r;s=s.toUpperCase();let a=null,d=t?.service||this.service,u=t?.owner||this.owner,g=null,f=await wa.bind(this)(e,!!i,!!r.stableGateway);if(!o&&(a=await this.__connection,!a))throw new l("Invalid connection. The service could have been disabled, or has a restricted CORS.",{code:"INVALID_REQUEST"});let c=r?.tokenHeaders?.idToken===true;(i||c)&&(g=await Ce.bind(this)());let p={},{fetchMore:h=false,progress:m}=r?.fetchOptions||{};if(r?.fetchOptions&&Object.keys(r.fetchOptions).length){for(let v of ["limit","startKey","ascending"])if(r.fetchOptions.hasOwnProperty(v)){if(v==="startKey"&&r.fetchOptions[v]===null)continue;p[v]=r.fetchOptions[v];}p=y.Params(p,{limit:v=>{if(typeof v!="number")throw new l("Fetch limit should be a number.",{code:"INVALID_REQUEST"});if(v>1e3)throw new l("Fetch limit should be below 1000.",{code:"INVALID_REQUEST"});return v},startKey:v=>v,ascending:"boolean"});}let w=n?.ignoreService?{}:{service:d,owner:u};Object.assign(w,p),t=j(t).data,t?t&&typeof t=="object"&&(t=Object.assign(w,t)):t=w;let b=`${s}:${i?"auth":"public"}:${e}`,_=(()=>{if(t&&typeof t=="object"&&Object.keys(t).length&&!(tt&&t instanceof FormData)){let v=function(U){return typeof U=="object"&&U!==null?Object.keys(U).sort().reduce((O,V)=>(typeof U[V]=="object"&&U[V]!==null?O[V]=v(U[V]):O[V]=U[V],O),{}):U};return Z.hash(b+"/"+JSON.stringify(v(t)))}return Z.hash(b+"/"+d)})(),{requestKey:E,requestKeyWithStartKey:S}=Ea.bind(this)({params:t,url:e,fetchMore:h,hashedParams:_});if(!E||E&&typeof E=="object")return E;if(this.log("requestKey",S),typeof S=="string"&&et[S]instanceof Promise)return this.log("request:returning pending",S),et[S];let A={Accept:"*/*"};if(Object.prototype.hasOwnProperty.call(r,"contentType")&&r.contentType!==void 0){let v=r.contentType===null?"application/x-www-form-urlencoded":r.contentType;v&&(A["Content-Type"]=v);}else A["Content-Type"]="application/json";if(g&&(A.Authorization=g),r?.tokenHeaders){let v=(V,de)=>typeof V=="string"?V:V===true?de:null,U=v(r.tokenHeaders.accessToken,this.session?.accessToken?.jwtToken||null),O=v(r.tokenHeaders.idToken,this.bearerToken||this.session?.idToken?.jwtToken||g||null);U&&(A["X-Access-Token"]=U),O&&(A["X-Id-Token"]=O);}let x={public_identifier:this.__public_identifier,service:d,owner:u,resolves_offloaded_data:true};A["Content-Meta"]=JSON.stringify(x),r.revalidate&&(A["Cache-Control"]="no-cache",A.Pragma="no-cache");let C={headers:A};if(r?.responseType&&(C.responseType=r.responseType),s==="GET"){if(t){let v=[];if(tt&&t instanceof FormData?v=Array.from(t.entries()).map(([U,O])=>{let V=typeof O=="string"?O:O.name;return encodeURIComponent(U)+"="+encodeURIComponent(V)}):v=Object.keys(t).map(U=>{let O=t[U];return typeof O!="string"&&(O=JSON.stringify(O)),encodeURIComponent(U)+"="+encodeURIComponent(O)}),v.length){let U=f.includes("?")?f.endsWith("?")||f.endsWith("&")?"":"&":"?";f+=U+v.join("&");}}C.body=null;}else if(tt&&t instanceof FormData)C.body=t;else if(A["Content-Type"]==="application/x-www-form-urlencoded"&&t&&typeof t=="object"){let v=new URLSearchParams;for(let U of Object.keys(t)){let O=t[U];v.append(U,typeof O=="string"?O:JSON.stringify(O));}C.body=v.toString();}else typeof t=="string"?C.body=t:C.body=t?JSON.stringify(t):null;if(C.method=s,Oe===null){let v={batchSize:this.requestBatchSize,breakWhenError:false,onProgress:U=>{this.onBatchProcess.forEach(O=>O(U));}};Oe=new as(v);}return this.log("request-opt",C),new Promise((v,U)=>{Oe.add([async()=>{let O=Ri.bind(this)(f,C,m);et[S]=O;try{let V=Ra.bind(this)({hashedParam:E,requestKeyWithStartKey:S,url:e,fetched:await O});return delete et[S],this.log("request:end",V),v(V),V}catch(V){throw delete et[S],this.log("request:err",V),U(V),V}}]);})}function Ea(e){let{params:t={},url:r,fetchMore:n=false,hashedParams:i}=e||{};if(t.startKey){if(!(typeof t.startKey=="object"&&Object.keys(t.startKey).length)&&t.startKey!=="start"&&t.startKey!=="end")throw new l(`"${t.startKey}" is invalid startKey key.`,{code:"INVALID_PARAMETER"});t.startKey==="start"&&(n=false,delete t.startKey);}if(!n){if(this.__cached_requests?.[r]?.[i]&&delete this.__cached_requests[r][i],this.__startKeyHistory?.[r]?.[i]){if(Array.isArray(this.__startKeyHistory[r][i])&&this.__startKeyHistory[r][i].length)for(let d of this.__startKeyHistory[r][i]){let u=i+Z.hash(d);this.__cached_requests?.[r]&&this.__cached_requests?.[r]?.[u]&&delete this.__cached_requests[r][u];}delete this.__startKeyHistory[r][i];}return {requestKeyWithStartKey:i,requestKey:i}}if(!Array.isArray(this.__startKeyHistory?.[r]?.[i]))return {requestKeyWithStartKey:i,requestKey:i};let s=this.__startKeyHistory[r][i],o=s[s.length-1],a=i;if(o){if(o==="end")return {requestKey:{list:[],startKey:"end",endOfList:true,startKeyHistory:s},requestKeyWithStartKey:a};a+=Z.hash(o),t.startKey=JSON.parse(o);}return this.__cached_requests?.[r]?.[a]?{requestKey:this.__cached_requests[r][a],requestKeyWithStartKey:a}:{requestKeyWithStartKey:a,requestKey:i}}function Aa(e){let t=r=>r&&typeof r=="object"&&r.encrypted?Object.assign({},r,{data:null}):r;return Array.isArray(e)?e.map(t):e&&typeof e=="object"?Array.isArray(e.list)?Object.assign({},e,{list:e.list.map(t)}):t(e):e}function Ri(e,t,r){return new Promise((n,i)=>{let s=new XMLHttpRequest;s.open(t.method||"GET",e);for(var o in t.headers||{})s.setRequestHeader(o,t.headers[o]);t.responseType&&(s.responseType=t.responseType),s.onload=()=>{if(s.status<400)if(t.responseType=="json"||t.responseType=="blob")n(s.response);else {let a=s.responseText;try{a=JSON.parse(a);}catch{}n(a);}else if(s.status===429){let a=s.getResponseHeader("Retry-After"),d=Ei(a);d!==null?setTimeout(()=>{Ri(e,t,r).then(n,i);},d):i("Too many requests");}else {let a=s.status,d=["INVALID_CORS","INVALID_REQUEST","SERVICE_DISABLED","INVALID_PARAMETER","ERROR","EXISTS","NOT_EXISTS"],u=t.responseType=="blob"?s.response:s.responseText;try{u=JSON.parse(u);}catch{}if(typeof u=="string"){let g=u.split(":"),f=g.splice(0,1)[0].trim(),c=g.join(":").trim();i(new l(c||u,{code:d.includes(f)?f:"ERROR"}));}else if(typeof u=="object"&&(u?.message||u?.stage||u?.code)){let g=u?.code||(a?a.toString():null)||"ERROR",f=u.message,c=u?.cause;c===void 0&&u.stage&&(c=u),typeof f=="string"&&(f=f.trim()),f||(f=String(g)),i(new l(f,{cause:c,code:g}));}else i(u);}},s.onerror=()=>i("Network error"),s.onabort=()=>i("Aborted"),s.ontimeout=()=>i("Timeout"),typeof r=="function"&&(s.onprogress=a=>{r({status:"download",progress:Ar(a.loaded,a.total),loaded:a.loaded,total:a.total,abort:()=>s.abort()});},s.upload&&(s.upload.onprogress=a=>{r({status:"upload",progress:Ar(a.loaded,a.total),loaded:a.loaded,total:a.total,abort:()=>s.abort()});})),s.send(t.body);})}function Ra(e){let{hashedParam:t,requestKeyWithStartKey:r,url:n,fetched:i}=e;if(!i?.startKey)return i;this.__startKeyHistory.hasOwnProperty(n)||(this.__startKeyHistory[n]={}),this.__startKeyHistory[n].hasOwnProperty(t)||(this.__startKeyHistory[n][t]=[]);let s=i.startKey==="end"?"end":JSON.stringify(i.startKey);return this.__startKeyHistory[n][t].includes(s)||this.__startKeyHistory[n][t].push(s),this.__cached_requests?.[n]||(this.__cached_requests[n]={}),this.__cached_requests[n][r]=i,Object.assign({startKeyHistory:this.__startKeyHistory[n][t]},i)}async function rt(e,t){await this.__connection;let{record_id:r,service:n=this.service,progress:i}=t;if(!r)throw new l('"record_id" is required.',{code:"INVALID_PARAMETER"});if(wi&&e instanceof SubmitEvent&&(e=e.target),_a&&e instanceof HTMLFormElement&&(e=new FormData(e)),!tt||!(e instanceof FormData))throw new l('"fileList" should be a FormData or HTMLFormElement.',{code:"INVALID_PARAMETER"});let o={reserved_key:Te(),service:n,request:"post"};t?.record_id&&(o.id=t.record_id);let a,d=(p,h,m)=>new Promise((w,b)=>{a=new XMLHttpRequest,a.open("POST",p),a.onload=()=>{let _=a.responseText;try{_=JSON.parse(_);}catch{}if(a.status>=200&&a.status<300)w(_);else if(a.status===429){let E=a.getResponseHeader("Retry-After"),S=Ei(E);S!==null?setTimeout(()=>{d(p,h,m).then(w,b);},S):b("Too many requests");}else b(_);},a.onerror=()=>b("Network error"),a.onabort=()=>b("Aborted"),a.ontimeout=()=>b("Timeout"),a.upload&&typeof m=="function"&&(a.upload.onprogress=m),a.send(h);});function u(p){let h="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";if(p===0)return h[0];let m="";for(;p>0;)m=h[p%62]+m,p=Math.floor(p/62);return m}let g=[],f=[],c=[];for(let[p,h]of e.entries()){if(!(h instanceof File))continue;let m=await zn.bind(this)(r,p,h),w=m.file,b=m.key,_=Object.assign({key:b+"/"+w.name,sizeKey:u(w.size),contentType:w.type||null},o),{fields:E=null,url:S,cdn:A}=await k.bind(this)("get-signed-url",_,{auth:!!this.__user});c.push(A);let N=new FormData;for(let x in E)N.append(x,E[x]);N.append("file",w);try{await d(S,N,typeof i=="function"?x=>i({status:"upload",progress:Ar(x.loaded,x.total),currentFile:h,completed:g,failed:f,loaded:x.loaded,total:x.total,abort:()=>a.abort()}):null),g.push(h);}catch{f.push(h);}}return {completed:g,failed:f,bin_endpoints:c}}var It={};function P(e){let{preventMultipleCalls:t=false}=e||{};return function(r,n,i){let s=i.value;i.value=function(...o){let a=o[0],d=true,u=null,g="",f={},c=false;if(wi&&a instanceof SubmitEvent){a.preventDefault();let b=window.location.href;u=a.target;let _=new URL(u.action);g=_.href;let E=g?g.match(/(?<=\{).*?(?=\})/g):"";if(E)for(let S of E){if(!S)continue;let A=u.querySelector(`[name="${S}"]`);if(A)if(A.type==="file")for(let N=0;N<=A.files.length-1;N++)A.files[N]&&(f[S]||(f[S]=[]),f[S].push(new Promise((x,C)=>{let v=new FileReader;v.onload=function(){x(v.result);},v.readAsDataURL(A.files[N]),v.onerror=C;})));else g=g.replace(`{${S}}`,A.value);}u.getAttribute("action")===null?d=false:c=_.href===b;}let p=async b=>{if(g)for(let _ in f)f[_].length&&(g=g.replace(`{${_}}`,(await Promise.all(f[_])).join(",")));if(u&&d){let _=L.call(this)?Aa(b):b;window.sessionStorage.setItem(`${this.service}:${Z.hash(g)}`,JSON.stringify(_)),c?window.location.replace(g):window.location.href=g;}return b},h,m=b=>{throw b instanceof l?b.name=n+"()":b=b instanceof Error?b:new l(b,{name:n+"()"}),b},w=async()=>{try{if(h=s.bind(this)(...o),h instanceof Promise){let b=await h;return p(b)}return p(h)}catch(b){throw m(b)}};if(t){let b=`${n}:${this?.__public_identifier||""}:${this?.service||""}:${this?.owner||""}`;return It?.[b]||(It[b]=w().finally(()=>{delete It[b];})),It[b]}return w()};}}async function Ti(){await this.__connection;let e=`${this.service}:${Z.hash(window.location.href.split("?")[0])}`,t=window.sessionStorage.getItem(e);if(window.sessionStorage.removeItem(e),t!==null){try{t=JSON.parse(t);}catch{}return t}return null}var Ta=256,Ia=256,Pa=256,Ii=256,Sa="\u{10FFFF}",ka=/[\u0000-\u001F\u007F]|\u{10FFFF}/u,va={"/":"%2F","!":"%21","*":"%2A","#":"%23"},Na={"%2F":"/","%21":"!","%2A":"*","%23":"#"};function Da(e){return e.replace(/%/g,"%25").replace(/[\/!*#]/g,r=>va[r]||r)}function le(e){return typeof e!="string"?e:e.replace(/%(2F|21|2A|23)/gi,r=>{let n=r.toUpperCase();return Na[n]||r}).replace(/%25/gi,"%")}function fe(e,t,r={}){let{allowEmpty:n=false,maxLength:i,blockKeyDelimiters:s=false,disallowLeadingDollar:o=false,onlyAlphanumeric:a=false}=r;if(typeof e!="string")throw new l(`"${t}" should be type: <string>.`,{code:"INVALID_PARAMETER"});if(a&&/[^a-zA-Z0-9]/.test(e))throw new l(`"${t}" should only contain alphanumeric characters.`,{code:"INVALID_PARAMETER"});if(!n&&e.length===0)throw new l(`"${t}" is required.`,{code:"INVALID_PARAMETER"});if(i&&e.length>i)throw new l(`"${t}" should be <= ${i} characters.`,{code:"INVALID_PARAMETER"});if(ka.test(e)||e.includes(Sa))throw new l(`"${t}" cannot include control characters or unsupported sentinel characters.`,{code:"INVALID_PARAMETER"});if(s&&(e=Da(e),i&&e.length>i))throw new l(`"${t}" should be <= ${i} characters. "/", "!", "*", "#" and "%" count as 3 characters each.`,{code:"INVALID_PARAMETER"});if(o&&e.startsWith("$"))throw new l(`"${t}" cannot start with "$".`,{code:"INVALID_PARAMETER"});return e}function Le(e,t="table.name",r={}){return fe(e,t,{allowEmpty:r.allowEmpty===true,maxLength:Ta,blockKeyDelimiters:true})}function St(e,t="tag",r={}){return fe(e,t,{allowEmpty:r.allowEmpty===true,maxLength:Ia,blockKeyDelimiters:true})}function nt(e,t="index.name",r={}){return fe(e,t,{allowEmpty:r.allowEmpty===true,maxLength:Pa,blockKeyDelimiters:true,disallowLeadingDollar:true})}function Pi(e,t="index.value"){return fe(e,t,{allowEmpty:true,maxLength:Ii})}function Rr(e){return typeof e=="string"&&e.slice(-1)==="."}function Tr(e,t){return fe(e,t,{allowEmpty:true,maxLength:Ii,blockKeyDelimiters:true})}function Si(e){if(!e.record_id&&!e.unique_id)return null;let t={};return e?.service&&(t.service=e.service),e?.owner&&(t.owner=e.owner),e?.record_id?t.record_id=fe(e.record_id,"record_id",{allowEmpty:false,onlyAlphanumeric:true}):e?.unique_id&&(t.unique_id=e.unique_id),t}function Ir(e){if(e===void 0)return 0;if(typeof e=="number"){if(e>99||e<0)throw new l('"table.access_group" value should be within a range of 0 ~ 99.',{code:"INVALID_REQUEST"})}else if(typeof e=="string"){if(e={"*":"private",private:"private",public:0,authorized:1,admin:99}[e],e===void 0)throw new l('"table.access_group" is invalid.',{code:"INVALID_PARAMETER"})}else throw new l('"table.access_group" should be type: <number | string>.',{code:"INVALID_PARAMETER"});if(!this.__user&&e)throw new l("Unsigned users have no access to records with access group.",{code:"INVALID_REQUEST"});return e}var Pt=4503599627370496;function kt(e){if(typeof e=="number"){if(e>Pt||e<-Pt)throw new l(`Number value should be within range -${Pt} ~ +${Pt}`,{code:"INVALID_PARAMETER"});return e}if(typeof e=="boolean")return e;if(typeof e=="string")return Pi(e,"index.value");throw new l('"index.value" should be type: <number | boolean | string>.',{code:"INVALID_PARAMETER"})}function ki(e,t){if(!t.index||!("value"in t.index))throw new l('"index.value" is required.',{code:"INVALID_PARAMETER"});if(t.index.name==="$record_id")throw new l(`Cannot do "index.range" on ${t.index.name}`,{code:"INVALID_PARAMETER"});if(typeof t.index.value!=typeof e)throw new l('"index.range" type should match the type of "index.value".',{code:"INVALID_PARAMETER"});return typeof e=="string"?Rr(t.index.name)?Tr(e,"index.range"):Pi(e,"index.range"):e}var vt={},xa=10080*60,Ua=3600,vi=2;function Ca(e,t){if(!t)return String(vi);let r=Math.max(60,e-300)*1e3;return "g"+vi+"w"+Math.floor(Date.now()/r)}function Oa(e){if(!this.user?.user_id)return false;let t=e[6]==="**"?"**":parseInt(e[6]),r=this.user?.access_group??-1;return !(this.user.user_id!==e[3]&&(t==="**"||r<t))}function La(e){if(typeof e=="string"){if(e.startsWith("!J%"))try{return JSON.parse(e.substring(3))}catch{return e}return e==="!D%{}"?{}:e==="!L%[]"?[]:e}if(e&&typeof e=="object"&&!Array.isArray(e)&&typeof e.__json__=="string"&&Object.keys(e).length===1)try{return JSON.parse(e.__json__)}catch{}return e}async function Nt(e){return typeof e=="string"?e:e&&typeof e.text=="function"?await e.text():await new Promise((t,r)=>{try{let n=new FileReader;n.onload=()=>t(n.result),n.onerror=()=>r(n.error||new Error("Failed to read blob")),n.readAsText(e);}catch(n){r(n);}})}function Sr(e){return !!e&&typeof e=="object"&&!Array.isArray(e)&&typeof e.__data__=="string"&&Object.keys(e).length===1&&e.__data__.endsWith("/__data__/__json__.json")}var Fe=new Map,Fa=1024,Ma=/^[0-9A-Za-z]+\/[0-9A-Za-z]+\/__data__\/__json__\.json$/,Di=/^[0-9A-Za-z_-]+$/,qa=/^(\d{2}|\*\*)$/;function xi(e){if(typeof e!="string")return null;let t=e.split("?")[0].split("/");if(t.length<15||t[0]!=="https:"||t[1]!==""||!t[2])return null;let r=t.slice(3);return r[0]!=="publ"&&r[0]!=="auth"||r[4]!=="records"||r[7]!=="bin"||!Di.test(r[1])?null:{origin:t.slice(0,3).join("/"),service:r[1]}}function Va(e){let t=xi(e);!t||Fe.get(t.service)===t.origin||(Fe.size>=Fa&&!Fe.has(t.service)&&Fe.clear(),Fe.set(t.service,t.origin));}function Ni(e,t){if(typeof t!="string"||!Ma.test(t))return null;let r=typeof e.usr_tbl=="string"?e.usr_tbl.split("/"):null,n=typeof e.tbl=="string"?e.tbl.split("/"):null,i=null,s=null;if(typeof e.srvc=="string"){let g=e.srvc.split("!")[0].split("/");g.length===2&&(i=g[0],s=g[1]);}i||(i=r?.[2]||n?.[1]||null,i&&i===this.service&&(s=this.owner));let o=typeof e.usr=="string"&&e.usr?e.usr:r?.[0]||null,a=r?.[3]||n?.[2]||null,d=e.rec;for(let g of [i,s,o,d])if(typeof g!="string"||!Di.test(g))return null;if(typeof a!="string"||!qa.test(a))return null;let u=null;if(Array.isArray(e.bin))for(let g of e.bin){let f=xi(g);if(f&&f.service===i){u=f.origin;break}}return u=u||Fe.get(i)||null,u?`${u}/${a==="00"?"publ":"auth"}/${i}/${s}/${o}/records/${d}/${a}/bin/${t}`:null}async function Se(e,t,r=false,n=false,i=false){let s={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:{}},o=false,a=[],d=null;function u(c){let p=c=="**"?"private":parseInt(c);return p=p==0?"public":p==1?"authorized":p==99?"admin":p,p}let g={ip:c=>{let p=c.split("#"),h=p[0];p.length>1&&(s.unique_id=p.slice(1).join("#")),h.slice(-1)==="R"?(s.readonly=true,h=h.slice(0,-1)):s.readonly=false,/^\d{1,3}-\d{1,3}-\d{1,3}-\d{1,3}$/.test(h)&&(h=h.split("-").join("."),o=true),s.ip=h;},rec:c=>{if(!c)return;s.record_id=c;let p=c.substring(0,c.length-9),h=se(p);s.uploaded=h;},usr:c=>{s.user_id=c;},tbl:c=>{if(c&&!s.table.name){let p=c.split("/");s.table.name=le(p[0]),s.table.access_group=u(p[2]),p?.[3]&&(s.table.subscription.is_subscription_record=true);}},usr_tbl:c=>{let p=c.split("/");s.user_id||(s.user_id=p[0]),s.table.name||(s.table.name=le(p[1]),s.table.access_group=u(p[3]),p?.[4]&&(s.table.subscription.is_subscription_record=true));},idx:c=>{if(!c)return;let p=c.split("!"),h=le(p.splice(0,1)[0]),m=$a("!"+p.join("!"));s.index={name:h,value:m};},ref:c=>{c&&(s.reference=c.split("/")[0]);},tags:c=>{s.tags=Array.isArray(c)?c.map(p=>le(p)):c;},upd:c=>{s.updated=c;},acpt_mrf:c=>{s.source.prevent_multiple_referencing=!c;},ref_limt:c=>{s.source.referencing_limit=c;},rfd:c=>{s.referenced_count=c;},bin:async c=>{let p={},h=s?.reference||null;if(Array.isArray(c)){let m=await Promise.all(c.map(async w=>{try{let b=w.split("/").slice(3).join("/"),_=b.split("/");if(_.length<12)return null;let E=_[_.length-1],S=_[10];if(S==="__data__"&&E==="__json__.json")return {isDataFile:!0,rawUrl:w};if(lr(S,E))return {isDataFile:!0,rawUrl:w};let A=Et(S),N=_[9],x=_[8],C=u(_[6]),v=w,U=C!=="public"&&Oa.call(this,_)?{expires:Ua,browserCache:xa}:null;if(C!=="public"&&!i)try{v=await _e.bind(this)(w,{dataType:"endpoint",_ref:h});}catch(V){console.error("Error getting signed url for private file:",V),v=w;}let O={access_group:C,filename:E,url:v,path:b,size:A?A.plainSize:se(N),uploaded:se(x),getFile:(V,de)=>{let ie={dataType:V||"download",progress:de,_ref:h},F=()=>_e.bind(this)(v,Object.assign({},ie,{_update:O}));return U?_e.bind(this)(w,Object.assign({},ie,U)).catch(()=>F()):F()}};return A&&(O.encrypted=!0,O.stored_size=se(N)),{pathKey:A?A.key:S,obj:O}}catch{return null}}));for(let w of m)if(w&&!w.isDataFile){if(p[w.pathKey]){p[w.pathKey].push(w.obj);continue}p[w.pathKey]=[w.obj];}}s.bin=p;},prv_acs:c=>{for(let p in c)["notify_subscribers","upload_to_feed","feed_referencing_records","notify_referencing_records"].includes(p)?s.table.subscription[p]=c[p]:p==="referencing_index_restrictions"&&Array.isArray(c[p])?s.source[p]=c[p].map(m=>m&&typeof m=="object"&&typeof m.name=="string"?Object.assign({},m,{name:le(m.name)}):m):s.source[p]=c[p];},data:async c=>{let p={access_group:s.table.access_group,table_name:s.table.name,user_id:s.user_id,record_id:s.record_id,unique_id:s.unique_id,ctUrl:d},h=()=>{L.call(this)&&(s.encrypted={status:"failed",reason:"DATA_UNAVAILABLE"});},m=async b=>{if(n||!L.call(this)&&!bt(b))return b;let _=await kn.bind(this)(b,p);return _.flag&&(s.encrypted=_.flag),_.value},w=La(c);if(w!==c){s.data=await m(w);return}if(Sr(c)){let b=c.__data__,_=a.find(E=>E.endsWith(b))||null;if(!_&&!r){await Promise.resolve();let E=Ni.call(this,e,b),S=false,A;if(E)try{let N=await _e.bind(this)(E,{dataType:"blob",_ref:s.reference||null});A=JSON.parse(await Nt(N)),S=!0;}catch{}if(S){s.data=await m(A);return}h();}if(_){if(r){s.data=c;return}try{let E=await _e.bind(this)(_,{dataType:"blob",_ref:s.reference||null}),S=await Nt(E);s.data=await m(JSON.parse(S));}catch(E){let S=Ni.call(this,e,b),A=false,N;if(S&&S!==_)try{let x=await _e.bind(this)(S,{dataType:"blob",_ref:s.reference||null});N=JSON.parse(await Nt(x)),A=!0;}catch{}if(A){s.data=await m(N);return}console.error("Failed to fetch offloaded record data:",E),s.data=null,h();}return}}s.data=await m(c);}};if(e.record_id)return e;if(Array.isArray(e.bin))for(let c of e.bin)try{if(typeof c!="string")continue;Va(c);let p=c.split("/").slice(3);p.length>=12&&p[10]==="__data__"&&p[p.length-1]==="__json__.json"&&a.push(c),p.length>=12&&lr(p[10],p[p.length-1])&&(d=c);}catch{}let f=[];for(let c in g)if(e.hasOwnProperty(c)){let p=g[c](e[c]);p instanceof Promise&&f.push(p);}return o&&(s.user_id="anonymous:"+s.user_id),await Promise.all(f),s}function $a(e){let t=e.substring(3);switch(e.substring(0,3)){case "!S%":return t;case "!N%":let n=t.split("."),i=Number(n[0])-4503599627370496;return n.length===1?i:parseFloat(i.toString()+"."+n[1]);case "!B%":return t==="1";case "!L%":case "!D%":try{return JSON.parse(t)}catch{throw new l("Value parse error.",{code:"PARSE_ERROR"})}default:return e}}async function Ui(e){let{endpoints:t}=e;if(typeof t=="string"&&(t=[t]),!Array.isArray(t))throw new l('"endpoints" should be type: array | string.',{code:"INVALID_PARAMETER"});let r=await k.bind(this)("del-files",{endpoints:t,storage:"records"},{auth:true,method:"post"}),n=[];for(let i in r)n.push(Se.bind(this)(r[i]));return Promise.all(n)}async function _e(e,t){if(typeof e!="string")throw new l('"url" should be type: string.',{code:"INVALID_PARAMETER"});let r=e,n=e.split("?"),i=n.shift()||"",s=n.length?"?"+n.join("?"):"",o=y.Url(i);e=o+s;let a=false,d=o.split("/"),g=d[2].split("."),f=null;g.length===3&&g[1]==="skapi"&&(f=g[0],a=true);let c=d.slice(3),p=false;if(!a&&(c[0]==="auth"||c[0]==="publ"))try{y.UserId(c[2]),y.UserId(c[3]),p=c[0]=="auth",a=!0;}catch{throw new l("Invalid file url.",{code:"INVALID_PARAMETER"})}let h=f?null:c[1];if(t=y.Params(t,{expires:["number",()=>0],browserCache:["number",()=>0],refresh:["boolean",()=>false],dataType:["base64","blob","endpoint","text","info",()=>"download"],progress:["function","undefined",null],_ref:[null,"string"],_update:E=>E}),t?.dataType==="info")return {url:e,filename:c[c.length-1],fileKey:c[c.length-2],access_group:c[6]==="**"?"private":c[6]==="01"?"authorized":c[6]==="00"?"public":parseInt(c[6]),uploader:c[3],record_id:c[4]==="records"?c[5]:"N/A",filesize:se(c[9]),uploaded:se(c[8])};let m=e.split("/").slice(-1)[0],w=t.expires;if(w){if(!a)throw new l("Expires option can only be used on skapi cdn endpoints.",{code:"INVALID_PARAMETER"});if(w<0)throw new l('"config.expires" should be > 0. (seconds)',{code:"INVALID_PARAMETER"});let E={request:f?"get-host":"get",id:f||c[5],key:r.split("?")[0],expires:w};h&&(E.service=h);let S=t.browserCache,A={auth:true};if(S){if(S<0)throw new l('"config.browserCache" should be > 0. (seconds)',{code:"INVALID_PARAMETER"});A.method="get",A.stableGateway=true,E.browser_cache=S;let N=this.session?.idToken?.payload?.sub||this.user?.user_id;N&&(E.uid=N),E.nocache=Ca(w,t.refresh);}e=(await k.bind(this)("get-signed-url",E,A)).url;}else if(p){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 G.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(x){throw this.log("getFile:new token error",x),new l("User login is required.",{code:"INVALID_REQUEST"})}}let S=this.bearerToken||this.session?.idToken?.jwtToken;if(!S||!this.user?.user_id)throw new l("User login is required.",{code:"INVALID_REQUEST"});e+=`${e.includes("?")?"&":"?"}t=${encodeURIComponent(S)}`;let A=c[6]==="**"?"**":parseInt(c[6]),N=this.user?.access_group??-1;if(this.user.user_id!==c[3]&&(A==="**"||N<A)){let x=c[5];if(this.__private_access_key[x]&&typeof this.__private_access_key[x]=="string")e+=`&p=${encodeURIComponent(this.__private_access_key[x])}`;else if(this.owner!==this.host)try{let C=await this.requestPrivateRecordAccessKey({record_id:x,reference_id:t?._ref});e+=`&p=${encodeURIComponent(C)}`;}catch{}}}if((L.call(this)?br(e):null)&&t?.dataType!=="endpoint"&&t?.dataType!=="info"){let E=await k.bind(this)(e,null,{method:"get",contentType:null,responseType:"blob",fetchOptions:{progress:t?.progress}},{ignoreService:true}),S=await Jn.bind(this)(e,E);if(t?.dataType==="blob")return S;if(t?.dataType==="text")return await Nt(S);if(t?.dataType==="base64")return await new Promise((x,C)=>{let v=new FileReader;v.onloadend=()=>x(v.result),v.onerror=()=>C(v.error),v.readAsDataURL(S);});let A=URL.createObjectURL(S),N=document.createElement("a");return N.href=A,document.body.appendChild(N),N.setAttribute("download",m),N.click(),document.body.removeChild(N),setTimeout(()=>URL.revokeObjectURL(A),6e4),null}if(t?.dataType==="endpoint")return t._update&&(t._update.url=e),e;if(t?.dataType==="download"){let E=document.createElement("a");return E.href=e,document.body.appendChild(E),E.setAttribute("download",m),E.target="_blank",E.click(),document.body.removeChild(E),null}return new Promise(async(E,S)=>{try{let A=await k.bind(this)(e,null,{method:"get",contentType:null,responseType:t?.dataType==="text"?"text":"blob",fetchOptions:{progress:t?.progress}},{ignoreService:!0});if(t?.dataType==="base64"){let N=new FileReader;N.onloadend=()=>E(N.result),N.readAsDataURL(A);}else E(A);}catch(A){if(t?.browserCache&&!t?.refresh)try{E(await _e.bind(this)(r,Object.assign({},t,{refresh:!0})));return}catch(N){S(N);return}S(A);}})}function Dt(e,t){return `${e||this.service}/${t||this.owner}`}function Pr(e,t){let r=this.__my_unique_ids[e];return r?r[t]:void 0}function Ci(e,t,r){this.__my_unique_ids[e]||(this.__my_unique_ids[e]={}),this.__my_unique_ids[e][t]=r;}function ja(e,t){this.__my_unique_ids[e]&&delete this.__my_unique_ids[e][t];}function Oi(e,t){return !t||t.table===void 0?e:Object.assign({},e,{table:t.table})}async function it(e){if(await this.__connection,!this.__user&&this.connection?.opt?.require_login===true)throw new l(`This project requires users to sign in before reading its database, so "${e}" is not available to a signed-out visitor.`,{code:"REQUIRE_LOGIN"})}async function Li(e,t=false){e=j(e,{ignoreEmpty:true}).data||{};let r=Dt.bind(this)(e?.service,e?.owner),n="",i=Si(e);if(i){if(e=i,n=e.record_id||e.unique_id,typeof n=="string"){typeof this.__private_access_key?.[n]=="string"&&(e.private_key=this.__private_access_key?.[n]||void 0);let s=Pr.bind(this)(r,n);s&&(t?ja.bind(this)(r,n):e.record_id=s);}}else {let s=await W.bind(this)(),o=e?.reference,a=false;typeof o=="object"&&Object.keys(o).length&&(o?.record_id||o?.unique_id?(n=o.record_id||o.unique_id,n&&typeof this.__private_access_key?.[n]=="string"&&(e.private_key=this.__private_access_key?.[n]||void 0),e.reference=n):o?.user_id&&(a=o.user_id===this.user?.user_id,e.reference=o.user_id)),typeof e?.table=="string"&&(e.table={name:e.table,access_group:0}),e.index&&e.index.hasOwnProperty("range")&&e.index.hasOwnProperty("condition")&&delete e.index.range;let d=u=>({table:{name:g=>Le(g,"table.name"),access_group:Ir.bind(this),subscription:g=>y.UserId(g,'User ID in "subscription"')},reference:"string",index:{name:["$updated","$uploaded","$referenced_count","$user_id",g=>nt(g,"index.name")],value:g=>{let f={$updated:"number",$uploaded:"number",$referenced_count:"number",$user_id:y.UserId};if(f.hasOwnProperty(u.index.name)){let c=f[u.index.name];if(typeof c=="function")return c(g);if(c!==typeof g)throw new l(`"index.value" should be type: ${c}.`,{code:"INVALID_PARAMETER"});return g}return typeof g=="string"&&!g?"":typeof g=="string"&&Rr(u.index.name)?Tr(g,"index.value"):kt(g)},condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq"],range:g=>ki(g,u)},tag:g=>{if(g==null)return g;if(typeof g=="string")return St(g,"tag");throw new l('"tag" should be type: string.',{code:"INVALID_PARAMETER"})},private_key:"string"});e=y.Params(e||{},d(e),a||s?[]:["table"],{ignoreEmpty:true});}return {query:e,is_reference_fetch:n}}async function Fi(e,t){await this.__connection,await it.call(this,"getRecords");let r=await Li.bind(this)(e),n=r.is_reference_fetch,i=await k.bind(this)("get-records",r.query,{fetchOptions:t,auth:!!this.__user,method:this.__user?"post":"get"});n&&i?.reference_private_key&&typeof i.reference_private_key=="string"&&(this.__private_access_key[n]=i.reference_private_key);let s=[];for(let o in i.list)s.push(Se.bind(this)(i.list[o]));return i.list=await Promise.all(s),i}function Mi(e){let t="",r=[],n=Dt.bind(this)(e?.service,e?.owner),i=y.Params(e||{},{record_id:o=>{let a=typeof o=="string"?Pr.bind(this)(n,o):void 0;return a||fe(o,"record_id",{allowEmpty:false})},unique_id:["string",null],readonly:"boolean",table:{name:o=>Le(o,"table.name"),subscription:[null,{is_subscription_record:"boolean",upload_to_feed:"boolean",notify_subscribers:"boolean",feed_referencing_records:"boolean",notify_referencing_records:"boolean"}],access_group:Ir.bind(this)},source:{referencing_limit:o=>{if(o===null)return null;if(typeof o=="number"){if(0>o)throw new l('"reference_limit" should be >= 0',{code:"INVALID_PARAMETER"});if(o>4503599627370546)throw new l('"reference_limit" should be <= 4503599627370546',{code:"INVALID_PARAMETER"});return o}throw new l('"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:o=>{if(o===void 0)return;if(!o||Array.isArray(o)&&!o.length)return null;let a={name:u=>nt(u,'"name" in "index_restrictions"'),value:u=>kt(u),condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne",()=>null],range:u=>{if(u!==null&&typeof o.value!=typeof u)throw new l('Index restriction "range" type should match the type of "value".',{code:"INVALID_PARAMETER"});if(!o.hasOwnProperty("value"))throw new l('Index restriction "value" is required.',{code:"INVALID_PARAMETER"});return u}};Array.isArray(o)||(o=[o]);let d=o.map(u=>y.Params(u,a,["name"]));if(d.length)for(let u of d)u.condition&&u.hasOwnProperty("range")&&delete u.range;return d}},reference:o=>{if(o===null)return {record_id:null};if(o){if(typeof o=="string"){t=o;let a=Pr.bind(this)(n,o);return a||o}if(typeof o!="object")throw new l('"reference" should be type: <string | object>.',{code:"INVALID_PARAMETER"});return y.Params(o,{unique_id:"string",record_id:a=>a==null?a:(t=a,typeof this.__private_access_key?.[a]=="string"&&(e.reference_private_key=this.__private_access_key[a]||void 0),fe(a,"reference.record_id",{allowEmpty:false,onlyAlphanumeric:true}))})}},index:[null,{name:o=>nt(o,"index.name"),value:o=>kt(o)}],tags:o=>{if(o==null)return o;if(typeof o=="string"&&(o=o.split(",").map(a=>a.trim())),!Array.isArray(o))throw new l('"tag" should be type: <string | string[]>.',{code:"INVALID_PARAMETER"});return o.map(a=>St(a,"tag"))},remove_bin:o=>{if(!o)return null;let a=[];if(Array.isArray(o))for(let d of o)if(typeof d=="string")a.push(d.split("?")[0]);else if(d.url&&d.size&&d.filename){let g=d.url.split("/").slice(0,3).join("/")+"/"+d.path;a.push(g);}else throw new l('"remove_bin" should be type: <string[] | BinaryFile[] | null>',{code:"INVALID_PARAMETER"});else throw new l('"remove_bin" should be type: <string[] | BinaryFile[] | null>',{code:"INVALID_PARAMETER"});return a},progress:"function",data:o=>o},[],{precall:o=>{let a=o?.data||{};if(!a?.record_id&&!a.table)throw new l('"table.name" is required.',{code:"INVALID_PARAMETER"});typeof a.table=="string"&&(a.table={name:a.table},a?.record_id||(a.table.access_group=0)),o.files&&(r=o.files);}}),s=e.progress||null;if(delete i.progress,!this.__user){let o=!!(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 l("Public users cannot update existing records.",{code:"INVALID_REQUEST"});if(i.table.access_group!=="public"&&i.table.access_group!==0)throw new l("Public users can only post records to public tables.",{code:"INVALID_REQUEST"});if(o)throw new l("Public users cannot post subscription records.",{code:"INVALID_REQUEST"});if(i.remove_bin)throw new l("Public users cannot remove files from records.",{code:"INVALID_REQUEST"});if(i.unique_id)throw new l("Public users cannot set unique_id for records.",{code:"INVALID_REQUEST"})}return {config:i,progress:s,is_reference_post:t,files:r}}async function qi(e){if(await this.__connection,!Array.isArray(e)||!e.length)throw new l('"params" should be a non-empty array.',{code:"INVALID_PARAMETER"});let t=[],r,n,i=null,s={},o={},d={_is_bulk_:await Promise.all(e.map(async(h,m)=>{if(!h||typeof h!="object"||Array.isArray(h))throw new l(`"params[${m}]" should be type: <object>.`,{code:"INVALID_PARAMETER"});o[m]={has:h.data!==void 0,value:h.data};let w=Mi.bind(this)(h),b=w.config;if(L.call(this)){let _=Object.prototype.hasOwnProperty.call(b,"data"),E=await cr.bind(this)(b.data,Oi(h,b),_);E.encrypted&&(b.data=E.send,s[m]=E.plain);}if(w.is_reference_post&&t.push(w.is_reference_post),typeof b.progress=="function"&&i===null&&(i=b.progress),b.service!==void 0){if(r===void 0)r=b.service;else if(r!==b.service)throw new l('All bulk params should share the same "service" value.',{code:"INVALID_PARAMETER"})}if(b.owner!==void 0){if(n===void 0)n=b.owner;else if(n!==b.owner)throw new l('All bulk params should share the same "owner" value.',{code:"INVALID_PARAMETER"})}return delete b.progress,delete b.service,delete b.owner,b})),service:"",owner:""};r!==void 0&&(d.service=r),n!==void 0&&(d.owner=n);let u={auth:!!this.__user,method:"post"},g={};Object.keys(g).length&&Object.assign(u,{fetchOptions:g});let f=await k.bind(this)("post-record",d,u),c=await Promise.all(f.map((h,m)=>Se.bind(this)(h,"called from postRecord",o[m]?.has===true,s.hasOwnProperty(m))));for(let h=0;h<c.length;h++)s.hasOwnProperty(h)&&c[h]&&!c[h].error?(c[h].data=s[h],c[h].encrypted={status:"encrypted"}):o[h]?.has&&c[h]&&!f[h]?.error&&Sr(f[h]?.data)&&(c[h].data=o[h].value);let p=Dt.bind(this)(r,n);for(let h=0;h<f.length;h++){let m=f[h],w=c[h];if(m&&typeof m=="object"&&m.error&&w&&!w.record_id&&(w.error=m.error),typeof m?.reference_private_key=="string")for(let b of t)this.__private_access_key[b]=m.reference_private_key;w?.unique_id&&Ci.bind(this)(p,w.unique_id,w.record_id);}return c}async function kr(e,t,r){if(await this.__connection,!t)throw new l('"config" argument is required.',{code:"INVALID_PARAMETER"});let n=Mi.bind(this)(t),i=n.config,s=n.progress,o=n.is_reference_post,a={auth:!!this.__user,method:"post"},d=[],u=j(e);r&&Array.isArray(r)&&r.length&&(d=d.concat(r)),u.files&&Array.isArray(u.files)&&u.files.length&&(d=d.concat(u.files));let g=t?.data!==void 0?t.data:u.data,f=g!==void 0,c=await cr.bind(this)(g,Oi(t,i),f),p=null;p=Object.assign({},i),delete p.data,c.omit||(p.data=c.send);let h={};if(typeof s=="function"&&(h.progress=s),Object.keys(h).length&&Object.assign(a,{fetchOptions:h}),c.files==="decrypt"&&t?.record_id){let E=await _r.bind(this)(t.record_id,"decrypt",s);if(E.length){let S=p.remove_bin;p.remove_bin=Array.isArray(S)?S.concat(E):E;}}if(c.spill&&t?.record_id){let E=new FormData;if(E.append(Xe,new File([c.spill],"payload.bin",{type:"application/octet-stream"})),await rt.bind(this)(E,{record_id:t.record_id}),c.retireCt){let S=p.remove_bin,A=[c.retireCt];p.remove_bin=Array.isArray(S)?S.concat(A):A;}}let m=await k.bind(this)("post-record",p,a);if(c.encrypted&&m?.rec&&Pn.bind(this)(m.rec,c.dek),c.files==="encrypt"&&m?.rec)try{let E=await _r.bind(this)(m.rec,"encrypt",s);E.length&&await kr.bind(this)(void 0,{record_id:m.rec,remove_bin:E});}catch(E){console.error("Failed to encrypt existing attachments after making the record private:",E);}if(J()&&d.length){let E=new FormData;for(let N of d)E.append(N.name,N.file,N.file.name);let S={record_id:m.rec,progress:s};i.hasOwnProperty("service")&&(S.service=i.service);let{bin_endpoints:A}=await rt.bind(this)(E,S);m.bin?m.bin.push(...A):m.bin=A;}o&&typeof m?.reference_private_key=="string"&&(this.__private_access_key[o]=m.reference_private_key);let w=!!m&&Sr(m.data),b=!c.omit&&c.send!==void 0,_=await Se.bind(this)(m,"called from postRecord",b,c.encrypted);if(w&&b&&!c.encrypted&&(_.data=c.plain),c.encrypted&&(_.data=c.plain,_.encrypted={status:"encrypted",recipients:Object.keys(c.send.k||{})}),_.unique_id){let E=Dt.bind(this)(i?.service,i?.owner);Ci.bind(this)(E,_.unique_id,_.record_id),J()&&(this.__uniqueIdsPersistTimer!==null&&clearTimeout(this.__uniqueIdsPersistTimer),this.__uniqueIdsPersistTimer=setTimeout(()=>{this.__uniqueIdsPersistTimer=null;try{window.sessionStorage.setItem(`${E}:uniqueids`,JSON.stringify(this.__my_unique_ids[E]||{}));}catch{}},500));}return _}async function Vi(e,t){await it.call(this,"getTables");let r=await k.bind(this)("get-table",y.Params(e||{},{table:i=>Le(i,"table",{allowEmpty:true}),condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}),Object.assign({auth:!!this.__user},{fetchOptions:t})),n={cnt_rec:"number_of_records",tbl:"table",srvc:"service",grp_:"number_of_records_in_access_group_"};if(Array.isArray(r?.list))for(let i of r.list){for(let s in n){if(s==="grp_"){for(let o in i)if(o.startsWith("grp_")){let a=o.substring(4);a==="pv"?a="private":a==="00"?a="public":a==="01"?a="authorized":a==="99"&&(a="admin"),i[`number_of_records_in_access_group_${a}`]=i[o],delete i[o];}}i.hasOwnProperty(s)&&(i[n[s]]=i[s],delete i[s]);}typeof i.table=="string"&&(i.table=le(i.table));}return r}async function $i(e,t){if(await it.call(this,"getIndexes"),!e?.table)throw new l('"table" is required.',{code:"INVALID_PARAMETER"});let r=y.Params(e||{},{table:s=>Le(s,"table",{allowEmpty:true}),index:s=>nt(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:s=>{if(e?.order?.by==="index_name"&&typeof s=="string")return fe(s,"order.value",{allowEmpty:true,maxLength:256,blockKeyDelimiters:true});if(typeof s!="string"&&typeof s!="number"&&typeof s!="boolean")throw new l('"order.value" should be type: <string | number | boolean>.',{code:"INVALID_PARAMETER"});return s},condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}},["table"]);if(r.hasOwnProperty("order")){if(!r.order?.by)throw new l('"order.by" is required.',{code:"INVALID_PARAMETER"});if(r.order.hasOwnProperty("condition")&&!r.order.hasOwnProperty("value"))throw new l('"value" is required for "condition".',{code:"INVALID_PARAMETER"});if(r.hasOwnProperty("index")&&r.index.substring(r.index.length-1)!==".")throw new l('"index" should be a parent index name of the compound index when using "order.by"',{code:"INVALID_PARAMETER"})}let n=await k.bind(this)("get-index",r,Object.assign({auth:!!this.__user},{fetchOptions:t})),i={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(n?.list)&&(n.list=n.list.map(s=>{let o=s.idx.split("/"),a={table:le(o[1]),index:le(o[2]),number_of_records:s.cnt_rec};for(let d in i)Object.prototype.hasOwnProperty.call(s,d)&&(a[i[d]]=s[d]);return a})),n}async function ji(e,t){await it.call(this,"getTags");let r=await k.bind(this)("get-tag",y.Params(e||{},{table:n=>Le(n,"table",{allowEmpty:true}),tag:n=>St(n,"tag",{allowEmpty:true}),condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}),Object.assign({auth:!!this.__user},{fetchOptions:t}));return Array.isArray(r?.list)&&(r.list=r.list.map(n=>{let i=n.tag.split("/");return {table:le(i[1]),tag:le(i[0]),number_of_records:n.cnt_rec}})),r}async function Bi(e,t){await it.call(this,"getUniqueId");let r=await k.bind(this)("get-uniqueid",y.Params(e||{},{unique_id:"string",condition:["gt","gte","lt","lte",">",">=","<","<=","=","eq","!=","ne"]}),Object.assign({auth:!!this.__user},{fetchOptions:t}));if(Array.isArray(r?.list))for(let n in r.list){let i=r.list[n];r.list[n]={unique_id:i.unq,record_id:i.rec};}return r}async function Ki(e,t){await this.__connection;let r=await Li.bind(this)(e,true),n=r.is_reference_fetch,i=await k.bind(this)("del-records",r.query,{auth:true,fetchOptions:t});return n&&typeof i?.reference_private_key=="string"&&(this.__private_access_key[n]=i.reference_private_key),Array.isArray(i?.list)&&(i.list=await Promise.all(i.list.map(async s=>{if(!s||typeof s!="object")return s;try{return await Se.bind(this)(s,"called from deleteRecords",!0,!1,!0)}catch{return s}}))),i?.message||i}async function Hi(e){if(L.call(this)){let t=typeof e.user_id=="string"?[e.user_id]:e.user_id;Array.isArray(t)&&t.length&&await yr.bind(this)(e.record_id,t);}return zi.bind(this)({record_id:e.record_id,user_id:e.user_id,execute:"add"})}async function Gi(e){let t=await zi.bind(this)({record_id:e.record_id,user_id:e.user_id||null,execute:"remove"});if(L.call(this)){let r=typeof e.user_id=="string"?[e.user_id]:e.user_id;await $n.bind(this)(e.record_id,Array.isArray(r)&&r.length?r:null);}return t}async function Wi(e,t){let r={record_id:e.record_id||void 0,user_id:e.user_id||void 0,execute:"list"};if(!r.record_id&&!r.user_id)throw new l("Either record_id or user_id must be provided.",{code:"INVALID_PARAMETER"});if(r.user_id)if(typeof r.user_id=="string")y.UserId(r.user_id),r.user_id=[r.user_id];else if(Array.isArray(r.user_id))for(let s of r.user_id)y.UserId(s);else throw new l("user_id should be type: <string | string[]>",{code:"INVALID_PARAMETER"});let n=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),i=await k.bind(this)("grant-private-access",r,{auth:true,fetchOptions:t});return i.list=i.list.map(n),i}function Qi(e){let t=e.record_id,r=e.reference_id||void 0;if(!t)throw new l("Record ID is required.",{code:"INVALID_PARAMETER"});if(typeof t!="string")throw new l("Record ID should be type: <string | string[]>",{code:"INVALID_PARAMETER"});if(r&&typeof r!="string")throw new l("Reference ID should be type: <string>",{code:"INVALID_PARAMETER"});if(typeof this.__private_access_key[t]=="string")return Promise.resolve(this.__private_access_key[t]);if(vt[t])return vt[t];let n=k.bind(this)("request-private-access-key",{record_id:t,reference_id:r},{auth:true}).then(i=>{let s=typeof i=="string"?i:i?.private_key;if(typeof s!="string")throw new l("Invalid private access key response.",{code:"ERROR"});return this.__private_access_key[t]=s,s}).finally(()=>{delete vt[t];});return vt[t]=n,n}function zi(e){e.execute;let r=y.Params(e,{record_id:"string",user_id:n=>{if(!n)throw new l("User ID is required.",{code:"INVALID_PARAMETER"});let i=n;if(typeof i=="string"&&(i=[i]),i.length>100)throw new l("Cannot process more than 100 users at once.",{code:"INVALID_REQUEST"});for(let s of i)y.UserId(s,'User ID in "user_id"');return i},execute:["add","remove"]},["execute","record_id","user_id"]);return r.user_id||(r.user_id=null),k.bind(this)("grant-private-access",r,{auth:true})}var D={},H={},ce={},pe={},ge={},xt={},Ut={};function Ji(e,t,r){e[t]||(e[t]=[]),e[t].push(r);}async function Ct(e,t,r){let n=[];if(e[t]){for(let i of e[t])if(i){let s=r(i);s instanceof Promise&&(s=await s),n.push(s);}delete e[t];}return n}async function Nr(e,t){if(!this?.session?.accessToken?.jwtToken)throw new l("Access token is required.",{code:"INVALID_PARAMETER"});let r=await this.__socket;async function n(i,s,o){this.log("answerSdpOffer from",s),await D[s].setRemoteDescription(new RTCSessionDescription(i));let a=await D[s].createAnswer();await D[s].setLocalDescription(a),o.send(JSON.stringify({action:"rtc",uid:s,content:{sdpanswer:a},token:this.session.accessToken.jwtToken}));}D?.[t]?e?(await Ct(Ut,t,i=>n.bind(this)(i,t,r)),await n.bind(this)(e,t,r)):await Ct(Ut,t,i=>n.bind(this)(i,t,r)):e&&Ji(Ut,t,e);}async function Dr(e,t){if(this.log("receiveIceCandidate",e),D?.[t]&&D[t]?.remoteDescription&&D[t]?.remoteDescription?.type){if(!e)return Ct(xt,t,r=>D[t].addIceCandidate(r));await Ct(xt,t,r=>D[t].addIceCandidate(r)),await D[t].addIceCandidate(e);}else Ji(xt,t,e);}async function ue(e){if(typeof window>"u"||window._runningInNodeJS)throw new l("WebRTC is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});y.Params(e,{cid:s=>{if(typeof s!="string")throw new l('"cid" should be type: <string>.',{code:"INVALID_PARAMETER"});if(s&&s.slice(0,4)!=="cid:")throw new l('"cid" should be a valid connection id.',{code:"INVALID_PARAMETER"});return s},close:"boolean"});let t=await this.__socket,{cid:r,close_all:n=false}=e||{};if(!n&&!r)throw new l('"cid" is required.',{code:"INVALID_PARAMETER"});let i=s=>{if(!s)throw new l('"cid" is required.',{code:"INVALID_PARAMETER"});if(delete Ut[s],delete xt[s],H[s]&&Object.values(H[s]).forEach(o=>{o.readyState!=="closed"&&o.close();}),delete H[s],D?.[s]){D[s].connectionState!=="closed"&&(D[s].close(),t.send(JSON.stringify({action:"rtc",uid:s,content:{hungup:this.user.user_id},token:this.session.accessToken.jwtToken})));let o={type:"connectionstatechange",target:D[s],timestamp:new Date().toISOString(),state:D[s].connectionState,iceState:D[s].iceConnectionState,signalingState:D[s].signalingState};ge[s]&&ge[s](o),this.log("closeRTC",o);}delete ge[s],delete pe[s],delete ce[s],delete D[s];};if(n)for(let s in D)i(s);else i(r);this.log("Cleaning up media stream..."),this.__mediaStream&&(this.__mediaStream.getTracks().forEach(s=>{s.stop();}),this.__mediaStream=null);}async function Yi(e){if(e instanceof MediaStream)return e;if(!e.video&&!e.audio){let t=new MediaStream,r=document.createElement("canvas");r.width=1,r.height=1;let i=r.captureStream().getVideoTracks()[0];return t.addTrack(i),t}return window.navigator.mediaDevices.getUserMedia(e)}async function Xi(e,t){if(typeof window>"u"||window._runningInNodeJS)throw new l("WebRTC is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(typeof t!="function")throw new l("Callback is required.",{code:"INVALID_PARAMETER"});if(!this?.session?.accessToken?.jwtToken)throw new l("Access token is required.",{code:"INVALID_PARAMETER"});e=y.Params(e,{cid:o=>{if(typeof o!="string")throw new l('"cid" should be type: <string>.',{code:"INVALID_PARAMETER"});if(o&&o.slice(0,4)!=="cid:")throw new l('"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:r,ice:n}=e;if(!(e?.media instanceof MediaStream)&&(e?.media?.video||e?.media?.audio)&&window.location.hostname!=="localhost"&&window.location.protocol!=="https:")throw new l("Media stream is only supported on either localhost or https.",{code:"INVALID_REQUEST"});let i=this.__socket?await this.__socket:this.__socket;if(!i)throw new l("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});if(i.readyState!==1)throw new l("Realtime connection is not ready.",{code:"INVALID_REQUEST"});let s={iceServers:[{urls:n}]};D?.[r]||(D[r]=new RTCPeerConnection(s)),e?.media&&(this.__mediaStream=await Yi(e.media),this.__mediaStream.getTracks().forEach(o=>{D[r].addTrack(o,this.__mediaStream);})),ge[r]=t,H[r]||(H[r]={});for(let o=0;o<e.channels.length;o++){let a=e.channels[o];if(typeof a=="string")switch(a){case "text-chat":a={ordered:true,maxRetransmits:10,protocol:"text-chat"};break;case "file-transfer":a={ordered:false,maxPacketLifeTime:3e3,protocol:"file-transfer"};break;case "video-chat":a={ordered:true,maxRetransmits:10,protocol:"video-chat"};break;case "voice-chat":a={ordered:true,maxRetransmits:10,protocol:"voice-chat"};break;case "gaming":a={ordered:false,maxPacketLifeTime:100,protocol:"gaming"};break;default:a={ordered:true,maxRetransmits:10,protocol:"default"};break}let d=a.protocol||"default";if(Object.keys(H[r]).includes(d))throw new l(`Data channel with the protocol "${d}" already exists.`,{code:"INVALID_REQUEST"});let u=D[r].createDataChannel(d,a);H[r][d]=u;}for(let o in H[r]){let a=H[r][o];ts.bind(this)(r,a);}return es.bind(this)(r,["onnegotiationneeded"]),await vr.bind(this)(r),{hangup:()=>ce[r]&&ce[r](false),connection:new Promise(o=>{ce[r]=(a=>{if(this.log("receiver picked up the call",r),!a)return ue.bind(this)({cid:r}),null;D[r].onnegotiationneeded=()=>{this.log("onnegotiationneeded",`sending offer to "${r}".`),vr.bind(this)(r),ge[r]&&ge[r]({type:"negotiationneeded",target:D[r],timestamp:new Date().toISOString(),signalingState:D[r].signalingState,connectionState:D[r].iceConnectionState,gatheringState:D[r].iceGatheringState});},o({target:D[r],channels:H[r],hangup:()=>ue.bind(this)({cid:r}),media:this.__mediaStream});}).bind(this);})}}function Zi(e){return async(t,r)=>{t=t||{},t=j(t).data;let n=e.sender_cid,i=await this.__socket;if(!pe[n])return null;if(typeof r!="function")throw new l("Callback is required.",{code:"INVALID_PARAMETER"});if(!(t?.media instanceof MediaStream)&&(t?.media?.video||t?.media?.audio)&&window.location.hostname!=="localhost"&&window.location.protocol!=="https:")throw new l("Media stream is only supported on either localhost or https.",{code:"INVALID_REQUEST"});let{ice:s="stun:stun.skapi.com:3468"}=t;return D?.[n]||(D[n]=new RTCPeerConnection({iceServers:[{urls:s}]})),t?.media&&(this.__mediaStream=await Yi(t.media),this.__mediaStream.getTracks().forEach(o=>{D[n].addTrack(o,this.__mediaStream);})),delete pe[n],ge[n]=r,H[n]||(H[n]={}),D[n].ondatachannel=o=>{this.log("ondatachannel",`received data channel "${o.channel.label}".`);let a=o.channel;H[n][a.label]=a,ts.bind(this)(n,a);},es.bind(this)(n,["onnegotiationneeded"]),await Nr.bind(this)(null,n),await Dr.bind(this)(null,n),i.send(JSON.stringify({action:"rtc",uid:n,content:{pickup:this.user.user_id},token:this.session.accessToken.jwtToken})),{target:D[n],channels:H[n],hangup:()=>ue.bind(this)({cid:n}),media:this.__mediaStream}}}async function vr(e){if(!this?.session?.accessToken?.jwtToken)throw new l("Access token is required.",{code:"INVALID_PARAMETER"});this.log("sendOffer",e);let t=await this.__socket,r=await D[e].createOffer();await D[e].setLocalDescription(r);let n=D[e].localDescription;this.log("rtcSdpOffer to",n),t.send(JSON.stringify({action:"rtc",uid:e,content:{sdpoffer:n},token:this.session.accessToken.jwtToken}));}async function Ba(e,t){if(!this?.session?.accessToken?.jwtToken)throw new l("Access token is required.",{code:"INVALID_PARAMETER"});this.log("sendIceCandidate to",t);let r=await this.__socket;if(!e.candidate){this.log("candidate-end","all ice candidates have been sent");return}let n=ge[t]||(()=>{}),i=e.candidate;this.log("ice gathering state set to",D[t].iceGatheringState),n({type:"icecandidate",target:D[t],timestamp:new Date().toISOString(),candidate:e.candidate.candidate,sdpMid:e.candidate.sdpMid,sdpMLineIndex:e.candidate.sdpMLineIndex,usernameFragment:e.candidate.usernameFragment,protocol:e.candidate.protocol,gatheringState:D[t].iceGatheringState,connectionState:D[t].iceConnectionState}),r.send(JSON.stringify({action:"rtc",uid:t,content:{candidate:i},token:this.session.accessToken.jwtToken}));}function es(e,t){let r=new Set(t),n=ge[e]||(o=>{}),i=D[e],s={ontrack:o=>{n({type:"track",target:i,timeStamp:o.timeStamp,streams:o.streams,track:o.track});},onicecandidate:o=>{Ba.bind(this)(o,e),o.candidate?n({type:"icecandidate",target:i,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:i.iceGatheringState,connectionState:i.iceConnectionState}):n({type:"icecandidateend",target:i,timestamp:new Date().toISOString()});},onicecandidateerror:o=>{n({type:"icecandidateerror",target:i,timestamp:new Date().toISOString(),errorCode:o.errorCode,errorText:o.errorText,url:o.url,hostCandidate:o.hostCandidate,gatheringState:i.iceGatheringState,connectionState:i.iceConnectionState});},oniceconnectionstatechange:()=>{n({type:"iceconnectionstatechange",target:i,timestamp:new Date().toISOString(),state:i.iceConnectionState,gatheringState:i.iceGatheringState,signalingState:i.signalingState});},onicegatheringstatechange:()=>{n({type:"icegatheringstatechange",target:i,timestamp:new Date().toISOString(),state:i.iceGatheringState,connectionState:i.iceConnectionState,signalingState:i.signalingState});},onsignalingstatechange:()=>{n({type:"signalingstatechange",target:i,timestamp:new Date().toISOString(),state:i.signalingState,connectionState:i.iceConnectionState,gatheringState:i.iceGatheringState});},onnegotiationneeded:()=>{vr.bind(this)(e),n({type:"negotiationneeded",target:i,timestamp:new Date().toISOString(),signalingState:i.signalingState,connectionState:i.iceConnectionState,gatheringState:i.iceGatheringState});},onconnectionstatechange:()=>{n({type:"connectionstatechange",target:i,timestamp:new Date().toISOString(),state:i.connectionState,iceState:i.iceConnectionState,signalingState:i.signalingState});let o=i.connectionState;(o==="disconnected"||o==="failed"||o==="closed")&&ue.bind(this)({cid:e});}};for(let[o,a]of Object.entries(s))r.has(o)||(i[o]=a);}function ts(e,t,r){let n=new Set(r),i=ge[e]||(o=>{}),s={onmessage:o=>{let a={type:o.type,target:t,timeStamp:o.timeStamp,data:o.data,lastEventId:o.lastEventId,origin:o.origin,readyState:t.readyState,bufferedAmount:t.bufferedAmount};this.log(`${t.label}: message`,o.data),i(a);},onerror:o=>{let a={type:o.type,target:t,timeStamp:o.timeStamp,error:o.error.message,errorCode:o.error.errorDetail,readyState:t.readyState,label:t.label};this.log(`${t.label}: error`,o.error.message),i(a);},onclose:o=>{let a={type:o.type,target:t,timeStamp:o.timeStamp,readyState:t.readyState,label:t.label,id:t.id};this.log(`${t.label}: closed`,null),i(a),H[e]&&(delete H[e][t.label],Object.keys(H[e]).length===0&&ue.bind(this)({cid:e}));},onbufferedamountlow:o=>{let a={target:t,bufferedAmount:t.bufferedAmount,bufferedAmountLowThreshold:t.bufferedAmountLowThreshold,type:o.type,timeStamp:o.timeStamp};this.log(`${t.label}: bufferedamountlow`,t.bufferedAmount),i(a);},onopen:o=>{this.log("dataChannel",`data channel: "${t.label}" is open and ready to send messages.`);let a={type:o.type,target:t,timeStamp:o.timeStamp,readyState:t.readyState,label:t.label,id:t.id,ordered:t.ordered,maxRetransmits:t.maxRetransmits,protocol:t.protocol};i(a);}};for(let[o,a]of Object.entries(s))n.has(o)||(t[o]=a);}var we;function rs(){return we}var Re=null,st=true,Me=0;async function Ka(){if(typeof window>"u"||window._runningInNodeJS)throw new l("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.getProfile(),!this.session)throw new l("No access.",{code:"INVALID_REQUEST"});let e=await this.record_endpoint;return new WebSocket(e.websocket_private+"?token="+this.session.accessToken.jwtToken)}var xr=null;async function Ot(){if(typeof window>"u"||window._runningInNodeJS)throw new l("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});st=true;let e=this.__socket?await this.__socket:this.__socket;ue.bind(this)({close_all:true}),we&&Ve.bind(this)({group:null}),Me=0,Re&&(Re.terminate(),Re=null);try{e&&e.close();}catch{}return window.removeEventListener("visibilitychange",xr),this.__socket=null,null}async function qe(e,t=50,r){if(typeof window>"u"||window._runningInNodeJS)throw new l("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(typeof e!="function")throw new l("Callback must be a function.",{code:"INVALID_REQUEST"});if(r==="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(st&&(xr=()=>{!document.hidden&&!st&&qe.bind(this)(e,0,"reconnect");},this.__socket instanceof Promise))return this.__socket;Re&&(Re.terminate(),Re=null);let n={value:null};return this.__socket=new Promise(async(i,s)=>{let o=a=>{this.__socket===n.value&&(this.__socket=null),s(a);};try{await Ce.bind(this)();}catch(a){o(a);return}setTimeout(async()=>{try{let a=await Ka.bind(this)();a.onopen=()=>{st=!1,Me=0,r!=="reconnect"&&window.addEventListener("visibilitychange",xr),this.log("realtime onopen","Connected to WebSocket server."),e({type:"success",message:"Connected to WebSocket server."}),we&&a.send(JSON.stringify({action:"joinRoom",rid:we,token:this.session.accessToken.jwtToken}));let d=`
|
|
207
207
|
let interval = 15000; // Set interval time 15 seconds
|
|
208
208
|
|
|
209
209
|
function runInterval() {
|
|
@@ -212,9 +212,9 @@ var Qs=Object.defineProperty;var zs=Object.getOwnPropertyDescriptor;var ke=(e=>t
|
|
|
212
212
|
}
|
|
213
213
|
|
|
214
214
|
runInterval(); // Start interval
|
|
215
|
-
`,l=new Blob([u],{type:"application/javascript"});Ae=new Worker(URL.createObjectURL(l)),Ae.onmessage=g=>{a.readyState===1&&a.send(JSON.stringify({action:"keepAlive"}));},i(a);},a.onmessage=async u=>{let l="";try{l=JSON.parse(decodeURI(u.data)),this.log("socket onmessage",l);}catch{return}let g;switch(!0){case !!l?.["#message"]:g="message";break;case !!l?.["#private"]:g="private";break;case !!l?.["#notice"]:g="notice";break;case !!l?.["#rtc"]:g="rtc";break;case !!l?.["#error"]:g="error";break}if(!g)return;let f={type:g,message:l?.["#rtc"]||l?.["#message"]||l?.["#private"]||l?.["#notice"]||l?.["#error"]||null,sender:l?.["#user_id"]||null,sender_cid:l?.["#scid"]?"cid:"+l["#scid"]:null,sender_rid:l?.["#srid"]||null,code:l?.["#code"]||null};if(g==="notice")e(f);else if(g==="rtc"){if(f.sender!==this.user.user_id){let d=f.message;if(d.hungup){ce[f.sender_cid]&&(ce[f.sender_cid](!1),delete ce[f.sender_cid]),pe[f.sender_cid]&&delete pe[f.sender_cid],N?.[f.sender_cid]&&ue.bind(this)({cid:f.sender_cid}),f.type="rtc:closed",e(f);return}if(d.candidate&&Pr.bind(this)(d.candidate,f.sender_cid),d.sdpoffer&&(Tr.bind(this)(d.sdpoffer,f.sender_cid),pe[f.sender_cid]||(pe[f.sender_cid]=f.sender_cid,delete f.message,f.connectRTC=Vi.bind(this)(f),f.type="rtc:incoming",f.hangup=(()=>{N[f.sender_cid]?ue.bind(this)({cid:f.sender_cid}):pe[f.sender_cid]&&(delete pe[f.sender_cid],a.send(JSON.stringify({action:"rtc",uid:f.sender_cid,content:{hungup:this.user.user_id},token:this.session.accessToken.jwtToken})));}).bind(this),e(f))),d.pickup&&ce[f.sender_cid]&&(ce[f.sender_cid](!0),delete ce[f.sender_cid]),d.sdpanswer&&N[f.sender_cid])if(N[f.sender_cid].signalingState==="have-local-offer")await N[f.sender_cid].setRemoteDescription(new RTCSessionDescription(d.sdpanswer));else throw new c("Invalid signaling state.",{code:"INVALID_REQUEST"})}}else e(f);},a.onclose=()=>{it?(this.log("realtime onclose","WebSocket connection closed."),e({type:"close",message:"WebSocket connection closed."})):(this.log("realtime onclose","WebSocket unexpected close."),e({type:"error",message:"Skapi: WebSocket unexpected close."}),Me++,Me<3?(this.log("realtime onclose","Reconnecting to WebSocket server..."+Me),e({type:"reconnect",message:"Reconnecting to WebSocket server..."+Me}),Fe.bind(this)(e,3e3,"reconnect")):(this.log("realtime onclose","Max reconnection attempts reached."),e({type:"error",message:"Skapi: Max reconnection attempts reached."})));},a.onerror=()=>{this.log("realtime onerror","WebSocket connection error."),e({type:"error",message:"Skapi: WebSocket connection error."});};}catch(a){o(a);}},t);}),n.value=this.__socket,this.__socket}async function Ki(e,t,r){if(typeof window>"u"||window._runningInNodeJS)throw new c("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});let n=this.__socket?await this.__socket:this.__socket;if(!n)throw new c("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});if(!t)throw new c("No recipient.",{code:"INVALID_REQUEST"});await Ce.bind(this)(),e=j(e).data;let i="";if(r&&(r=h.Params(r,{config:{always:"boolean"},title:"string",body:"string"},["title","body"]),i=JSON.stringify({title:r.title,body:r.body}),new Blob([i]).size>3072))throw new c("Notification size exceeds 3kb.",{code:"INVALID_PARAMETER"});if(n.readyState===1){try{h.UserId(t),n.send(JSON.stringify({action:"sendMessage",uid:t,content:e,notification:i,notificationConfig:r?.config||{},token:`IdT:${this.service}:${this.owner}:`+(this.bearerToken||this.session?.idToken?.jwtToken||"null")}));}catch(s){if(this.log("postRealtime:err",{err:s}),_e!==t)throw new c(`User has not joined to the recipient group. Run joinRealtime({ group: "${t}" })`,{code:"INVALID_REQUEST"});n.send(JSON.stringify({action:"broadcast",rid:t,content:e,notification:i,notificationConfig:r?.config||{},token:`IdT:${this.service}:${this.owner}:`+(this.bearerToken||this.session?.idToken?.jwtToken||"null")}));}return {type:"success",message:"Message sent."}}throw new c("Realtime connection is not open. Try reconnecting with connectRealtime().",{code:"INVALID_REQUEST"})}async function qe(e){if(typeof window>"u"||window._runningInNodeJS)throw new c("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});let t=this.__socket?await this.__socket:this.__socket;if(!t)throw new c("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});await Ce.bind(this)(),e=j(e,{nullIfEmpty:true}).data;let{group:r=null}=e;if(!r&&!_e)return {type:"success",message:"Left realtime message group."};if(r!==null&&typeof r!="string")throw new c('"group" must be a string | null.',{code:"INVALID_PARAMETER"});return t.readyState===1&&t.send(JSON.stringify({action:"joinRoom",rid:r,token:this.session.accessToken.jwtToken})),_e=r,{type:"success",message:r?`Joined realtime message group: "${r}".`:"Left realtime message group."}}async function Hi(e,t){e=h.Params(e,{user_id:n=>h.UserId(n,'User ID in "user_id"'),group:["string",()=>{if(!_e)throw new c('No group has been joined. Otherwise "group" is required.',{code:"INVALID_REQUEST"});return _e}]});let r=await T.bind(this)("get-ws-group",e,{fetchOptions:t,auth:true,method:"post"});return r.list=r.list.map(n=>({user_id:n.uid.split("#")[1],cid:"cid:"+n.cid})),r}async function Gi(e,t){if(await this.__connection,e||(e={searchFor:"group",value:" ",condition:">"}),e=h.Params(e,{searchFor:["group","number_of_users",()=>"group"],value:["string","number",()=>e?.searchFor&&e?.searchFor==="number_of_users"?0:" "],condition:[">",">=","=","<","<=","!=","gt","gte","eq","lt","lte","ne"],range:["string","number"]}),e.condition||(e.value===" "||!e.value?e.condition=">":e.condition="="),e.range&&e.condition&&delete e.condition,e.searchFor==="number_of_users"&&typeof e.value!="number")throw new c('"value" must be a number.',{code:"INVALID_PARAMETER"});if(e.searchFor==="group"&&typeof e.value!="string")throw new c('"value" must be a string.',{code:"INVALID_PARAMETER"});if(e.hasOwnProperty("range")&&typeof e.range!=typeof e.value)throw new c(`"range" must be a ${typeof e.value}.`,{code:"INVALID_PARAMETER"});let r=await T.bind(this)("get-ws-group",e,{fetchOptions:t,auth:true,method:"post"});return r.list=r.list.map(n=>({group:n.rid.split("#")[1],number_of_users:n.cnt})),r}var Qi=typeof FormData<"u",zi=typeof HTMLFormElement<"u",Ji=typeof SubmitEvent<"u",he={},st={},te={};function ot(e){return Object.freeze({id:e,status:"stopped"})}function Yi(e){return !!e&&typeof e=="object"&&e.status==="stopped"}var Xi=3;function Zi(e,t,r){let n=false,i=Array.isArray(e?.chunks)?e.chunks.slice():[];i.sort((s,o)=>(s?.seq||0)-(o?.seq||0));for(let s of i)if(!(!s||typeof s.seq!="number"||s.seq<=t.seq)&&(t.seq=s.seq,n=true,r&&typeof s.txt=="string"&&s.txt!==""))try{r(s.txt,s.seq,"poll");}catch(o){console.error(o);}return typeof e?.last_seq=="number"&&e.last_seq>t.seq&&(t.seq=e.last_seq,n=true),n}var Pa=2e3,es=5e3,Sa=2e3,ka=5,va=1500,Dt=null;function ts(e,t,r){let n=new Map,i=false,s=false,o=0,a={socket:0,poll:0},u=(d,p,m)=>{if(e.seq=d,!(!t||typeof p!="string"||p===""))try{t(p,d,m);}catch(y){console.error(y);}},l=()=>{for(let d of Array.from(n.keys()))d<=e.seq&&n.delete(d);for(;;){let d=e.seq+1;if(!n.has(d))break;let p=n.get(d);n.delete(d),u(d,p.txt,p.via);}};return {cursor:e,open:()=>{i||s||(i=true,l());},fromPoll:d=>{if(s)return false;let p=e.seq,m=e.seq,y=Array.isArray(d?.chunks)?d.chunks:[];for(let w of y){if(!w||typeof w.seq!="number"||w.seq<=e.seq)continue;let b=!n.has(w.seq);b&&(a.poll++,r&&a.poll===1&&r("poll",w.seq)),n.set(w.seq,{txt:typeof w.txt=="string"?w.txt:"",via:b?"poll":n.get(w.seq).via}),w.seq>m&&(m=w.seq);}typeof d?.last_seq=="number"&&d.last_seq>m&&(m=d.last_seq);let _=Array.from(n.keys()).sort((w,b)=>w-b);for(let w of _){if(w<=e.seq){n.delete(w);continue}if(w>m)break;let b=n.get(w);n.delete(w),u(w,b.txt,b.via);}return m>e.seq&&(e.seq=m),l(),e.seq>p},fromSocket:(d,p)=>{s||typeof d!="number"||!Number.isFinite(d)||(o=Date.now(),!(d<=e.seq)&&(!n.has(d)&&n.size>=Sa||(n.has(d)||(a.socket++,r&&a.socket===1&&r("socket",d)),n.set(d,{txt:typeof p=="string"?p:"",via:n.has(d)?n.get(d).via:"socket"}),i&&l())));},warm:()=>o!==0&&Date.now()-o<Pa,stats:()=>({socket:a.socket,poll:a.poll}),close:()=>{s=true,n.clear();}}}function rs(e){if(!this||!this.__network_logs)return {onTransport:void 0,done:()=>{}};let t=Date.now(),r=false;return {onTransport:(n,i)=>{console.log(`%cSKAPI: stream chunk arrived over ${n==="socket"?"WEBSOCKET":"POLL"}`,`color: ${n==="socket"?"green":"orange"};`,{id:e,first_seq:i,after_ms:Date.now()-t});},done:n=>{if(r||!n)return;r=true;let i=n.stats();console.log("%cSKAPI: stream transport","color: blue;",{id:e,over_websocket:i.socket,over_poll:i.poll,took_ms:Date.now()-t});}}}function ns(e,t){let r={stop:()=>{}};if(typeof window>"u"||window._runningInNodeJS||Dt)return r;let n={stopped:false,socket:null,opened:null,joined:false,attempts:0,unavailable:false};Dt=n;let i=l=>{if(n.stopped)return;let g=l?.data;if(typeof g!="string")return;let f=null;try{f=JSON.parse(g);}catch{try{f=JSON.parse(decodeURI(g));}catch{return}}let d=f?.["#message"];if(d==null)return;if(typeof d=="string")try{d=JSON.parse(d);}catch{return}if(typeof d!="object")return;let p=f?.["#srid"];if(typeof p=="string"&&p!==e)return;let m=d.seq;typeof m=="string"&&m!==""&&(m=Number(m)),t.fromSocket(m,d.txt);},s=()=>{if(n.socket){try{n.socket.removeEventListener("message",i);}catch{}try{n.socket.removeEventListener("close",a);}catch{}n.socket=null;}},o=async()=>{let l=n.opened,g=n.joined;if(n.opened=null,n.joined=false,s(),!(!g&&!l))try{let f=this.__socket?await this.__socket:null;if(l&&f===l){await xt.bind(this)();return}g&&f&&Bi()===room&&await qe.bind(this)({group:null});}catch{}},a=()=>{n.stopped||(s(),!n.unavailable&&(n.attempts>=ka||(n.attempts+=1,setTimeout(()=>{n.stopped||u();},va))));},u=async()=>{try{let l=this.__socket?await this.__socket:null;if(n.stopped){o();return}if(!l){if(!this.session){n.unavailable=!0,o();return}if(await Fe.bind(this)(()=>{},0),l=this.__socket?await this.__socket:null,n.stopped){o();return}l&&!n.opened&&(n.opened=l);}if(!l||l.readyState!==1)return;if(l.addEventListener("message",i),l.addEventListener("close",a),n.socket=l,!n.joined&&(await qe.bind(this)({group:e}),n.joined=!0,n.stopped)){o();return}}catch{}};return u(),{stop:()=>{n.stopped||(n.stopped=true,Dt===n&&(Dt=null),o());}}}function is(e){return e?.status==="running"||e?.status==="pending"}function Na(e){return !!e&&typeof e=="object"&&!Array.isArray(e)&&typeof e.status=="string"&&typeof e.id=="string"&&"in_queue"in e}function ss(e,t,r,n){if(!e||typeof e!="string")throw new c('"requestId" should be type: <string>.',{code:"INVALID_PARAMETER"});if(e.includes("#"))return e;if(!t||typeof t!="string"||!r||typeof r!="string")throw new c('"url" and "method" are required to address a request by its short id.',{code:"INVALID_PARAMETER"});return h.Url(t),`[${r.toUpperCase()}]${t.toLowerCase()}#${n}:${e}`}function os({id:e,auth:t,service:r,owner:n,latency:i=1e3,queue:s,seedExecuted:o,onResponse:a,onError:u,onStream:l,realtimeGroup:g}){if(typeof i!="number")throw new c('"latency" should be a number.',{code:"INVALID_PARAMETER"});if(i<0)throw new c('"latency" should be a non-negative number.',{code:"INVALID_PARAMETER"});s&&!he?.[s]&&(he[s]=new Wi({breakWhenError:false,batchSize:1}));let f={stop:null,aborted:false,queue:s};te[e]=f;let d=null,p=()=>{te[e]===f&&delete te[e];},m=()=>new Promise((_,w)=>{let b=false;if(f.aborted){p(),_(ot(e));return}let E={seq:0},k=rs.call(this,e),A=l&&g?ts(E,l,k.onTransport):null,D=A?ns.call(this,g,A):null,x=()=>{k.done(A),D&&D.stop(),A&&A.close();};d=x;let C=0,v=false,U=0,L=typeof o=="number"&&o>0?o:void 0,V=async()=>{if(!(b||v)&&!(A&&A.warm()&&Date.now()-C<es)){v=true;try{for(;;){let ie={id:e,service:r,owner:n};l&&(ie.since=E.seq),C=Date.now();let M=await T.bind(this)("csr-poll",ie,{auth:t});if(b)return;let J=A?A.fromPoll(M):l?Zi(M,E,l):!1;A&&A.open();let lt=is(M);if(typeof M?.executed=="number"&&M.executed>0&&(L=M.executed),M?.more&&J){U=0;continue}if(lt){U=0;return}if(U=M?.more?U+1:0,M?.more&&U<Xi)return;b=!0,a&&a(M,L!==void 0?{executed:L}:void 0),clearInterval(de),x(),p(),_(M);return}}catch(ie){if(b)return;b=true,u&&u(ie),clearInterval(de),x(),p(),w(ie);}finally{v=false;}}},de=setInterval(V,i);A&&V(),f.stop=()=>{b||(b=true,clearInterval(de),x(),p(),_(ot(e)));};}),y=()=>{let _=te[e];_&&(_.stop?_.stop():(_.aborted=true,delete te[e]));};if(s){let _=new Promise((w,b)=>{let E=false,k=he[s].add([async()=>{try{let A=await m();return E||(E=!0,w(A)),A}catch(A){throw E||(E=true,b(A)),A}}])[0];st[e]=k,f.stop=()=>{if(!E){f.aborted=true,d&&d();try{he[s]&&he[s].remove(st[e]);}catch{}delete st[e],p(),E=true,w(ot(e));}};});return Object.assign(_,{stop:y})}else return Object.assign(m(),{stop:y})}function as(e){let t=0,r=[];if(e?.id){if(e.url&&e.method){let n=e.service||this.service;r.push(`[${e.method.toUpperCase()}]${e.url.toLowerCase()}#${n}:${e.id}`);}r.push(e.id);}else if(e?.queue)for(let n in te)te[n]?.queue===e.queue&&r.push(n);else for(let n in te)r.push(n);for(let n of r){let i=te[n];i&&(i.stop?i.stop():(i.aborted=true,delete te[n]),t+=1);}return t}function ls(e,t){if(!e.queue)throw new c('"queue" is required.',{code:"INVALID_PARAMETER"});let r={service:e.service||this.service,owner:e.owner||this.owner,queue:e.queue+":"};return T.bind(this)("csr-poll",r,{auth:true})}async function cs(e){let t=false;if(typeof e.poll=="number"&&e.poll<0)throw new c('"poll" should be a non-negative number.',{code:"INVALID_PARAMETER"});let r=e?.onResponse,n=e?.onError,i=e?.onStream,s=typeof e.poll=="number"?e.poll:e.poll?1e3:0;delete e.poll,(s||e.stream)&&!e.queue&&(e.queue=(this.__user?.user_id||"anonymous")+"-"+Re());let o=l=>{for(let g in l)if(typeof l[g]=="string"&&l[g].includes("$CLIENT_SECRET")){t=true;break}};if(e=h.Params(e,{url:l=>{if(!l||typeof l!="string")throw new c('"url" should be type: <string>.',{code:"INVALID_PARAMETER"});return h.Url(l),l.includes("$CLIENT_SECRET")&&(t=true),l},clientSecretName:"string",method:l=>{if(l&&typeof l!="string")throw new c('"method" should be either "GET" or "POST" or "DELETE" or "PUT".',{code:"INVALID_PARAMETER"});let g=l.toLowerCase();if(g!=="get"&&g!=="post"&&g!=="delete"&&g!=="put")throw new c('"method" should be either "GET" or "POST" or "DELETE" or "PUT".',{code:"INVALID_PARAMETER"});return g},stream:l=>{if(l!=null&&typeof l!="boolean")throw new c('"stream" should be type: <boolean>.',{code:"INVALID_PARAMETER"});return !!l},realtime:l=>{if(l!=null&&typeof l!="boolean")throw new c('"realtime" should be type: <boolean>.',{code:"INVALID_PARAMETER"});return !!l},headers:l=>{if(l&&typeof l!="object")throw new c('"headers" should be type: <object>.',{code:"INVALID_PARAMETER"});return o(l),l},data:l=>{if(l&&typeof l!="object")throw new c('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return o(l),l},params:l=>{if(l&&typeof l!="object")throw new c('"params" should be type: <object>.',{code:"INVALID_PARAMETER"});return o(l),l},expires:"number",queue:"string"},["clientSecretName","method","url"]),e.realtime&&!e.stream)throw new c('"realtime" requires "stream": true.',{code:"INVALID_PARAMETER"});if(!t)throw new c(`At least one parameter value should include "$CLIENT_SECRET" in ${e.method.toLowerCase()==="post"?'"data"':'"params"'} or "headers".`,{code:"INVALID_PARAMETER"});await this.__connection;let a=!!this.__user,u=()=>T.bind(this)("csr",e,{auth:a,tokenHeaders:{accessToken:!!a}}).then(l=>{if(l.status==="running"||l.status==="pending"){let g=`[${e.method.toUpperCase()}]${e.url.toLowerCase()}`,f=e.service||this.service,d=e.owner||this.owner,p=`${g}#${f}:${l.id}`;Object.assign(l,{poll:m=>os.call(this,{id:p,auth:a,service:f,owner:d,latency:m?.latency||1e3,queue:e?.queue,onResponse:r,onError:n,onStream:m?.onStream||i,realtimeGroup:l?.realtime_group})});}return r?r(l):l}).catch(l=>{if(n)return n(l);throw l});if(e?.queue){let l="base:"+e.queue;return he?.[l]||(he[l]=new Wi({breakWhenError:false,batchSize:1})),new Promise((g,f)=>{he[l].add([async()=>{try{let d=await u();if(s>0){let p=d.poll({latency:s});return g(p),p}return g(d),d}catch(d){throw f(d),d}}]);})}else return u()}async function us(e,t){await this.__connection;let r=e.service||this.service,n=e.owner||this.owner;e=h.Params(e,{url:"string",method:["GET","POST","DELETE","PUT"],queue:"string",status:["pending","running","resolved","failed"],compact:"boolean",queue_exact:"boolean",queue_exclude:"string"},["url","method"]);let i=!!this.__user,s=`[${e.method.toUpperCase()}]${e.url.toLowerCase()}#${r}:`,o={id:s,queue:e?.queue,status:e?.status,service:r,owner:n};e?.compact&&(o.compact=true),e?.queue_exact&&(o.queue_exact=true),e?.queue_exclude&&(o.queue_exclude=e.queue_exclude),Object.keys(o).forEach(u=>{o[u]||delete o[u];}),o.queue&&(o.id_prefix=o.id,delete o.id);let a=await T.bind(this)("csr-poll",o,{auth:i,fetchOptions:t});return a.list=a.list.map(u=>{let l={id:u.id,status_code:u.rslv?.status_code||null,response_body:u.rslv?.body||u.rslv?.truncated||null,error:u?.err,created:u?.stmp,updated:u?.utmp,executed:typeof u?.att=="number"?u.att*1e3:void 0,request_body:u?.reqbdy,expires:u?.expt,status:u.stts,queue_name:u?.qid,request_text:u?.reqtxt,response_text:u?.rslvtxt,response_complete_marker:u?.rslvmk!=null?!!u.rslvmk:void 0,compact:u?.cmpct?true:void 0};for(let g in l)l[g]===void 0&&delete l[g];return (l.status==="running"||l.status==="pending")&&(l.poll=g=>os.call(this,{id:s+l.id,auth:i,service:r,owner:n,latency:g?.latency||1e3,queue:u?.qid,seedExecuted:l.executed,onResponse:g?.onResponse,onError:g?.onError,onStream:g?.onStream})),l}),a}async function ds(e){await this.__connection,e=h.Params(e,{url:"string",method:["GET","POST","DELETE","PUT"],id:"string",queue:"string"},["url","method","id"]);let t=e?.service||this.service,r=e?.owner||this.owner,n=!!this.__user,i=`[${e.method.toUpperCase()}]${e.url.toLowerCase()}#${t}`,s=e.id,o=`${i}:${s}`,a=e?.queue;return a&&he?.[a]&&(he[a].remove(st[o]),delete st[o]),T.bind(this)("csr-cancel",{id:o,service:t,owner:r},{auth:n})}function fs(e,t){let r=typeof t?.poll=="number"?t.poll:1e3;if(!Number.isFinite(r)||r<0)throw new c('"poll" should be a non-negative number.',{code:"INVALID_PARAMETER"});if(!e||typeof e!="string")throw new c('"requestId" should be type: <string>.',{code:"INVALID_PARAMETER"});if(t?.since!==void 0&&typeof t.since!="number")throw new c('"since" should be a number.',{code:"INVALID_PARAMETER"});if(t?.realtimeGroup!==void 0&&t.realtimeGroup!==null&&typeof t.realtimeGroup!="string")throw new c('"realtimeGroup" should be type: <string>.',{code:"INVALID_PARAMETER"});let n=typeof t?.since=="number"&&t.since>0?t.since:0,i=t?.onStream,s=t?.onResponse,o=t?.onError,a={stopped:false,fullId:e,resolve:null},u=null,l={stop:null,aborted:false},g=()=>{te[a.fullId]===l&&delete te[a.fullId];},f=()=>{a.stopped||(a.stopped=true,u&&u(),g(),a.resolve&&a.resolve(ot(a.fullId)));};l.stop=f;let d=new Promise(async(p,m)=>{a.resolve=p;try{await this.__connection;let y=!!this.__user,_=t?.service||this.service,w=t?.owner||this.owner;if(a.fullId=ss(e,t?.url,t?.method,_),a.stopped){p(ot(a.fullId));return}te[a.fullId]=l;let b={seq:n},E=0,k=rs.call(this,a.fullId),A=i&&t?.realtimeGroup?ts(b,i,k.onTransport):null,D=A?ns.call(this,t.realtimeGroup,A):null,x=()=>{k.done(A),D&&D.stop(),A&&A.close();};for(u=x;;){let C=await T.bind(this)("csr-poll",{id:a.fullId,service:_,owner:w,since:b.seq},{auth:y});if(a.stopped)return;if(!Na(C)){x(),g(),s&&s(C),p(C);return}let v=A?A.fromPoll(C):Zi(C,b,i);A&&A.open();let U=is(C);if(C.more&&v){E=0;continue}if(E=C.more?E+1:0,!U&&(!C.more||E>=Xi)){x(),g(),s&&s(C),p(C);return}if(await new Promise(L=>setTimeout(L,A&&A.warm()?Math.max(r,es):r)),a.stopped)return}}catch(y){if(a.stopped)return;u&&u(),g(),o&&o(y),m(y);}});return Object.assign(d,{stop:f})}async function gs(e,t,r){await this.__connection;let n=r?.service||this.service,i=r?.owner||this.owner,s=!!this.__user,o=ss(e,r?.url,r?.method,n);return T.bind(this)("csr-finalize",{id:o,data:t,service:n,owner:i},{auth:s})}async function ps(e){await this.__connection;let t={name:"string",email:r=>(h.Email(r),r),subject:"string",message:"string"};return e=h.Params(e,t,["name","email","subject","message"]),await T.bind(this)("send-inquiry",e),"SUCCESS: Inquiry has been sent."}async function hs(e,t){if(await this.__connection,Qi&&e instanceof FormData||zi&&e instanceof HTMLFormElement||Ji&&e instanceof SubmitEvent){if(!t)throw new c("Url string as a second argument is required when form is passed.",{code:"INVALID_PARAMETER"});let n=j(e);e={url:t,data:n.data,sync:true};}let r={url:n=>h.Url(n),data:n=>n,sync:["boolean",()=>true]};if(Array.isArray(e))for(let n of e)n=h.Params(n,r);else e=h.Params(e,r);return T.bind(this)("post-secure",e,{auth:true})}async function ms(e,t){await this.__connection;let{auth:r=false,method:n="POST",bypassAwaitConnection:i=false,responseType:s,contentType:o,tokenHeaders:a,progress:u}=t||{};if(t=Object.assign({auth:r,method:n,bypassAwaitConnection:i,responseType:s,contentType:o,tokenHeaders:a},{fetchOptions:{progress:u}}),typeof e!="object"&&(o==="application/json"||o===void 0))throw new c('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return T.bind(this)("mock",e,t)}async function ys(e,t){if(await this.__connection,!t?.url||typeof t.url!="string")throw new c('"url" is required in the second argument.',{code:"INVALID_PARAMETER"});h.Url(t.url);let n=(await this.admin_endpoint)?.forward_request;if(!n)throw new c("forwardRequest is not available on this service region yet.",{code:"NOT_EXISTS"});let i=null,s=null,o=Ji&&e instanceof SubmitEvent?e.target:zi&&e instanceof HTMLFormElement?e:null;o?i=new FormData(o):Qi&&e instanceof FormData?i=e:e!=null&&(i=JSON.stringify(e),s="application/json");let a={public_identifier:this.__public_identifier,service:this.service,owner:this.owner,forward:{url:t.url,method:t.method||"POST",headers:t.headers||{},apiKeyHeader:t.apiKeyHeader,apiKeyScheme:t.apiKeyScheme}},u=JSON.stringify(a).replace(/[\u007f-\uffff]/g,p=>"\\u"+p.charCodeAt(0).toString(16).padStart(4,"0"));if(u.length>4096)throw new c("Destination url and headers are too large for Content-Meta.",{code:"INVALID_PARAMETER"});let l=this.bearerToken||this.session?.idToken?.jwtToken||null;if(!l)throw new c("User login is required.",{code:"INVALID_REQUEST"});let g={"Content-Meta":u,Authorization:l};s&&(g["Content-Type"]=s);let f=await fetch(n,{method:"POST",headers:g,body:i,signal:t.signal});if(t.responseType==="response")return f;if(!f.ok){let p=await f.text();try{p=JSON.parse(p);}catch{}throw new c(p?.message||(typeof p=="string"?p:JSON.stringify(p)),{code:p?.code||"ERROR"})}if(t.onStream&&f.body){let p=f.body.getReader(),m=new TextDecoder,y="";for(;;){let{done:_,value:w}=await p.read();if(_)break;let b=m.decode(w,{stream:true});y+=b;try{t.onStream(b);}catch(E){console.error(E);}}return y}let d=await f.text();if(t.responseType==="text")return d;try{return JSON.parse(d)}catch{return d}}async function bs(e,t){await this.__connection,e=h.Params(e||{},{access_group:n=>{if(n==="authorized"&&(n=1),n==="public"&&(n=0),typeof n!="number")throw new c('"access_group" should be type number.',{code:"INVALID_PARAMETER"});if(n<0)throw new c('"access_group" should be zero or a positive number.',{code:"INVALID_PARAMETER"});if(n>this.__user.access_group)throw new c("User has no access.",{code:"INVALID_REQUEST"});return n}});let r=await T.bind(this)("get-feed",e,{auth:true,fetchOptions:t});for(let n in r.list)r.list[n]=await Se.bind(this)(r.list[n]);return r}function at(e){if(e===this.__user.user_id)throw new c(`"user_id" cannot be the user's own ID.`,{code:"INVALID_PARAMETER"});return h.UserId(e,'"user_id"')}async function _s(e,t){if(e=j(e,{ignoreEmpty:true}).data,e=h.Params(e,{subscriber:n=>h.UserId(n,'User ID in "subscriber"'),subscription:at.bind(this),blocked:"boolean"}),!e.subscriber&&!e.subscription)throw new c('At least either "subscriber" or "subscription" should have a value.',{code:"INVALID_PARAMETER"});let r=await T.bind(this)("get-subscription",e,Object.assign({auth:true},{fetchOptions:t}));return r.list=r.list.map((n=>{let i={};if(n.sub){let s=n.sub.split("#");i.subscriber=s[2],i.subscription=s[0];}else i.subscriber=n.subscriber,i.subscription=n.subscription;return i.timestamp=n?.timestamp||n.stmp,i.blocked=n?.blocked||n.grp.substring(0,1)==="N",Object.assign(i,n.opt),i})),r}async function ws(e){await this.__connection,e=h.Params(e,{user_id:at.bind(this),get_feed:["boolean",()=>false],get_notified:["boolean",()=>false],get_email:n=>{if(n&&!this.__user.email||!this.__user.email_verified)throw new c("User has no verified email address.",{code:"INVALID_REQUEST"});return !!n}},["user_id"]);let t=await T.bind(this)("subscription",{subscribe:e.user_id,option:{get_feed:e.get_feed,get_notified:e.get_notified,get_email:e.get_email||false}},{auth:true}),r={};if(t.sub){let n=t.sub.split("#");r.subscriber=n[2],r.subscription=n[0];}else r.subscriber=t.subscriber,r.subscription=t.subscription;return r.timestamp=t?.timestamp||t.stmp,r.blocked=t?.blocked||t.grp.substring(0,1)==="N",Object.assign(r,t.opt),r}async function Es(e){await this.__connection;let{user_id:t}=h.Params(e,{user_id:at.bind(this)},["user_id"]);return await T.bind(this)("subscription",{unsubscribe:t},{auth:true})}async function As(e){await this.__connection;let{user_id:t}=h.Params(e,{user_id:at.bind(this)},["user_id"]);return await T.bind(this)("subscription",{block:t},{auth:true})}async function Rs(e){await this.__connection;let{user_id:t}=h.Params(e,{user_id:at.bind(this)},["user_id"]);return await T.bind(this)("subscription",{unblock:t},{auth:true})}async function Is(e,t){await this.__connection;let r=await W.bind(this)();e=h.Params(e||{},{user_id:o=>{if(o!==this.__user.user_id&&!r)throw new c("No access.",{code:"INVALID_REQUEST"});return o},group:o=>h.newsletterGroup(o,{allowNull:true})});let n=await T.bind(this)("get-newsletter-subscription",e,{auth:true,fetchOptions:t||null}),i=n?.list||n,s=[];Array.isArray(i)||(i=[]);for(let o of i){let a=o.subt.split("#"),u=true;a[0].charAt(0)==="@"&&(u=false,a[0]=a[0].substring(1));let l=/^\d+$/.test(a[0])?parseInt(a[0]):a[0];s.push({timestamp:o.stmp,group:l,subscribed_email:a[1],active:u});}return n?.list?(n.list=s,n):s}async function Ts(e){await this.__connection;let t=h.Params(e||{},{email:r=>Array.isArray(r)&&r.length>0?r.length===1?h.Email(r[0]):r.map(n=>h.Email(n)):h.Email(r),group:r=>h.newsletterGroup(r),redirect:r=>h.Url(r)},this.__user?["group"]:["email","group"]);return T.bind(this)(`subscribe-${this.__user?"":"public-"}newsletter`,t,{auth:!!this.__user})}async function Ps(e){await this.__connection;let t=h.Params(e||{},{group:r=>h.newsletterGroup(r,{nameOnly:true}),restriction:r=>{if(typeof r!="number"||!Number.isInteger(r)||r<0||r>99)throw new c('"restriction" should be a number between 0 and 99.',{code:"INVALID_PARAMETER"});return r},name:r=>{if(typeof r!="string"||r.length>60)throw new c('"name" should be a string of 60 characters or less.',{code:"INVALID_PARAMETER"});return r}},["group"]);return T.bind(this)("register-newsletter-group",t,{auth:true})}async function Ss(e){await this.__connection;let t=h.Params(e||{},{group:r=>h.newsletterGroup(r,{nameOnly:true})},["group"]);return T.bind(this)("delete-newsletter-group",t,{auth:true})}async function ks(){return await this.__connection,T.bind(this)("newsletter-group-endpoint",null,{auth:true})}async function vs(e){await this.__connection,e=h.Params(e,{group:r=>h.newsletterGroup(r,{allowNull:true})},["group"]);let t=Object.assign({action:"unsubscribe"},e);return T.bind(this)("subscribe-newsletter",t,{auth:true})}async function Ns(e,t){let r=await W.bind(this)(),n={message_id:"string",timestamp:"number",read:"number",complaint:"number",subject:"string",bounced:"number"};e||(t=Object.assign({ascending:false},t||{})),e=j(e).data,e=e||{searchFor:"timestamp",value:Date.now(),condition:"<",group:"public"},e=h.Params(e,{searchFor:["message_id","timestamp","subject","complaint","read","bounced"],value:u=>{if(typeof u!==n[e.searchFor])throw new c(`"value" type does not match the type of "${e.searchFor}" index.`,{code:"INVALID_PARAMETER"});if(typeof u=="string"&&!u)throw new c('"value" should not be empty string.',{code:"INVALID_PARAMETER"});return u},range:u=>{if(!e.hasOwnProperty("value")||typeof u!=typeof e.value)throw new c('"range" should match type of "value".',{code:"INVALID_PARAMETER"});return u},condition:[">",">=","=","<","<=","gt","gte","eq","lt","lte",()=>"="],group:u=>{let l=h.newsletterGroup(u);if(l===0)return 0;if(typeof l=="string")return l;if(!this.session)throw new c("User should be logged in.",{code:"INVALID_REQUEST"});if(u==="authorized")return 1;if(!r&&l>parseInt(this.user?.access_group||this.session?.idToken?.payload?.access_group))throw new c("User has no access.",{code:"INVALID_REQUEST"});return l}},["searchFor","value","group"]);let i=e.group===0||typeof e.group=="string"&&!this.__user?"get-public-newsletters":"get-newsletters",s=await T.bind(this)(i,e,Object.assign({method:"get",auth:i==="get-public-newsletters"?!!this.__user:true},{fetchOptions:t})),o={message_id:"mid",timestamp:"stmp",complaint:"cmpl",read:"read",subject:"subj",bounced:"bnce",url:"url",delivered:"delv",group:"grp"},a={message_id:"",timestamp:0,complaint:0,read:0,subject:"",bounced:"",url:"",delivered:0,group:e.group};return s.list=s.list.map(u=>{let l={};for(let g in o)l[g]=u[o[g]]||a[g];return l.bounced=String(l.bounced),l}),s}async function Us(e){let t=h.Params(e,{user_id:n=>h.UserId(n,'"user_id"')},["user_id"]);if(t?.service&&t?.owner?t={service:t?.service,owner:t?.owner,block:t.user_id}:t={block:t.user_id},!await W.bind(this)()){if(!this.__user)throw new c("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new c("Invalid access.",{code:"INVALID_REQUEST"})}return await T.bind(this)("block-account",t,{auth:true})}async function xs(e){let t=h.Params(e,{user_id:n=>h.UserId(n,'"user_id"')},["user_id"]);if(t?.service&&t?.owner?t={service:t?.service,owner:t?.owner,unblock:t.user_id}:t={unblock:t.user_id},!await W.bind(this)()){if(!this.__user)throw new c("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new c("Invalid access.",{code:"INVALID_REQUEST"})}return await T.bind(this)("block-account",t,{auth:true})}async function Ds(e){let t=h.Params(e,{user_id:n=>h.UserId(n,'"user_id"')},["user_id"]);if(t?.service&&t?.owner?t={service:t?.service,owner:t?.owner,delete:t.user_id}:t={delete:t.user_id},!await W.bind(this)()){if(!this.__user)throw new c("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new c("Invalid access.",{code:"INVALID_REQUEST"})}return await T.bind(this)("remove-account",t,{auth:true})}async function Cs(e,t){let r={email:s=>h.Email(s),password:s=>h.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=>h.Birthdate(s),phone_number:s=>h.PhoneNumber(s),picture:s=>{if(s)return h.Url(s)},profile:s=>{if(s)return h.Url(s)},website:s=>{if(s)return h.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 c('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof s!="number"||s<1||s>100)throw new c('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"});return s}},n=h.Params(e,r,["email"]);if(t=h.Params(t,{confirmation_url:s=>{let o=s;if(typeof s=="string")o=h.Url(s);else throw new c('"options.confirmation_url" should be type: <string>.',{code:"INVALID_PARAMETER"});if(o&&!n.email)throw new c('"email" is required for signup confirmation.',{code:"INVALID_PARAMETER"});return o},email_subscription:s=>{if(typeof s!="boolean")throw new c('"options.email_subscription" should be type: <boolean>.',{code:"INVALID_PARAMETER"});if(!t?.confirmation_url)throw new c('"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 c('"options.template" should be type: <object> with "url" and "subject".',{code:"INVALID_PARAMETER"});return {url:h.Url(s.url),subject:s.subject}}}),n.signup_confirmation=t?.confirmation_url||true,n.email_subscription=t?.email_subscription||false,n.template=t?.template||{},!await W.bind(this)()){if(!this.__user)throw new c("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new c("Invalid access.",{code:"INVALID_REQUEST"})}return await T.bind(this)("admin-signup",n,{auth:true})}async function Ls(e){let t={email:s=>h.Email(s),password:s=>h.Password(s),openid_id:"string",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=>h.Birthdate(s),phone_number:s=>h.PhoneNumber(s),picture:s=>s?h.Url(s):"",profile:s=>s?h.Url(s):"",website:s=>s?h.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],access_group:s=>{try{typeof s=="string"&&(s=parseInt(s));}catch{throw new c('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof s!="number"||s<1||s>100)throw new c('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"});return s}},r=["email","password"],n=h.Params(e,t,r);if(!await W.bind(this)()){if(!this.__user)throw new c("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new c("Invalid access.",{code:"INVALID_REQUEST"})}return await T.bind(this)("admin-signup",n,{auth:true})}async function Os(e){if(e=h.Params(e,{user_id:r=>h.UserId(r,'"user_id"'),access_group:r=>{try{typeof r=="string"&&(r=parseInt(r));}catch{throw new c('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof r=="number"&&r>0&&r<100)return r;throw new c('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"})}},["user_id","access_group"]),!await W.bind(this)()){if(!this.__user)throw new c("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new c("Invalid access.",{code:"INVALID_REQUEST"})}return await T.bind(this)("grant-access",e,{auth:true})}async function Ms(e,t){if(e=h.Params(e,{email:"string"}),!await W.bind(this)()){if(!this.__user)throw new c("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new c("Invalid access.",{code:"INVALID_REQUEST"})}let n=await T.bind(this)("invitation-list",Object.assign({mode:"search"},e),{fetchOptions:t,auth:true});return n.list=n.list.map(i=>$e(i.user)),n}async function Fs(e){if(e=h.Params(e,{email:r=>h.Email(r)},["email"]),!await W.bind(this)()){if(!this.__user)throw new c("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new c("Invalid access.",{code:"INVALID_REQUEST"})}return await T.bind(this)("invitation-list",Object.assign({mode:"cancel"},e),{auth:true})}async function qs(e){if(e=h.Params(e,{email:r=>h.Email(r)},["email"]),!await W.bind(this)()){if(!this.__user)throw new c("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new c("Invalid access.",{code:"INVALID_REQUEST"})}return await T.bind(this)("invitation-list",Object.assign({mode:"resend"},e),{auth:true})}async function Vs(e){let t=h.Params(e,{user_id:o=>h.UserId(o,'"user_id"'),email:o=>h.Email(o),address:o=>{if(!o)return "";if(typeof o=="string")return o;if(typeof o=="object")return JSON.stringify(o)},name:"string",gender:"string",birthdate:o=>o?h.Birthdate(o):"",phone_number:o=>o?h.PhoneNumber(o):"",email_public:"boolean",phone_number_public:"boolean",address_public:"boolean",gender_public:"boolean",birthdate_public:"boolean",misc:"string",picture:o=>o?h.Url(o):"",profile:o=>o?h.Url(o):"",nickname:"string",website:o=>o?h.Url(o):""},["user_id"]),r=t.service,n=t.owner;if(delete t.service,delete t.owner,Object.keys(t).filter(o=>o!=="user_id"&&t[o]!==void 0).length===0)throw new c("At least one attribute to update is required.",{code:"INVALID_PARAMETER"});if(!await W.bind(this)()){if(!this.__user)throw new c("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new c("Invalid access.",{code:"INVALID_REQUEST"})}t.email&&(t.preferred_username=(r||this.service)+"-"+G.hash(t.email));let s={attributes:t};return r&&n&&(s.service=r,s.owner=n),await T.bind(this)("admin-edit-profile",s,{auth:true})}async function $s(e){if(typeof window>"u"||window._runningInNodeJS)throw new c("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.__connection,!e.endpoint)throw new c("Missing parameter: endpoint",{code:"INVALID_PARAMETER"});if(!e.keys||!e.keys.p256dh||!e.keys.auth)throw new c("Missing parameter: keys.p256dh or keys.auth",{code:"INVALID_PARAMETER"});return await T.bind(this)("store-subscription",{endpoint:e.endpoint,keys:e.keys},{auth:true}),"SUCCESS: Subscribed to receive notifications."}async function js(e){if(typeof window>"u"||window._runningInNodeJS)throw new c("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.__connection,!e.endpoint)throw new c("Missing parameter: endpoint",{code:"INVALID_PARAMETER"});if(!e.keys||!e.keys.p256dh||!e.keys.auth)throw new c("Missing parameter: keys.p256dh or keys.auth",{code:"INVALID_PARAMETER"});return await T.bind(this)("delete-subscription",{endpoint:e.endpoint,keys:e.keys},{auth:true}),"SUCCESS: Unsubscribed from notifications."}async function Bs(){if(typeof window>"u"||window._runningInNodeJS)throw new c("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});return await this.__connection,{VAPIDPublicKey:await T.bind(this)("get-vapid-public-key",null,{auth:true})}}async function Ks(e,t){if(typeof window>"u"||window._runningInNodeJS)throw new c("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});await this.__connection;let{title:r,body:n}=j(e||{},{nullIfEmpty:true}).data;if(!r)throw new c("Missing parameter: message title",{code:"INVALID_PARAMETER"});if(!n)throw new c("Missing parameter: message body",{code:"INVALID_PARAMETER"});let i={title:r,body:n};return t?(typeof t=="string"&&(t=[t]),i.user_ids=t):i.user_ids="all_users",await T.bind(this)("push-notification",i,{auth:true}),"SUCCESS: Notification sent."}async function Hs(e){await this.__connection,e=h.Params(e,{spell:"string",name:"string",magic:r=>r},["spell","name"]);await T.bind(this)("castspell",e);return `The spell "${e.spell}" has been cast.`}async function Gs(e){return await this.__connection,e=h.Params(e||{},{search:["spell","name",()=>"spell"],value:"string"}),await T.bind(this)("getspell",e)}async function Ws(e){await this.__connection,e=h.Params(e,{message:"string",name:"string"},["message","name"]);let t=await T.bind(this)("dopamine",e,{auth:true}),r=t?.previous_message?.message,n=t?.previous_message?.name;if(Y())r&&n&&window.alert(`${n} said: ${r}`),window.location.href=t.video;else return r&&n?`${n} said: ${r}
|
|
215
|
+
`,u=new Blob([d],{type:"application/javascript"});Re=new Worker(URL.createObjectURL(u)),Re.onmessage=g=>{a.readyState===1&&a.send(JSON.stringify({action:"keepAlive"}));},i(a);},a.onmessage=async d=>{let u="";try{u=JSON.parse(decodeURI(d.data)),this.log("socket onmessage",u);}catch{return}let g;switch(!0){case !!u?.["#message"]:g="message";break;case !!u?.["#private"]:g="private";break;case !!u?.["#notice"]:g="notice";break;case !!u?.["#rtc"]:g="rtc";break;case !!u?.["#error"]:g="error";break}if(!g)return;let f={type:g,message:u?.["#rtc"]||u?.["#message"]||u?.["#private"]||u?.["#notice"]||u?.["#error"]||null,sender:u?.["#user_id"]||null,sender_cid:u?.["#scid"]?"cid:"+u["#scid"]:null,sender_rid:u?.["#srid"]||null,code:u?.["#code"]||null};if(g==="notice")e(f);else if(g==="rtc"){if(f.sender!==this.user.user_id){let c=f.message;if(c.hungup){ce[f.sender_cid]&&(ce[f.sender_cid](!1),delete ce[f.sender_cid]),pe[f.sender_cid]&&delete pe[f.sender_cid],D?.[f.sender_cid]&&ue.bind(this)({cid:f.sender_cid}),f.type="rtc:closed",e(f);return}if(c.candidate&&Dr.bind(this)(c.candidate,f.sender_cid),c.sdpoffer&&(Nr.bind(this)(c.sdpoffer,f.sender_cid),pe[f.sender_cid]||(pe[f.sender_cid]=f.sender_cid,delete f.message,f.connectRTC=Zi.bind(this)(f),f.type="rtc:incoming",f.hangup=(()=>{D[f.sender_cid]?ue.bind(this)({cid:f.sender_cid}):pe[f.sender_cid]&&(delete pe[f.sender_cid],a.send(JSON.stringify({action:"rtc",uid:f.sender_cid,content:{hungup:this.user.user_id},token:this.session.accessToken.jwtToken})));}).bind(this),e(f))),c.pickup&&ce[f.sender_cid]&&(ce[f.sender_cid](!0),delete ce[f.sender_cid]),c.sdpanswer&&D[f.sender_cid])if(D[f.sender_cid].signalingState==="have-local-offer")await D[f.sender_cid].setRemoteDescription(new RTCSessionDescription(c.sdpanswer));else throw new l("Invalid signaling state.",{code:"INVALID_REQUEST"})}}else e(f);},a.onclose=()=>{st?(this.log("realtime onclose","WebSocket connection closed."),e({type:"close",message:"WebSocket connection closed."})):(this.log("realtime onclose","WebSocket unexpected close."),e({type:"error",message:"Skapi: WebSocket unexpected close."}),Me++,Me<3?(this.log("realtime onclose","Reconnecting to WebSocket server..."+Me),e({type:"reconnect",message:"Reconnecting to WebSocket server..."+Me}),qe.bind(this)(e,3e3,"reconnect")):(this.log("realtime onclose","Max reconnection attempts reached."),e({type:"error",message:"Skapi: Max reconnection attempts reached."})));},a.onerror=()=>{this.log("realtime onerror","WebSocket connection error."),e({type:"error",message:"Skapi: WebSocket connection error."});};}catch(a){o(a);}},t);}),n.value=this.__socket,this.__socket}async function ns(e,t,r){if(typeof window>"u"||window._runningInNodeJS)throw new l("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});let n=this.__socket?await this.__socket:this.__socket;if(!n)throw new l("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});if(!t)throw new l("No recipient.",{code:"INVALID_REQUEST"});await Ce.bind(this)(),e=j(e).data;let i="";if(r&&(r=y.Params(r,{config:{always:"boolean"},title:"string",body:"string"},["title","body"]),i=JSON.stringify({title:r.title,body:r.body}),new Blob([i]).size>3072))throw new l("Notification size exceeds 3kb.",{code:"INVALID_PARAMETER"});if(n.readyState===1){try{y.UserId(t),n.send(JSON.stringify({action:"sendMessage",uid:t,content:e,notification:i,notificationConfig:r?.config||{},token:`IdT:${this.service}:${this.owner}:`+(this.bearerToken||this.session?.idToken?.jwtToken||"null")}));}catch(s){if(this.log("postRealtime:err",{err:s}),we!==t)throw new l(`User has not joined to the recipient group. Run joinRealtime({ group: "${t}" })`,{code:"INVALID_REQUEST"});n.send(JSON.stringify({action:"broadcast",rid:t,content:e,notification:i,notificationConfig:r?.config||{},token:`IdT:${this.service}:${this.owner}:`+(this.bearerToken||this.session?.idToken?.jwtToken||"null")}));}return {type:"success",message:"Message sent."}}throw new l("Realtime connection is not open. Try reconnecting with connectRealtime().",{code:"INVALID_REQUEST"})}async function Ve(e){if(typeof window>"u"||window._runningInNodeJS)throw new l("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});let t=this.__socket?await this.__socket:this.__socket;if(!t)throw new l("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});await Ce.bind(this)(),e=j(e,{nullIfEmpty:true}).data;let{group:r=null}=e;if(!r&&!we)return {type:"success",message:"Left realtime message group."};if(r!==null&&typeof r!="string")throw new l('"group" must be a string | null.',{code:"INVALID_PARAMETER"});return t.readyState===1&&t.send(JSON.stringify({action:"joinRoom",rid:r,token:this.session.accessToken.jwtToken})),we=r,{type:"success",message:r?`Joined realtime message group: "${r}".`:"Left realtime message group."}}async function is(e,t){e=y.Params(e,{user_id:n=>y.UserId(n,'User ID in "user_id"'),group:["string",()=>{if(!we)throw new l('No group has been joined. Otherwise "group" is required.',{code:"INVALID_REQUEST"});return we}]});let r=await k.bind(this)("get-ws-group",e,{fetchOptions:t,auth:true,method:"post"});return r.list=r.list.map(n=>({user_id:n.uid.split("#")[1],cid:"cid:"+n.cid})),r}async function ss(e,t){if(await this.__connection,e||(e={searchFor:"group",value:" ",condition:">"}),e=y.Params(e,{searchFor:["group","number_of_users",()=>"group"],value:["string","number",()=>e?.searchFor&&e?.searchFor==="number_of_users"?0:" "],condition:[">",">=","=","<","<=","!=","gt","gte","eq","lt","lte","ne"],range:["string","number"]}),e.condition||(e.value===" "||!e.value?e.condition=">":e.condition="="),e.range&&e.condition&&delete e.condition,e.searchFor==="number_of_users"&&typeof e.value!="number")throw new l('"value" must be a number.',{code:"INVALID_PARAMETER"});if(e.searchFor==="group"&&typeof e.value!="string")throw new l('"value" must be a string.',{code:"INVALID_PARAMETER"});if(e.hasOwnProperty("range")&&typeof e.range!=typeof e.value)throw new l(`"range" must be a ${typeof e.value}.`,{code:"INVALID_PARAMETER"});let r=await k.bind(this)("get-ws-group",e,{fetchOptions:t,auth:true,method:"post"});return r.list=r.list.map(n=>({group:n.rid.split("#")[1],number_of_users:n.cnt})),r}var Ha=typeof FormData<"u",ls=typeof HTMLFormElement<"u",cs=typeof SubmitEvent<"u",he={},ot={},te={};function at(e){return Object.freeze({id:e,status:"stopped"})}function Cr(e){return !!e&&typeof e=="object"&&e.status==="stopped"}var us=3;function ds(e,t,r){let n=false,i=Array.isArray(e?.chunks)?e.chunks.slice():[];i.sort((s,o)=>(s?.seq||0)-(o?.seq||0));for(let s of i)if(!(!s||typeof s.seq!="number"||s.seq<=t.seq)&&(t.seq=s.seq,n=true,r&&typeof s.txt=="string"&&s.txt!==""))try{r(s.txt,s.seq,"poll");}catch(o){console.error(o);}return typeof e?.last_seq=="number"&&e.last_seq>t.seq&&(t.seq=e.last_seq,n=true),n}var Ga=2e3,fs=5e3,Wa=2e3,Qa=5,za=1500,Lt=null;function gs(e,t,r){let n=new Map,i=false,s=false,o=0,a={socket:0,poll:0},d=(c,p,h)=>{if(e.seq=c,!(!t||typeof p!="string"||p===""))try{t(p,c,h);}catch(m){console.error(m);}},u=()=>{for(let c of Array.from(n.keys()))c<=e.seq&&n.delete(c);for(;;){let c=e.seq+1;if(!n.has(c))break;let p=n.get(c);n.delete(c),d(c,p.txt,p.via);}};return {cursor:e,open:()=>{i||s||(i=true,u());},fromPoll:c=>{if(s)return false;let p=e.seq,h=e.seq,m=Array.isArray(c?.chunks)?c.chunks:[];for(let b of m){if(!b||typeof b.seq!="number"||b.seq<=e.seq)continue;let _=!n.has(b.seq);_&&(a.poll++,r&&a.poll===1&&r("poll",b.seq)),n.set(b.seq,{txt:typeof b.txt=="string"?b.txt:"",via:_?"poll":n.get(b.seq).via}),b.seq>h&&(h=b.seq);}typeof c?.last_seq=="number"&&c.last_seq>h&&(h=c.last_seq);let w=Array.from(n.keys()).sort((b,_)=>b-_);for(let b of w){if(b<=e.seq){n.delete(b);continue}if(b>h)break;let _=n.get(b);n.delete(b),d(b,_.txt,_.via);}return h>e.seq&&(e.seq=h),u(),e.seq>p},fromSocket:(c,p)=>{s||typeof c!="number"||!Number.isFinite(c)||(o=Date.now(),!(c<=e.seq)&&(!n.has(c)&&n.size>=Wa||(n.has(c)||(a.socket++,r&&a.socket===1&&r("socket",c)),n.set(c,{txt:typeof p=="string"?p:"",via:n.has(c)?n.get(c).via:"socket"}),i&&u())));},warm:()=>o!==0&&Date.now()-o<Ga,stats:()=>({socket:a.socket,poll:a.poll}),close:()=>{s=true,n.clear();}}}function ps(e){if(!this||!this.__network_logs)return {onTransport:void 0,done:()=>{}};let t=Date.now(),r=false;return {onTransport:(n,i)=>{console.log(`%cSKAPI: stream chunk arrived over ${n==="socket"?"WEBSOCKET":"POLL"}`,`color: ${n==="socket"?"green":"orange"};`,{id:e,first_seq:i,after_ms:Date.now()-t});},done:n=>{if(r||!n)return;r=true;let i=n.stats();console.log("%cSKAPI: stream transport","color: blue;",{id:e,over_websocket:i.socket,over_poll:i.poll,took_ms:Date.now()-t});}}}function hs(e,t){let r={stop:()=>{}};if(typeof window>"u"||window._runningInNodeJS||Lt)return r;let n={stopped:false,socket:null,opened:null,joined:false,attempts:0,unavailable:false};Lt=n;let i=u=>{if(n.stopped)return;let g=u?.data;if(typeof g!="string")return;let f=null;try{f=JSON.parse(g);}catch{try{f=JSON.parse(decodeURI(g));}catch{return}}let c=f?.["#message"];if(c==null)return;if(typeof c=="string")try{c=JSON.parse(c);}catch{return}if(typeof c!="object")return;let p=f?.["#srid"];if(typeof p=="string"&&p!==e)return;let h=c.seq;typeof h=="string"&&h!==""&&(h=Number(h)),t.fromSocket(h,c.txt);},s=()=>{if(n.socket){try{n.socket.removeEventListener("message",i);}catch{}try{n.socket.removeEventListener("close",a);}catch{}n.socket=null;}},o=async()=>{let u=n.opened,g=n.joined;if(n.opened=null,n.joined=false,s(),!(!g&&!u))try{let f=this.__socket?await this.__socket:null;if(u&&f===u){await Ot.bind(this)();return}g&&f&&rs()===room&&await Ve.bind(this)({group:null});}catch{}},a=()=>{n.stopped||(s(),!n.unavailable&&(n.attempts>=Qa||(n.attempts+=1,setTimeout(()=>{n.stopped||d();},za))));},d=async()=>{try{let u=this.__socket?await this.__socket:null;if(n.stopped){o();return}if(!u){if(!this.session){n.unavailable=!0,o();return}if(await qe.bind(this)(()=>{},0),u=this.__socket?await this.__socket:null,n.stopped){o();return}u&&!n.opened&&(n.opened=u);}if(!u||u.readyState!==1)return;if(u.addEventListener("message",i),u.addEventListener("close",a),n.socket=u,!n.joined&&(await Ve.bind(this)({group:e}),n.joined=!0,n.stopped)){o();return}}catch{}};return d(),{stop:()=>{n.stopped||(n.stopped=true,Lt===n&&(Lt=null),o());}}}function ms(e){return e?.status==="running"||e?.status==="pending"}function ys(e){return !!e&&typeof e=="object"&&!Array.isArray(e)&&typeof e.status=="string"&&typeof e.id=="string"&&"in_queue"in e}function bs(e,t,r,n){if(!e||typeof e!="string")throw new l('"requestId" should be type: <string>.',{code:"INVALID_PARAMETER"});if(e.includes("#"))return e;if(!t||typeof t!="string"||!r||typeof r!="string")throw new l('"url" and "method" are required to address a request by its short id.',{code:"INVALID_PARAMETER"});return y.Url(t),`[${r.toUpperCase()}]${t.toLowerCase()}#${n}:${e}`}function _s({id:e,auth:t,service:r,owner:n,latency:i=1e3,queue:s,seedExecuted:o,onResponse:a,onError:d,onStream:u,realtimeGroup:g}){if(typeof i!="number")throw new l('"latency" should be a number.',{code:"INVALID_PARAMETER"});if(i<0)throw new l('"latency" should be a non-negative number.',{code:"INVALID_PARAMETER"});s&&!he?.[s]&&(he[s]=new as({breakWhenError:false,batchSize:1}));let f={stop:null,aborted:false,queue:s};te[e]=f;let c=null,p=()=>{te[e]===f&&delete te[e];},h=()=>new Promise((w,b)=>{let _=false;if(f.aborted){p(),w(at(e));return}let E={seq:0},S=ps.call(this,e),A=u&&g?gs(E,u,S.onTransport):null,N=A?hs.call(this,g,A):null,x=()=>{S.done(A),N&&N.stop(),A&&A.close();};c=x;let C=0,v=false,U=0,O=typeof o=="number"&&o>0?o:void 0,V=async()=>{if(!(_||v)&&!(A&&A.warm()&&Date.now()-C<fs)){v=true;try{for(;;){let ie={id:e,service:r,owner:n};u&&(ie.since=E.seq),C=Date.now();let F=await k.bind(this)("csr-poll",ie,{auth:t});if(_)return;let z=A?A.fromPoll(F):u?ds(F,E,u):!1;A&&A.open();let ct=ms(F);if(typeof F?.executed=="number"&&F.executed>0&&(O=F.executed),F?.more&&z){U=0;continue}if(ct){U=0;return}if(U=F?.more?U+1:0,F?.more&&U<us)return;_=!0,a&&a(F,O!==void 0?{executed:O}:void 0),clearInterval(de),x(),p(),w(F);return}}catch(ie){if(_)return;_=true,d&&d(ie),clearInterval(de),x(),p(),b(ie);}finally{v=false;}}},de=setInterval(V,i);A&&V(),f.stop=()=>{_||(_=true,clearInterval(de),x(),p(),w(at(e)));};}),m=()=>{let w=te[e];w&&(w.stop?w.stop():(w.aborted=true,delete te[e]));};if(s){let w=new Promise((b,_)=>{let E=false,S=he[s].add([async()=>{try{let A=await h();return E||(E=!0,b(A)),A}catch(A){throw E||(E=true,_(A)),A}}])[0];ot[e]=S,f.stop=()=>{if(!E){f.aborted=true,c&&c();try{he[s]&&he[s].remove(ot[e]);}catch{}delete ot[e],p(),E=true,b(at(e));}};});return Object.assign(w,{stop:m})}else return Object.assign(h(),{stop:m})}function Mt(e){let t=0,r=[];if(e?.id){if(e.url&&e.method){let n=e.service||this.service;r.push(`[${e.method.toUpperCase()}]${e.url.toLowerCase()}#${n}:${e.id}`);}r.push(e.id);}else if(e?.queue)for(let n in te)te[n]?.queue===e.queue&&r.push(n);else for(let n in te)r.push(n);for(let n of r){let i=te[n];i&&(i.stop?i.stop():(i.aborted=true,delete te[n]),t+=1);}return t}function Or(e,t){if(!e.queue)throw new l('"queue" is required.',{code:"INVALID_PARAMETER"});let r={service:e.service||this.service,owner:e.owner||this.owner,queue:e.queue+":"};return k.bind(this)("csr-poll",r,{auth:true})}function Ja(e){if(typeof Buffer<"u"&&typeof Buffer.from=="function")return Buffer.from(e).toString("base64");if(typeof btoa=="function"){let t="";for(let n=0;n<e.length;n+=32768)t+=String.fromCharCode.apply(null,Array.from(e.subarray(n,n+32768)));return btoa(t)}throw new l("No base64 encoder available in this environment.",{code:"NOT_SUPPORTED"})}var os=2*1024*1024-64*1024;function Ft(e){return typeof File<"u"&&e instanceof File||typeof Blob<"u"&&e instanceof Blob}function Ur(e){if(Array.isArray(e)){let t=[];for(let r of e)Ft(r)||t.push(Ur(r));return t}if(e&&typeof e=="object"&&!Ft(e)){let t=Object.getPrototypeOf(e);if(t!==Object.prototype&&t!==null)return e;let r={};for(let n in e)Ft(e[n])||(r[n]=Ur(e[n]));return r}return e}function Ya(e){if(e==null)return null;let t=j(e)?.data;return !t||typeof t!="object"||Array.isArray(t)?null:Ur(t)}function ws(e,t,r){if(r!==void 0){if(Array.isArray(r)){for(let n of r)ws(e,t,n);return}if(Ft(r)){e.append(t,r);return}if(r===null){e.append(t,"");return}if(typeof r=="object"){e.append(t,JSON.stringify(r));return}e.append(t,String(r));}}async function Xa(e){if(e==null)throw new l('"multipart": true needs a form body in the first argument.',{code:"INVALID_PARAMETER"});if(typeof FormData>"u"||typeof Response>"u")throw new l('"multipart": true is not available in this environment.',{code:"NOT_SUPPORTED"});let t;if(cs&&e instanceof SubmitEvent)t=new FormData(e.target);else if(ls&&e instanceof HTMLFormElement)t=new FormData(e);else if(e instanceof FormData)t=e;else if(typeof e=="object"&&!Array.isArray(e)){t=new FormData;for(let s in e)ws(t,s,e[s]);}else throw new l('"form" should be a submit event, a form element, FormData, or an object.',{code:"INVALID_PARAMETER"});let r=new Response(t),n=r.headers.get("content-type"),i=Ja(new Uint8Array(await r.arrayBuffer()));if(i.length>os)throw new l(`Multipart body is too large: ${i.length} bytes once base64 encoded, and the limit is ${os}. Upload the file first and send its url instead.`,{code:"INVALID_PARAMETER"});return {body_b64:i,body_content_type:n}}function Za(e){if(e!=null){if(typeof e=="boolean")return e;if(typeof e=="object"&&!Array.isArray(e))return {user:!!e.user,service:!!e.service};throw new l('"skapiHeaders" should be type: <boolean> or { user?: boolean; service?: boolean }.',{code:"INVALID_PARAMETER"})}}function el(e){if(!(!e||typeof e!="object")){for(let t in e)if(typeof t=="string"&&t.toLowerCase().indexOf("x-skapi-")===0)throw new l(`"headers" cannot set "${t}": the "x-skapi-" prefix is reserved. Use "skapiHeaders" to tell the destination who the caller is.`,{code:"INVALID_PARAMETER"})}}async function Es(e,t){let r=false,n=!!(e?.secretName||e?.clientSecretName),i=t?.signal;if(i?.aborted)throw new l('"signal" was already aborted.',{code:"INVALID_REQUEST"});if(typeof e.poll=="number"&&e.poll<0)throw new l('"poll" should be a non-negative number.',{code:"INVALID_PARAMETER"});let s=e?.onResponse,o=e?.onError,a=e?.onStream,d=typeof e.poll=="number"?e.poll:e.poll?1e3:0;delete e.poll,(d||e.stream)&&!e.queue&&(e.queue=(this.__user?.user_id||"anonymous")+"-"+Te());let u=c=>{for(let p in c)if(typeof c[p]=="string"&&c[p].includes("$CLIENT_SECRET")){r=true;break}};if(e=y.Params(e,{url:c=>{if(!c||typeof c!="string")throw new l('"url" should be type: <string>.',{code:"INVALID_PARAMETER"});return y.Url(c),c.includes("$CLIENT_SECRET")&&(r=true),c},secretName:"string",clientSecretName:"string",method:c=>{if(c&&typeof c!="string")throw new l('"method" should be one of "GET", "POST", "PUT", "PATCH", "DELETE" or "HEAD".',{code:"INVALID_PARAMETER"});let p=c.toLowerCase();if(p!=="get"&&p!=="post"&&p!=="delete"&&p!=="put"&&p!=="patch"&&p!=="head")throw new l('"method" should be one of "GET", "POST", "PUT", "PATCH", "DELETE" or "HEAD".',{code:"INVALID_PARAMETER"});return p},stream:c=>{if(c!=null&&typeof c!="boolean")throw new l('"stream" should be type: <boolean>.',{code:"INVALID_PARAMETER"});return !!c},realtime:c=>{if(c!=null&&typeof c!="boolean")throw new l('"realtime" should be type: <boolean>.',{code:"INVALID_PARAMETER"});return !!c},headers:c=>{if(c&&typeof c!="object")throw new l('"headers" should be type: <object>.',{code:"INVALID_PARAMETER"});return el(c),u(c),c},skapiHeaders:c=>Za(c),data:c=>{if(c&&typeof c!="object")throw new l('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return u(c),c},params:c=>{if(c&&typeof c!="object")throw new l('"params" should be type: <object>.',{code:"INVALID_PARAMETER"});return u(c),c},body_b64:"string",body_content_type:"string",expires:"number",queue:"string"},t?.requireSecretName?["clientSecretName","method","url"]:["method","url"]),e.realtime&&!e.stream)throw new l('"realtime" requires "stream": true.',{code:"INVALID_PARAMETER"});if(e.body_b64&&e.data)throw new l('"data" cannot be sent with "multipart": true.',{code:"INVALID_PARAMETER"});if(n&&!r){let c=e.method==="get"||e.method==="delete"||e.method==="head"?'"params"':'"data"';throw new l(`At least one parameter value should include "$CLIENT_SECRET" in ${c} or "headers".`,{code:"INVALID_PARAMETER"})}await this.__connection;let g=!!this.__user,f=()=>k.bind(this)("csr",e,{auth:g,tokenHeaders:{accessToken:!!g}}).then(c=>{if(c.status==="running"||c.status==="pending"){let p=`[${e.method.toUpperCase()}]${e.url.toLowerCase()}`,h=e.service||this.service,m=e.owner||this.owner,w=`${p}#${h}:${c.id}`;if(i){let b=()=>{Mt.call(this,{id:w});};i.aborted?b():i.addEventListener("abort",b,{once:true});}Object.assign(c,{poll:b=>_s.call(this,{id:w,auth:g,service:h,owner:m,latency:b?.latency||1e3,queue:e?.queue,onResponse:s,onError:o,onStream:b?.onStream||a,realtimeGroup:c?.realtime_group})});}return s?s(c):c}).catch(c=>{if(o)return o(c);throw c});if(e?.queue){let c="base:"+e.queue;return he?.[c]||(he[c]=new as({breakWhenError:false,batchSize:1})),new Promise((p,h)=>{he[c].add([async()=>{try{let m=await f();if(d>0){let w=m.poll({latency:d});return i&&(i.aborted?w.stop():i.addEventListener("abort",()=>w.stop(),{once:!0})),p(w),w}return p(m),m}catch(m){throw h(m),m}}]);})}else return f()}async function As(e,t){if(!t||typeof t!="object")throw new l('"options" is required in the second argument.',{code:"INVALID_PARAMETER"});if(t.apiKeyHeader!==void 0||t.apiKeyScheme!==void 0)throw new l('"apiKeyHeader" and "apiKeyScheme" are no longer supported. Store the key as a client secret, name it with "secretName", and put "$CLIENT_SECRET" where the key goes.',{code:"INVALID_PARAMETER"});if(t.multipart!==void 0&&t.multipart!==null&&typeof t.multipart!="boolean")throw new l('"multipart" should be type: <boolean>.',{code:"INVALID_PARAMETER"});let r=t.responseType;if(r!=null){if(r==="response")throw new l(`"responseType": "response" is not available here. The request is relayed from the server and what comes back is the stored answer, not a live Response; the destination's status code is the "status_code" of the row forwardRequestHistory lists.`,{code:"INVALID_PARAMETER"});if(r!=="json"&&r!=="text")throw new l('"responseType" should be either "json" or "text".',{code:"INVALID_PARAMETER"})}let n=t.method||"POST",i=typeof n=="string"?n.toLowerCase():"",s=i==="get"||i==="delete"||i==="head"?"params":"data",o={url:t.url,method:n};if(t.secretName!==void 0&&(o.secretName=t.secretName),t.headers!==void 0&&(o.headers=t.headers),t.data!==void 0&&(o.data=t.data),t.params!==void 0&&(o.params=t.params),t.skapiHeaders!==void 0&&(o.skapiHeaders=t.skapiHeaders),t.service!==void 0&&(o.service=t.service),t.owner!==void 0&&(o.owner=t.owner),t.queue!==void 0&&(o.queue=t.queue),t.expires!==void 0&&(o.expires=t.expires),t.stream!==void 0&&(o.stream=t.stream),t.realtime!==void 0&&(o.realtime=t.realtime),t.poll!==void 0&&(o.poll=t.poll),t.onStream!==void 0&&(o.onStream=t.onStream),t.onResponse!==void 0&&(o.onResponse=t.onResponse),t.onError!==void 0&&(o.onError=t.onError),t.multipart){if(t.data!==void 0&&t.data!==null)throw new l('"data" cannot be sent with "multipart": true. The form itself is the body.',{code:"INVALID_PARAMETER"});let d=await Xa(e);o.body_b64=d.body_b64,o.body_content_type=d.body_content_type;}else {let d=Ya(e);d&&Object.keys(d).length&&(o[s]=Object.assign({},d,o[s]||{}));}let a=Es.call(this,o,{signal:t.signal});return r?a.then(d=>{if(ys(d)||Cr(d))return d;if(r==="text")return typeof d=="string"?d:JSON.stringify(d);if(typeof d=="string")try{return JSON.parse(d)}catch{return d}return d}):a}async function Rs(e){return Es.call(this,e,{requireSecretName:true})}async function Lr(e,t){await this.__connection;let r=e.service||this.service,n=e.owner||this.owner;e=y.Params(e,{url:"string",method:["GET","POST","PUT","PATCH","DELETE","HEAD"],queue:"string",status:["pending","running","resolved","failed"],compact:"boolean",queue_exact:"boolean",queue_exclude:"string"},["url","method"]);let i=!!this.__user,s=`[${e.method.toUpperCase()}]${e.url.toLowerCase()}#${r}:`,o={id:s,queue:e?.queue,status:e?.status,service:r,owner:n};e?.compact&&(o.compact=true),e?.queue_exact&&(o.queue_exact=true),e?.queue_exclude&&(o.queue_exclude=e.queue_exclude),Object.keys(o).forEach(d=>{o[d]||delete o[d];}),o.queue&&(o.id_prefix=o.id,delete o.id);let a=await k.bind(this)("csr-poll",o,{auth:i,fetchOptions:t});return a.list=a.list.map(d=>{let u={id:d.id,status_code:d.rslv?.status_code||null,response_body:d.rslv?.body||d.rslv?.truncated||null,error:d?.err,created:d?.stmp,updated:d?.utmp,executed:typeof d?.att=="number"?d.att*1e3:void 0,request_body:d?.reqbdy,expires:d?.expt,status:d.stts,queue_name:d?.qid,request_text:d?.reqtxt,response_text:d?.rslvtxt,response_complete_marker:d?.rslvmk!=null?!!d.rslvmk:void 0,compact:d?.cmpct?true:void 0};for(let g in u)u[g]===void 0&&delete u[g];return (u.status==="running"||u.status==="pending")&&(u.poll=g=>_s.call(this,{id:s+u.id,auth:i,service:r,owner:n,latency:g?.latency||1e3,queue:d?.qid,seedExecuted:u.executed,onResponse:g?.onResponse,onError:g?.onError,onStream:g?.onStream})),u}),a}async function Fr(e){await this.__connection,e=y.Params(e,{url:"string",method:["GET","POST","PUT","PATCH","DELETE","HEAD"],id:"string",queue:"string"},["url","method","id"]);let t=e?.service||this.service,r=e?.owner||this.owner,n=!!this.__user,i=`[${e.method.toUpperCase()}]${e.url.toLowerCase()}#${t}`,s=e.id,o=`${i}:${s}`,a=e?.queue;return a&&he?.[a]&&(he[a].remove(ot[o]),delete ot[o]),k.bind(this)("csr-cancel",{id:o,service:t,owner:r},{auth:n})}function Mr(e,t){let r=typeof t?.poll=="number"?t.poll:1e3;if(!Number.isFinite(r)||r<0)throw new l('"poll" should be a non-negative number.',{code:"INVALID_PARAMETER"});if(!e||typeof e!="string")throw new l('"requestId" should be type: <string>.',{code:"INVALID_PARAMETER"});if(t?.since!==void 0&&typeof t.since!="number")throw new l('"since" should be a number.',{code:"INVALID_PARAMETER"});if(t?.realtimeGroup!==void 0&&t.realtimeGroup!==null&&typeof t.realtimeGroup!="string")throw new l('"realtimeGroup" should be type: <string>.',{code:"INVALID_PARAMETER"});let n=typeof t?.since=="number"&&t.since>0?t.since:0,i=t?.onStream,s=t?.onResponse,o=t?.onError,a={stopped:false,fullId:e,resolve:null},d=null,u={stop:null,aborted:false},g=()=>{te[a.fullId]===u&&delete te[a.fullId];},f=()=>{a.stopped||(a.stopped=true,d&&d(),g(),a.resolve&&a.resolve(at(a.fullId)));};u.stop=f;let c=new Promise(async(p,h)=>{a.resolve=p;try{await this.__connection;let m=!!this.__user,w=t?.service||this.service,b=t?.owner||this.owner;if(a.fullId=bs(e,t?.url,t?.method,w),a.stopped){p(at(a.fullId));return}te[a.fullId]=u;let _={seq:n},E=0,S=ps.call(this,a.fullId),A=i&&t?.realtimeGroup?gs(_,i,S.onTransport):null,N=A?hs.call(this,t.realtimeGroup,A):null,x=()=>{S.done(A),N&&N.stop(),A&&A.close();};for(d=x;;){let C=await k.bind(this)("csr-poll",{id:a.fullId,service:w,owner:b,since:_.seq},{auth:m});if(a.stopped)return;if(!ys(C)){x(),g(),s&&s(C),p(C);return}let v=A?A.fromPoll(C):ds(C,_,i);A&&A.open();let U=ms(C);if(C.more&&v){E=0;continue}if(E=C.more?E+1:0,!U&&(!C.more||E>=us)){x(),g(),s&&s(C),p(C);return}if(await new Promise(O=>setTimeout(O,A&&A.warm()?Math.max(r,fs):r)),a.stopped)return}}catch(m){if(a.stopped)return;d&&d(),g(),o&&o(m),h(m);}});return Object.assign(c,{stop:f})}async function qr(e,t,r){await this.__connection;let n=r?.service||this.service,i=r?.owner||this.owner,s=!!this.__user,o=bs(e,r?.url,r?.method,n);return k.bind(this)("csr-finalize",{id:o,data:t,service:n,owner:i},{auth:s})}var Ts=Mr,Is=qr,Ps=Lr,Ss=Fr,ks=Mt,vs=Or;async function Ns(e){await this.__connection;let t={name:"string",email:r=>(y.Email(r),r),subject:"string",message:"string"};return e=y.Params(e,t,["name","email","subject","message"]),await k.bind(this)("send-inquiry",e),"SUCCESS: Inquiry has been sent."}async function Ds(e,t){if(await this.__connection,Ha&&e instanceof FormData||ls&&e instanceof HTMLFormElement||cs&&e instanceof SubmitEvent){if(!t)throw new l("Url string as a second argument is required when form is passed.",{code:"INVALID_PARAMETER"});let n=j(e);e={url:t,data:n.data,sync:true};}let r={url:n=>y.Url(n),data:n=>n,sync:["boolean",()=>true]};if(Array.isArray(e))for(let n of e)n=y.Params(n,r);else e=y.Params(e,r);return k.bind(this)("post-secure",e,{auth:true})}async function xs(e,t){await this.__connection;let{auth:r=false,method:n="POST",bypassAwaitConnection:i=false,responseType:s,contentType:o,tokenHeaders:a,progress:d}=t||{};if(t=Object.assign({auth:r,method:n,bypassAwaitConnection:i,responseType:s,contentType:o,tokenHeaders:a},{fetchOptions:{progress:d}}),typeof e!="object"&&(o==="application/json"||o===void 0))throw new l('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return k.bind(this)("mock",e,t)}async function Us(e,t){await this.__connection,e=y.Params(e||{},{access_group:n=>{if(n==="authorized"&&(n=1),n==="public"&&(n=0),typeof n!="number")throw new l('"access_group" should be type number.',{code:"INVALID_PARAMETER"});if(n<0)throw new l('"access_group" should be zero or a positive number.',{code:"INVALID_PARAMETER"});if(n>this.__user.access_group)throw new l("User has no access.",{code:"INVALID_REQUEST"});return n}});let r=await k.bind(this)("get-feed",e,{auth:true,fetchOptions:t});return Array.isArray(r?.list)&&(r.list=await Promise.all(r.list.map(n=>Se.bind(this)(n)))),r}function lt(e){if(e===this.__user.user_id)throw new l(`"user_id" cannot be the user's own ID.`,{code:"INVALID_PARAMETER"});return y.UserId(e,'"user_id"')}async function Cs(e,t){if(e=j(e,{ignoreEmpty:true}).data,e=y.Params(e,{subscriber:n=>y.UserId(n,'User ID in "subscriber"'),subscription:lt.bind(this),blocked:"boolean"}),!e.subscriber&&!e.subscription)throw new l('At least either "subscriber" or "subscription" should have a value.',{code:"INVALID_PARAMETER"});let r=await k.bind(this)("get-subscription",e,Object.assign({auth:true},{fetchOptions:t}));return r.list=r.list.map((n=>{let i={};if(n.sub){let s=n.sub.split("#");i.subscriber=s[2],i.subscription=s[0];}else i.subscriber=n.subscriber,i.subscription=n.subscription;return i.timestamp=n?.timestamp||n.stmp,i.blocked=n?.blocked||n.grp.substring(0,1)==="N",Object.assign(i,n.opt),i})),r}async function Os(e){await this.__connection,e=y.Params(e,{user_id:lt.bind(this),get_feed:["boolean",()=>false],get_notified:["boolean",()=>false],get_email:n=>{if(n&&!this.__user.email||!this.__user.email_verified)throw new l("User has no verified email address.",{code:"INVALID_REQUEST"});return !!n}},["user_id"]);let t=await k.bind(this)("subscription",{subscribe:e.user_id,option:{get_feed:e.get_feed,get_notified:e.get_notified,get_email:e.get_email||false}},{auth:true}),r={};if(t.sub){let n=t.sub.split("#");r.subscriber=n[2],r.subscription=n[0];}else r.subscriber=t.subscriber,r.subscription=t.subscription;return r.timestamp=t?.timestamp||t.stmp,r.blocked=t?.blocked||t.grp.substring(0,1)==="N",Object.assign(r,t.opt),r}async function Ls(e){await this.__connection;let{user_id:t}=y.Params(e,{user_id:lt.bind(this)},["user_id"]);return await k.bind(this)("subscription",{unsubscribe:t},{auth:true})}async function Fs(e){await this.__connection;let{user_id:t}=y.Params(e,{user_id:lt.bind(this)},["user_id"]);return await k.bind(this)("subscription",{block:t},{auth:true})}async function Ms(e){await this.__connection;let{user_id:t}=y.Params(e,{user_id:lt.bind(this)},["user_id"]);return await k.bind(this)("subscription",{unblock:t},{auth:true})}async function qs(e,t){await this.__connection;let r=await W.bind(this)();if(e=y.Params(e||{},{user_id:o=>{if(o!==this.__user.user_id&&!r)throw new l("No access.",{code:"INVALID_REQUEST"});return o},group:o=>y.newsletterGroup(o,{allowNull:true}),email:o=>{if(typeof o!="string"||!o.trim())throw new l('"email" should be a non-empty string.',{code:"INVALID_PARAMETER"});if(o.trim().length>255)throw new l('"email" should be at most 255 characters.',{code:"INVALID_PARAMETER"});return o.trim().toLowerCase()}}),e.email!==void 0){if(e.user_id!==void 0&&e.user_id!==null)throw new l('"email" cannot be used with "user_id".',{code:"INVALID_PARAMETER"});if(e.group===void 0||e.group===null)throw new l('"group" is required to search by "email".',{code:"INVALID_PARAMETER"})}let n=await k.bind(this)("get-newsletter-subscription",e,{auth:true,fetchOptions:t||null}),i=n?.list||n,s=[];Array.isArray(i)||(i=[]);for(let o of i){let a=o.subt.split("#"),d=true;a[0].charAt(0)==="@"&&(d=false,a[0]=a[0].substring(1));let u=/^\d+$/.test(a[0])?parseInt(a[0]):a[0],g={timestamp:o.stmp,group:u,subscribed_email:a[1],active:d};typeof o.email_token=="string"&&o.email_token&&(g.subscriber_token=o.email_token),s.push(g);}return n?.list?(n.list=s,n):s}async function Vs(e){await this.__connection;let t=y.Params(e||{},{email:r=>Array.isArray(r)&&r.length>0?r.length===1?y.Email(r[0]):r.map(n=>y.Email(n)):y.Email(r),group:r=>y.newsletterGroup(r),redirect:r=>y.Url(r)},this.__user?["group"]:["email","group"]);return k.bind(this)(`subscribe-${this.__user?"":"public-"}newsletter`,t,{auth:!!this.__user})}async function $s(e){await this.__connection;let t=y.Params(e||{},{group:r=>y.newsletterGroup(r,{nameOnly:true}),restriction:r=>{if(typeof r!="number"||!Number.isInteger(r)||r<0||r>99)throw new l('"restriction" should be a number between 0 and 99.',{code:"INVALID_PARAMETER"});return r},name:r=>{if(typeof r!="string"||r.length>60)throw new l('"name" should be a string of 60 characters or less.',{code:"INVALID_PARAMETER"});return r}},["group"]);return k.bind(this)("register-newsletter-group",t,{auth:true})}async function js(e){await this.__connection;let t=y.Params(e||{},{group:r=>y.newsletterGroup(r,{nameOnly:true})},["group"]);return k.bind(this)("delete-newsletter-group",t,{auth:true})}async function Bs(){return await this.__connection,k.bind(this)("newsletter-group-endpoint",null,{auth:true})}async function Ks(e){await this.__connection,e=y.Params(e,{group:r=>y.newsletterGroup(r,{allowNull:true})},["group"]);let t=Object.assign({action:"unsubscribe"},e);return k.bind(this)("subscribe-newsletter",t,{auth:true})}async function Hs(e,t){let r=await W.bind(this)(),n={message_id:"string",timestamp:"number",read:"number",complaint:"number",subject:"string",bounced:"number"};e||(t=Object.assign({ascending:false},t||{})),e=j(e).data,e=e||{searchFor:"timestamp",value:Date.now(),condition:"<",group:"public"},e=y.Params(e,{searchFor:["message_id","timestamp","subject","complaint","read","bounced"],value:d=>{if(typeof d!==n[e.searchFor])throw new l(`"value" type does not match the type of "${e.searchFor}" index.`,{code:"INVALID_PARAMETER"});if(typeof d=="string"&&!d)throw new l('"value" should not be empty string.',{code:"INVALID_PARAMETER"});return d},range:d=>{if(!e.hasOwnProperty("value")||typeof d!=typeof e.value)throw new l('"range" should match type of "value".',{code:"INVALID_PARAMETER"});return d},condition:[">",">=","=","<","<=","gt","gte","eq","lt","lte",()=>"="],group:d=>{let u=y.newsletterGroup(d);if(u===0)return 0;if(typeof u=="string")return u;if(!this.session)throw new l("User should be logged in.",{code:"INVALID_REQUEST"});if(d==="authorized")return 1;if(!r&&u>parseInt(this.user?.access_group||this.session?.idToken?.payload?.access_group))throw new l("User has no access.",{code:"INVALID_REQUEST"});return u}},["searchFor","value","group"]);let i=e.group===0||typeof e.group=="string"&&!this.__user?"get-public-newsletters":"get-newsletters",s=await k.bind(this)(i,e,Object.assign({method:"get",auth:i==="get-public-newsletters"?!!this.__user:true},{fetchOptions:t})),o={message_id:"mid",timestamp:"stmp",complaint:"cmpl",read:"read",subject:"subj",bounced:"bnce",url:"url",delivered:"delv",group:"grp"},a={message_id:"",timestamp:0,complaint:0,read:0,subject:"",bounced:"",url:"",delivered:0,group:e.group};return s.list=s.list.map(d=>{let u={};for(let g in o)u[g]=d[o[g]]||a[g];return u.bounced=String(u.bounced),u}),s}async function Gs(e){let t=y.Params(e,{user_id:n=>y.UserId(n,'"user_id"')},["user_id"]);if(t?.service&&t?.owner?t={service:t?.service,owner:t?.owner,block:t.user_id}:t={block:t.user_id},!await W.bind(this)()){if(!this.__user)throw new l("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new l("Invalid access.",{code:"INVALID_REQUEST"})}return await k.bind(this)("block-account",t,{auth:true})}async function Ws(e){let t=y.Params(e,{user_id:n=>y.UserId(n,'"user_id"')},["user_id"]);if(t?.service&&t?.owner?t={service:t?.service,owner:t?.owner,unblock:t.user_id}:t={unblock:t.user_id},!await W.bind(this)()){if(!this.__user)throw new l("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new l("Invalid access.",{code:"INVALID_REQUEST"})}return await k.bind(this)("block-account",t,{auth:true})}async function Qs(e){let t=y.Params(e,{user_id:n=>y.UserId(n,'"user_id"')},["user_id"]);if(t?.service&&t?.owner?t={service:t?.service,owner:t?.owner,delete:t.user_id}:t={delete:t.user_id},!await W.bind(this)()){if(!this.__user)throw new l("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new l("Invalid access.",{code:"INVALID_REQUEST"})}return await k.bind(this)("remove-account",t,{auth:true})}async function zs(e,t){let r={email:s=>y.Email(s),password:s=>y.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=>y.Birthdate(s),phone_number:s=>y.PhoneNumber(s),picture:s=>{if(s)return y.Url(s)},profile:s=>{if(s)return y.Url(s)},website:s=>{if(s)return y.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 l('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof s!="number"||s<1||s>100)throw new l('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"});return s}},n=y.Params(e,r,["email"]);if(t=y.Params(t,{confirmation_url:s=>{let o=s;if(typeof s=="string")o=y.Url(s);else throw new l('"options.confirmation_url" should be type: <string>.',{code:"INVALID_PARAMETER"});if(o&&!n.email)throw new l('"email" is required for signup confirmation.',{code:"INVALID_PARAMETER"});return o},email_subscription:s=>{if(typeof s!="boolean")throw new l('"options.email_subscription" should be type: <boolean>.',{code:"INVALID_PARAMETER"});if(!t?.confirmation_url)throw new l('"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 l('"options.template" should be type: <object> with "url" and "subject".',{code:"INVALID_PARAMETER"});return {url:y.Url(s.url),subject:s.subject}}}),n.signup_confirmation=t?.confirmation_url||true,n.email_subscription=t?.email_subscription||false,n.template=t?.template||{},!await W.bind(this)()){if(!this.__user)throw new l("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new l("Invalid access.",{code:"INVALID_REQUEST"})}return await k.bind(this)("admin-signup",n,{auth:true})}async function Js(e){let t={email:s=>y.Email(s),password:s=>y.Password(s),openid_id:"string",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=>y.Birthdate(s),phone_number:s=>y.PhoneNumber(s),picture:s=>s?y.Url(s):"",profile:s=>s?y.Url(s):"",website:s=>s?y.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],access_group:s=>{try{typeof s=="string"&&(s=parseInt(s));}catch{throw new l('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof s!="number"||s<1||s>100)throw new l('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"});return s}},r=["email","password"],n=y.Params(e,t,r);if(!await W.bind(this)()){if(!this.__user)throw new l("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new l("Invalid access.",{code:"INVALID_REQUEST"})}return await k.bind(this)("admin-signup",n,{auth:true})}async function Ys(e){if(e=y.Params(e,{user_id:r=>y.UserId(r,'"user_id"'),access_group:r=>{try{typeof r=="string"&&(r=parseInt(r));}catch{throw new l('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof r=="number"&&r>0&&r<100)return r;throw new l('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"})}},["user_id","access_group"]),!await W.bind(this)()){if(!this.__user)throw new l("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new l("Invalid access.",{code:"INVALID_REQUEST"})}return await k.bind(this)("grant-access",e,{auth:true})}async function Xs(e,t){if(e=y.Params(e,{email:"string"}),!await W.bind(this)()){if(!this.__user)throw new l("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new l("Invalid access.",{code:"INVALID_REQUEST"})}let n=await k.bind(this)("invitation-list",Object.assign({mode:"search"},e),{fetchOptions:t,auth:true});return n.list=n.list.map(i=>je(i.user)),n}async function Zs(e){if(e=y.Params(e,{email:r=>y.Email(r)},["email"]),!await W.bind(this)()){if(!this.__user)throw new l("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new l("Invalid access.",{code:"INVALID_REQUEST"})}return await k.bind(this)("invitation-list",Object.assign({mode:"cancel"},e),{auth:true})}async function eo(e){if(e=y.Params(e,{email:r=>y.Email(r)},["email"]),!await W.bind(this)()){if(!this.__user)throw new l("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new l("Invalid access.",{code:"INVALID_REQUEST"})}return await k.bind(this)("invitation-list",Object.assign({mode:"resend"},e),{auth:true})}async function to(e){let t=y.Params(e,{user_id:o=>y.UserId(o,'"user_id"'),email:o=>y.Email(o),address:o=>{if(!o)return "";if(typeof o=="string")return o;if(typeof o=="object")return JSON.stringify(o)},name:"string",gender:"string",birthdate:o=>o?y.Birthdate(o):"",phone_number:o=>o?y.PhoneNumber(o):"",email_public:"boolean",phone_number_public:"boolean",address_public:"boolean",gender_public:"boolean",birthdate_public:"boolean",misc:"string",picture:o=>o?y.Url(o):"",profile:o=>o?y.Url(o):"",nickname:"string",website:o=>o?y.Url(o):""},["user_id"]),r=t.service,n=t.owner;if(delete t.service,delete t.owner,await this.__connection,this.__user?.user_id&&t.user_id===this.__user.user_id)throw new l("Cannot modify attributes of the current user.",{code:"INVALID_REQUEST"});if(Object.keys(t).filter(o=>o!=="user_id"&&t[o]!==void 0).length===0)throw new l("At least one attribute to update is required.",{code:"INVALID_PARAMETER"});if(!await W.bind(this)()){if(!this.__user)throw new l("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new l("Invalid access.",{code:"INVALID_REQUEST"})}let s={attributes:t};return r&&n&&(s.service=r,s.owner=n),await k.bind(this)("admin-edit-profile",s,{auth:true})}async function ro(e){if(typeof window>"u"||window._runningInNodeJS)throw new l("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.__connection,!e.endpoint)throw new l("Missing parameter: endpoint",{code:"INVALID_PARAMETER"});if(!e.keys||!e.keys.p256dh||!e.keys.auth)throw new l("Missing parameter: keys.p256dh or keys.auth",{code:"INVALID_PARAMETER"});return await k.bind(this)("store-subscription",{endpoint:e.endpoint,keys:e.keys},{auth:true}),"SUCCESS: Subscribed to receive notifications."}async function no(e){if(typeof window>"u"||window._runningInNodeJS)throw new l("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.__connection,!e.endpoint)throw new l("Missing parameter: endpoint",{code:"INVALID_PARAMETER"});if(!e.keys||!e.keys.p256dh||!e.keys.auth)throw new l("Missing parameter: keys.p256dh or keys.auth",{code:"INVALID_PARAMETER"});return await k.bind(this)("delete-subscription",{endpoint:e.endpoint,keys:e.keys},{auth:true}),"SUCCESS: Unsubscribed from notifications."}async function io(){if(typeof window>"u"||window._runningInNodeJS)throw new l("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});return await this.__connection,{VAPIDPublicKey:await k.bind(this)("get-vapid-public-key",null,{auth:true})}}async function so(e,t){if(typeof window>"u"||window._runningInNodeJS)throw new l("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});await this.__connection;let{title:r,body:n}=j(e||{},{nullIfEmpty:true}).data;if(!r)throw new l("Missing parameter: message title",{code:"INVALID_PARAMETER"});if(!n)throw new l("Missing parameter: message body",{code:"INVALID_PARAMETER"});let i={title:r,body:n};return t?(typeof t=="string"&&(t=[t]),i.user_ids=t):i.user_ids="all_users",await k.bind(this)("push-notification",i,{auth:true}),"SUCCESS: Notification sent."}async function oo(e){await this.__connection,e=y.Params(e,{spell:"string",name:"string",magic:r=>r},["spell","name"]);await k.bind(this)("castspell",e);return `The spell "${e.spell}" has been cast.`}async function ao(e){return await this.__connection,e=y.Params(e||{},{search:["spell","name",()=>"spell"],value:"string"}),await k.bind(this)("getspell",e)}async function lo(e){await this.__connection,e=y.Params(e,{message:"string",name:"string"},["message","name"]);let t=await k.bind(this)("dopamine",e,{auth:true}),r=t?.previous_message?.message,n=t?.previous_message?.name;if(J())r&&n&&window.alert(`${n} said: ${r}`),window.location.href=t.video;else return r&&n?`${n} said: ${r}
|
|
216
216
|
Watch the video here: ${t.video}`:`Your message has been uploaded for future generations to receive.
|
|
217
|
-
Watch the video here: ${t.video}`}var
|
|
217
|
+
Watch the video here: ${t.video}`}var T=class{constructor(t,r,n,i){this.__version="2.1.0";this.project_id="";this.session=null;this.connection=null;this.__my_unique_ids={};this.__uniqueIdsPersistTimer=null;this.userPool=null;this.__socket=null;this.__mediaStream=null;this.host="skapi";this.hostDomain="skapi.com";this.target_cdn="d3e9syvbtso631";this.customApiDomain="skapi.dev";this.requestBatchSize=30;this.__disabledAccount=null;this.__cached_requests={};this.__startKeyHistory={};this.__request_signup_confirmation=null;this.__private_access_key={};this.__class_properties_has_been_cached=false;this.__user=null;this._userProfileListeners=[];this._onLoginListeners=[];this._onBatchProcessListeners=[];this.validate={userId(t){try{return y.UserId(t),!0}catch{return false}},url(t){try{return y.Url(t),!0}catch{return false}},phoneNumber(t){try{return y.PhoneNumber(t),!0}catch{return false}},birthdate(t){try{return y.Birthdate(t),!0}catch{return false}},email(t){try{return y.Email(t),!0}catch{return false}},params(t,r,n){return y.Params(t,r,n)}};this.util={MD5:Z,generateRandom:Te,toBase62:zr,fromBase62:se,decodeProjectId:Gt,formatServiceId:Wt,extractFormData:j,terminatePendingRequests:Ai,request:(t,r,n)=>k.bind(this)(t,r,n,{ignoreService:true})};this.__network_logs=false;this.__endpoint_version="v2";this.__public_identifier="";this.bearerToken="";this.registerTicket=ti.bind(this);this.unregisterTicket=ri.bind(this);if(!t||typeof t!="string")throw this._alert("Service ID is required."),new l("Service ID is required.",{code:"INVALID_PARAMETER"});let s=t.trim().toLowerCase().replace(/^<|>$/g,"").replace(/[\s_\-.]+/g,"");if(s==="serviceid"||s==="projectid")throw this._alert(`Replace "${t}" with your actual Project ID.`),new l("Project ID is required.",{code:"INVALID_PARAMETER"});let o=t.split("-").length;if(o===2||o===7)try{let _=Gt(t);n&&typeof n=="object"&&(i=n),r&&typeof r=="object"&&(n=r),r=_.owner,t=_.service;}catch{throw this._alert("Service ID is invalid."),new l("Service ID is invalid.",{code:"INVALID_PARAMETER"})}if(!r||typeof r!="string")throw this._alert("Owner ID is invalid."),new l("Owner ID is invalid.",{code:"INVALID_PARAMETER"});if(r!==this.host)try{y.UserId(r,'"owner"');}catch{throw this._alert("Owner ID is invalid."),new l("Owner ID is invalid.",{code:"INVALID_PARAMETER"})}this.service=t,this.owner=r;try{this.project_id=Wt(t,r);}catch{this.project_id="";}let u=true,g=false,f=null;if(n&&(typeof n.refetchServiceInfo=="boolean"&&(g=n.refetchServiceInfo),typeof n.autoLogin=="boolean"&&(u=n.autoLogin),n.encryption&&(f=_n(n.encryption)),typeof n.requestBatchSize=="number")){if(n.requestBatchSize<1)throw new l('"requestBatchSize" must be greater than 0.',{code:"INVALID_PARAMETER"});this.requestBatchSize=n.requestBatchSize;}n?.eventListener&&typeof n.eventListener=="object"&&(n.eventListener?.onLogin&&typeof n.eventListener.onLogin=="function"&&(this.onLogin=n.eventListener.onLogin),n.eventListener?.onUserUpdate&&typeof n.eventListener.onUserUpdate=="function"&&(this.onUserUpdate=n.eventListener.onUserUpdate),n.eventListener?.onBatchProcess&&typeof n.eventListener.onBatchProcess=="function"&&(this.onBatchProcess=n.eventListener.onBatchProcess)),this.target_cdn=i?.target_cdn||this.target_cdn,this.hostDomain=i?.hostDomain||this.hostDomain,this.customApiDomain=i?.customApiDomain||this.customApiDomain,this.__network_logs=!!i?.network_logs;let c=`https://${this.target_cdn}.cloudfront.net`,p=t.substring(0,4);this.admin_endpoint=fetch(`${c}/${p}/admin-${this.__endpoint_version}.json`).then(_=>_.blob()).then(_=>new Promise((E,S)=>{let A=new FileReader;A.onloadend=()=>E(A.result),A.onerror=S,A.readAsDataURL(_);})).then(_=>{try{return typeof _=="string"?JSON.parse(atob(_.split(",")[1])):null}catch{throw new l("Service does not exist. Create your service from skapi.com",{code:"NOT_EXISTS"})}}),this.record_endpoint=fetch(`${c}/${p}/record-${this.__endpoint_version}.json`).then(_=>_.blob()).then(_=>new Promise((E,S)=>{let A=new FileReader;A.onloadend=()=>E(A.result),A.onerror=S,A.readAsDataURL(_);})).then(_=>{try{return typeof _=="string"?JSON.parse(atob(_.split(",")[1])):null}catch{throw new l("Service does not exist. Create your service from skapi.com",{code:"NOT_EXISTS"})}});let h=J();if(h&&!window.sessionStorage)throw this._alert("This browser is not supported."),new Error("This browser is not supported.");let m=h?JSON.parse(window.sessionStorage.getItem(`${t}#${r}`)||"null"):null;if(this.log("constructor:restore",m),m?.connection){for(let _ in m)this[_]=m[_];m.__public_identifier||(this.__public_identifier=`${this.service}:${this.owner}:${Te(16)}`);}wn.bind(this)(f),this.__authConnection=(async()=>{let _=await this.admin_endpoint,E={UserPoolId:_.userpool_id,ClientId:_.userpool_client};Ht()&&(E.Storage=window.localStorage),this.userPool=new CognitoUserPool(E);try{this.user||await G.bind(this)().getSession({skipUserUpdateEventTrigger:!0}),this.user&&(!m?.connection&&!u?be.bind(this)():(f&&qn.bind(this)(),this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user)));}catch{}})();let w=`${this.service}/${this.owner}`,b=h?window.sessionStorage.getItem(`${w}:uniqueids`):null;if(b)try{let _=JSON.parse(b);this.__my_unique_ids=_&&typeof _=="object"&&!Array.isArray(_)?{[w]:_}:{};}catch{this.__my_unique_ids={};}this.__connection=(async()=>{let _=null;await this.record_endpoint,m?.connection||(_=this._updateConnection({refresh:g}));let E=()=>{if(this.__class_properties_has_been_cached)return;let S=()=>{let A={},N=["__startKeyHistory","__disabledAccount","__cached_requests","__request_signup_confirmation","__public_identifier","connection"];if(this.connection){for(let x of N)A[x]=this[x];if(f&&(A.__cached_requests={},A.__startKeyHistory={}),h){let x=`${t}#${r}`;try{window.sessionStorage.setItem(x,JSON.stringify(A));}catch{try{let v=Object.assign({},A,{__cached_requests:{},__startKeyHistory:{}});window.sessionStorage.setItem(x,JSON.stringify(v));}catch{try{window.sessionStorage.removeItem(x);}catch{}}}}this.__class_properties_has_been_cached=true;}};return _ instanceof Promise?_.then(()=>S()):S()};return h&&(window.addEventListener("beforeunload",()=>{this.closeRealtime(),E();}),window.addEventListener("visibilitychange",()=>{E();})),await _,await this.__authConnection,this.connection})(),this.__connection.then(_=>{((_?.group||0)<3||this.__network_logs)&&this.version();}).catch(()=>{});}get user(){return this.__user&&Object.keys(this.__user).length?JSON.parse(JSON.stringify(this.__user)):null}set user(t){}get onLogin(){return this._onLoginListeners}set onLogin(t){typeof t=="function"&&this._onLoginListeners.push(t);}get onUserUpdate(){return this._userProfileListeners}set onUserUpdate(t){typeof t=="function"&&this._userProfileListeners.push(t);}_runOnUserUpdateListeners(t){for(let r of this._userProfileListeners)typeof r=="function"&&r(t);}_runOnLoginListeners(t){for(let r of this._onLoginListeners)typeof r=="function"&&r(t);}get onBatchProcess(){return this._onBatchProcessListeners}set onBatchProcess(t){typeof t=="function"&&this._onBatchProcessListeners.push(t);}_alert(t){J()&&typeof window.alert=="function"&&window.alert(t);}async getConnectionInfo(t){t?.refresh&&(this.__connection instanceof Promise&&await this.__connection,this.__connection=this._updateConnection({refresh:true}));let n=await this.__connection,i=n?.user_agent||(J()&&typeof window.navigator?.userAgent=="string"?window.navigator.userAgent:`skapi-node/${globalThis?.process?.versions?.node||"unknown"}`);return {project_id:this.project_id,user_ip:n.ip,user_agent:i,user_location:n.locale,service_name:n.service_name,version:this.__version,service_description:n?.service_description||"",ai_agent:n?.ai_agent||"",conf:n?.opt}}async _updateConnection(t){let r=t?.refresh||false;try{this.connection=await k.bind(this)("service",{service:this.service,owner:this.owner,refresh:r},{bypassAwaitConnection:!0,method:"get"});}catch(n){throw this.log("connection fail",n),this._alert("Service is not available: "+(n.message||n.toString())),this.connection=null,n}return this.connection}async version(){if(await this.__connection,J()){let r=`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(r,"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(t,r){if(this.__network_logs){if(r!==null&&typeof r=="object")try{
|
|
233
|
-
export{
|
|
232
|
+
Full Documentation: https://docs.skapi.com/skapi.md`;console.log(r,"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(t,r){if(this.__network_logs){if(r!==null&&typeof r=="object")try{J()?r=JSON.parse(JSON.stringify(r)):r=JSON.stringify(r,null,2);}catch{r=String(r);}else typeof r=="string"&&r.length>100&&(r=r.substring(0,100)+"...");console.log(`%c${t}:`,"color: blue;",r);}}getFeed(t,r){return Us.bind(this)(t,r)}closeRTC(t){return ue.bind(this)(t)}connectRTC(t,r){return Xi.bind(this)(t,r)}connectRealtime(t){return qe.bind(this)(t)}spellcast(t){return oo.bind(this)(t)}getspell(t){return ao.bind(this)(t)}dopamine(t){return lo.bind(this)(t)}getUniqueId(t,r){return Bi.bind(this)(t,r)}resendInvitation(t){return eo.bind(this)(t)}cancelInvitation(t){return Zs.bind(this)(t)}getInvitations(t,r){return Xs.bind(this)(t,r)}openIdLogin(t){return ii.bind(this)(t)}loginWithToken(t){return si.bind(this)(t)}registerNewsletterGroup(t){return $s.bind(this)(t)}deleteNewsletterGroup(t){return js.bind(this)(t)}clientSecretRequest(t){return Rs.bind(this)(t)}clientSecretRequestHistory(t,r){return Lr.bind(this)(t,r)}clientSecretRequestStream(t,r){return Mr.bind(this)(t,r)}clientSecretRequestFinalize(t,r,n){return qr.bind(this)(t,r,n)}cancelClientSecretRequest(t){return Fr.bind(this)(t)}stopClientSecretPolling(t){return Mt.bind(this)(t||{})}isPollStopped(t){return Cr(t)}clientSecretRequestQueueCount(t){return Or.bind(this)(t)}forwardRequestHistory(t,r){return Ps.bind(this)(t,r)}forwardRequestStream(t,r){return Ts.bind(this)(t,r)}forwardRequestFinalize(t,r,n){return Is.bind(this)(t,r,n)}cancelForwardRequest(t){return Ss.bind(this)(t)}stopForwardRequestPolling(t){return ks.bind(this)(t||{})}forwardRequestQueueCount(t){return vs.bind(this)(t)}consumeTicket(t){return Xn.bind(this)(t)}getConsumedTickets(t,r){return ei.bind(this)(t,r)}getTickets(t,r){return Zn.bind(this)(t,r)}closeRealtime(){return Ot.bind(this)()}getRealtimeUsers(t,r){return is.bind(this)(t,r)}sendInquiry(t){return Ns.bind(this)(t)}blockAccount(t){return Gs.bind(this)(t)}unblockAccount(t){return Ws.bind(this)(t)}deleteAccount(t){return Qs.bind(this)(t)}inviteUser(t,r){return zs.bind(this)(t,r)}createAccount(t){return Js.bind(this)(t)}grantAccess(t){return Ys.bind(this)(t)}updateUserAttributes(t){return to.bind(this)(t)}getRealtimeGroups(t,r){return ss.bind(this)(t,r)}newsletterGroupEndpoint(){return Bs.bind(this)()}postRealtime(t,r,n){return ns.bind(this)(t,r,n)}joinRealtime(t){return Ve.bind(this)(t)}getProfile(t){return ni.bind(this)(t)}getFile(t,r){return _e.bind(this)(t,r)}secureRequest(t,r){return Ds.bind(this)(t,r)}forwardRequest(t,r){return As.bind(this)(t,r)}getFormResponse(){return Ti.bind(this)()}getRecords(t,r){return Fi.bind(this)(t,r)}getTables(t,r){return Vi.bind(this)(t,r)}getIndexes(t,r){return $i.bind(this)(t,r)}getTags(t,r){return ji.bind(this)(t,r)}deleteRecords(t,r){return Ki.bind(this)(t,r)}resendSignupConfirmation(){return oi.bind(this)()}recoverAccount(t=false){return ai.bind(this)(t)}getUsers(t,r){return yi.bind(this)(t,r)}disableAccount(){return ci.bind(this)()}lastVerifiedEmail(t){return bi.bind(this)(t)}unsubscribeNewsletter(t){return Ks.bind(this)(t)}subscribeNotification(t,r){return ro.bind(this)({endpoint:t,keys:r})}unsubscribeNotification(t,r){return no.bind(this)({endpoint:t,keys:r})}vapidPublicKey(){return io.bind(this)()}pushNotification(t,r){return so.bind(this)(t,r)}getNewsletters(t,r){return Hs.bind(this)(t,r)}getNewsletterSubscription(t,r){return qs.bind(this)(t,r)}getEncryptionStatus(){return En.bind(this)()}isWithheld(t){return ar.call(this,t)}unlockEncryption(t){return Cn.bind(this)(t)}lockEncryption(t){return On.bind(this)(t)}takeRecoveryCode(){return Kn.bind(this)()}unlockWithRecoveryCode(t){return Hn.bind(this)(t)}regenerateRecoveryCode(){return Gn.bind(this)()}pinPeerKey(t){return jn.bind(this)(t)}grantPrivateRecordAccess(t){return Hi.bind(this)(t)}removePrivateRecordAccess(t){return Gi.bind(this)(t)}listPrivateRecordAccess(t,r){return Wi.bind(this)(t,r)}requestPrivateRecordAccessKey(t){return Qi.bind(this)(t)}deleteFiles(t){return Ui.bind(this)(t)}uploadFiles(t,r){return rt.bind(this)(t,r)}mock(t,r){return xs.bind(this)(t,r)}login(t){return wr.bind(this)(t)}logout(t){return Ze.bind(this)(t)}signup(t,r){return li.bind(this)(t,r)}resetPassword(t){return ui.bind(this)(t)}verifyEmail(t,r){return gi.bind(this)(t,r)}verifyPhoneNumber(t,r){return fi.bind(this)(t,r)}forgotPassword(t,r){return pi.bind(this)(t,r)}changePassword(t){return hi.bind(this)(t)}updateProfile(t){return mi.bind(this)(t)}postRecord(t,r,n){return kr.bind(this)(t,r,n)}getSubscriptions(t,r){return Cs.bind(this)(t,r)}subscribe(t){return Os.bind(this)(t)}unsubscribe(t){return Ls.bind(this)(t)}blockSubscriber(t){return Fs.bind(this)(t)}unblockSubscriber(t){return Ms.bind(this)(t)}subscribeNewsletter(t){return Vs.bind(this)(t)}bulkPostRecords(t){return qi.bind(this)(t)}};I([P()],T.prototype,"getFeed"),I([P()],T.prototype,"closeRTC"),I([P()],T.prototype,"connectRTC"),I([P()],T.prototype,"spellcast"),I([P()],T.prototype,"getspell"),I([P()],T.prototype,"dopamine"),I([P()],T.prototype,"getUniqueId"),I([P()],T.prototype,"resendInvitation"),I([P()],T.prototype,"cancelInvitation"),I([P()],T.prototype,"getInvitations"),I([P()],T.prototype,"openIdLogin"),I([P()],T.prototype,"loginWithToken"),I([P()],T.prototype,"registerNewsletterGroup"),I([P()],T.prototype,"deleteNewsletterGroup"),I([P()],T.prototype,"clientSecretRequest"),I([P()],T.prototype,"clientSecretRequestHistory"),I([P()],T.prototype,"cancelClientSecretRequest"),I([P()],T.prototype,"forwardRequestHistory"),I([P()],T.prototype,"cancelForwardRequest"),I([P()],T.prototype,"consumeTicket"),I([P()],T.prototype,"getConsumedTickets"),I([P()],T.prototype,"getTickets"),I([P()],T.prototype,"getRealtimeUsers"),I([P()],T.prototype,"sendInquiry"),I([P()],T.prototype,"blockAccount"),I([P()],T.prototype,"unblockAccount"),I([P()],T.prototype,"deleteAccount"),I([P()],T.prototype,"inviteUser"),I([P()],T.prototype,"createAccount"),I([P()],T.prototype,"grantAccess"),I([P()],T.prototype,"updateUserAttributes"),I([P()],T.prototype,"getRealtimeGroups"),I([P()],T.prototype,"newsletterGroupEndpoint"),I([P()],T.prototype,"postRealtime"),I([P()],T.prototype,"joinRealtime"),I([P()],T.prototype,"getProfile"),I([P()],T.prototype,"getFile"),I([P()],T.prototype,"secureRequest"),I([P()],T.prototype,"forwardRequest"),I([P()],T.prototype,"getFormResponse"),I([P()],T.prototype,"getRecords"),I([P()],T.prototype,"getTables"),I([P()],T.prototype,"getIndexes"),I([P()],T.prototype,"getTags"),I([P()],T.prototype,"deleteRecords"),I([P()],T.prototype,"resendSignupConfirmation"),I([P()],T.prototype,"recoverAccount"),I([P()],T.prototype,"getUsers"),I([P()],T.prototype,"disableAccount"),I([P()],T.prototype,"lastVerifiedEmail"),I([P()],T.prototype,"unsubscribeNewsletter"),I([P()],T.prototype,"subscribeNotification"),I([P()],T.prototype,"unsubscribeNotification"),I([P()],T.prototype,"vapidPublicKey"),I([P()],T.prototype,"pushNotification"),I([P()],T.prototype,"getNewsletters"),I([P()],T.prototype,"getNewsletterSubscription"),I([P()],T.prototype,"unlockEncryption"),I([P()],T.prototype,"unlockWithRecoveryCode"),I([P()],T.prototype,"grantPrivateRecordAccess"),I([P()],T.prototype,"removePrivateRecordAccess"),I([P()],T.prototype,"listPrivateRecordAccess"),I([P()],T.prototype,"requestPrivateRecordAccessKey"),I([P()],T.prototype,"deleteFiles"),I([P()],T.prototype,"uploadFiles"),I([P()],T.prototype,"mock"),I([P({preventMultipleCalls:true})],T.prototype,"login"),I([P()],T.prototype,"logout"),I([P({preventMultipleCalls:true})],T.prototype,"signup"),I([P({preventMultipleCalls:true})],T.prototype,"resetPassword"),I([P({preventMultipleCalls:true})],T.prototype,"verifyEmail"),I([P({preventMultipleCalls:true})],T.prototype,"verifyPhoneNumber"),I([P({preventMultipleCalls:true})],T.prototype,"forgotPassword"),I([P({preventMultipleCalls:true})],T.prototype,"changePassword"),I([P({preventMultipleCalls:true})],T.prototype,"updateProfile"),I([P()],T.prototype,"postRecord"),I([P()],T.prototype,"getSubscriptions"),I([P()],T.prototype,"subscribe"),I([P()],T.prototype,"unsubscribe"),I([P()],T.prototype,"blockSubscriber"),I([P()],T.prototype,"unblockSubscriber"),I([P()],T.prototype,"subscribeNewsletter");var rl={};
|
|
233
|
+
export{T as Skapi,l as SkapiError,rl as Types};//# sourceMappingURL=skapi.mjs.map
|
|
234
234
|
//# sourceMappingURL=skapi.mjs.map
|