skapi-js 2.0.2 → 2.0.3
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 +2 -2
- package/dist/skapi.browser.mjs.map +1 -1
- package/dist/skapi.cjs +2 -2
- package/dist/skapi.cjs.map +1 -1
- package/dist/skapi.d.mts +1 -0
- package/dist/skapi.d.ts +1 -0
- package/dist/skapi.js +2 -2
- package/dist/skapi.js.map +1 -1
- package/dist/skapi.mjs +2 -2
- package/dist/skapi.mjs.map +1 -1
- package/package.json +1 -1
package/dist/skapi.d.mts
CHANGED
package/dist/skapi.d.ts
CHANGED
package/dist/skapi.js
CHANGED
|
@@ -213,9 +213,9 @@ var Fc=Object.create;var et=Object.defineProperty;var bi=Object.getOwnPropertyDe
|
|
|
213
213
|
}
|
|
214
214
|
|
|
215
215
|
runInterval(); // Start interval
|
|
216
|
-
`,c=new Blob([l],{type:"application/javascript"});He=new Worker(URL.createObjectURL(c)),He.onmessage=u=>{a.readyState===1&&a.send(JSON.stringify({action:"keepAlive"}));},i(a);},a.onmessage=async l=>{let c="";try{c=JSON.parse(decodeURI(l.data)),this.log("socket onmessage",c);}catch{return}let u;switch(!0){case !!c?.["#message"]:u="message";break;case !!c?.["#private"]:u="private";break;case !!c?.["#notice"]:u="notice";break;case !!c?.["#rtc"]:u="rtc";break;case !!c?.["#error"]:u="error";break}if(!u)return;let f={type:u,message:c?.["#rtc"]||c?.["#message"]||c?.["#private"]||c?.["#notice"]||c?.["#error"]||null,sender:c?.["#user_id"]||null,sender_cid:c?.["#scid"]?"cid:"+c["#scid"]:null,sender_rid:c?.["#srid"]||null,code:c?.["#code"]||null};if(u==="notice")t(f);else if(u==="rtc"){if(f.sender!==this.user.user_id){let d=f.message;if(d.hungup){Ae[f.sender_cid]&&(Ae[f.sender_cid](!1),delete Ae[f.sender_cid]),Ce[f.sender_cid]&&delete Ce[f.sender_cid],k?.[f.sender_cid]&&Se.bind(this)({cid:f.sender_cid}),f.type="rtc:closed",t(f);return}if(d.candidate&&pi.bind(this)(d.candidate,f.sender_cid),d.sdpoffer&&(hi.bind(this)(d.sdpoffer,f.sender_cid),Ce[f.sender_cid]||(Ce[f.sender_cid]=f.sender_cid,delete f.message,f.connectRTC=Ua.bind(this)(f),f.type="rtc:incoming",f.hangup=(()=>{k[f.sender_cid]?Se.bind(this)({cid:f.sender_cid}):Ce[f.sender_cid]&&(delete Ce[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),t(f))),d.pickup&&Ae[f.sender_cid]&&(Ae[f.sender_cid](!0),delete Ae[f.sender_cid]),d.sdpanswer&&k[f.sender_cid])if(k[f.sender_cid].signalingState==="have-local-offer")await k[f.sender_cid].setRemoteDescription(new RTCSessionDescription(d.sdpanswer));else throw new h("Invalid signaling state.",{code:"INVALID_REQUEST"})}}else t(f);},a.onclose=()=>{Ht?(this.log("realtime onclose","WebSocket connection closed."),t({type:"close",message:"WebSocket connection closed."})):(this.log("realtime onclose","WebSocket unexpected close."),t({type:"error",message:"Skapi: WebSocket unexpected close."}),wt++,wt<3?(this.log("realtime onclose","Reconnecting to WebSocket server..."+wt),t({type:"reconnect",message:"Reconnecting to WebSocket server..."+wt}),Et.bind(this)(t,3e3,"reconnect")):(this.log("realtime onclose","Max reconnection attempts reached."),t({type:"error",message:"Skapi: Max reconnection attempts reached."})));},a.onerror=()=>{this.log("realtime onerror","WebSocket connection error."),t({type:"error",message:"Skapi: WebSocket connection error."});};}catch(a){o(a);}},e);}),n.value=this.__socket,this.__socket}async function Da(t,e,r){if(typeof window>"u"||window._runningInNodeJS)throw new h("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});let n=this.__socket?await this.__socket:this.__socket;if(!n)throw new h("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});if(!e)throw new h("No recipient.",{code:"INVALID_REQUEST"});await yt.bind(this)(),t=j(t).data;let i="";if(r&&(r=b.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 h("Notification size exceeds 3kb.",{code:"INVALID_PARAMETER"});if(n.readyState===1){try{b.UserId(e),n.send(JSON.stringify({action:"sendMessage",uid:e,content:t,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}),qe!==e)throw new h(`User has not joined to the recipient group. Run joinRealtime({ group: "${e}" })`,{code:"INVALID_REQUEST"});n.send(JSON.stringify({action:"broadcast",rid:e,content:t,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 h("Realtime connection is not open. Try reconnecting with connectRealtime().",{code:"INVALID_REQUEST"})}async function At(t){if(typeof window>"u"||window._runningInNodeJS)throw new h("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});let e=this.__socket?await this.__socket:this.__socket;if(!e)throw new h("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});await yt.bind(this)(),t=j(t,{nullIfEmpty:true}).data;let{group:r=null}=t;if(!r&&!qe)return {type:"success",message:"Left realtime message group."};if(r!==null&&typeof r!="string")throw new h('"group" must be a string | null.',{code:"INVALID_PARAMETER"});return e.readyState===1&&e.send(JSON.stringify({action:"joinRoom",rid:r,token:this.session.accessToken.jwtToken})),qe=r,{type:"success",message:r?`Joined realtime message group: "${r}".`:"Left realtime message group."}}async function Na(t,e){t=b.Params(t,{user_id:n=>b.UserId(n,'User ID in "user_id"'),group:["string",()=>{if(!qe)throw new h('No group has been joined. Otherwise "group" is required.',{code:"INVALID_REQUEST"});return qe}]});let r=await I.bind(this)("get-ws-group",t,{fetchOptions:e,auth:true,method:"post"});return r.list=r.list.map(n=>({user_id:n.uid.split("#")[1],cid:"cid:"+n.cid})),r}async function Oa(t,e){if(await this.__connection,t||(t={searchFor:"group",value:" ",condition:">"}),t=b.Params(t,{searchFor:["group","number_of_users",()=>"group"],value:["string","number",()=>t?.searchFor&&t?.searchFor==="number_of_users"?0:" "],condition:[">",">=","=","<","<=","!=","gt","gte","eq","lt","lte","ne"],range:["string","number"]}),t.condition||(t.value===" "||!t.value?t.condition=">":t.condition="="),t.range&&t.condition&&delete t.condition,t.searchFor==="number_of_users"&&typeof t.value!="number")throw new h('"value" must be a number.',{code:"INVALID_PARAMETER"});if(t.searchFor==="group"&&typeof t.value!="string")throw new h('"value" must be a string.',{code:"INVALID_PARAMETER"});if(t.hasOwnProperty("range")&&typeof t.range!=typeof t.value)throw new h(`"range" must be a ${typeof t.value}.`,{code:"INVALID_PARAMETER"});let r=await I.bind(this)("get-ws-group",t,{fetchOptions:e,auth:true,method:"post"});return r.list=r.list.map(n=>({group:n.rid.split("#")[1],number_of_users:n.cnt})),r}var Fa=typeof FormData<"u",La=typeof HTMLFormElement<"u",Ma=typeof SubmitEvent<"u",ke={},Wt={},ue={};function Gt(t){return Object.freeze({id:t,status:"stopped"})}function qa(t){return !!t&&typeof t=="object"&&t.status==="stopped"}var Va=3;function Ba(t,e,r){let n=false,i=Array.isArray(t?.chunks)?t.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<=e.seq)&&(e.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 t?.last_seq=="number"&&t.last_seq>e.seq&&(e.seq=t.last_seq,n=true),n}var Nf=2e3,$a=5e3,Of=2e3,Ff=5,Lf=1500,Vr=null;function Ka(t,e,r){let n=new Map,i=false,s=false,o=0,a={socket:0,poll:0},l=(d,p,g)=>{if(t.seq=d,!(!e||typeof p!="string"||p===""))try{e(p,d,g);}catch(m){console.error(m);}},c=()=>{for(let d of Array.from(n.keys()))d<=t.seq&&n.delete(d);for(;;){let d=t.seq+1;if(!n.has(d))break;let p=n.get(d);n.delete(d),l(d,p.txt,p.via);}};return {cursor:t,open:()=>{i||s||(i=true,c());},fromPoll:d=>{if(s)return false;let p=t.seq,g=t.seq,m=Array.isArray(d?.chunks)?d.chunks:[];for(let w of m){if(!w||typeof w.seq!="number"||w.seq<=t.seq)continue;let _=!n.has(w.seq);_&&(a.poll++,r&&a.poll===1&&r("poll",w.seq)),n.set(w.seq,{txt:typeof w.txt=="string"?w.txt:"",via:_?"poll":n.get(w.seq).via}),w.seq>g&&(g=w.seq);}typeof d?.last_seq=="number"&&d.last_seq>g&&(g=d.last_seq);let y=Array.from(n.keys()).sort((w,_)=>w-_);for(let w of y){if(w<=t.seq){n.delete(w);continue}if(w>g)break;let _=n.get(w);n.delete(w),l(w,_.txt,_.via);}return g>t.seq&&(t.seq=g),c(),t.seq>p},fromSocket:(d,p)=>{s||typeof d!="number"||!Number.isFinite(d)||(o=Date.now(),!(d<=t.seq)&&(!n.has(d)&&n.size>=Of||(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&&c())));},warm:()=>o!==0&&Date.now()-o<Nf,stats:()=>({socket:a.socket,poll:a.poll}),close:()=>{s=true,n.clear();}}}function ja(t){if(!this||!this.__network_logs)return {onTransport:void 0,done:()=>{}};let e=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:t,first_seq:i,after_ms:Date.now()-e});},done:n=>{if(r||!n)return;r=true;let i=n.stats();console.log("%cSKAPI: stream transport","color: blue;",{id:t,over_websocket:i.socket,over_poll:i.poll,took_ms:Date.now()-e});}}}function Ha(t,e){let r={stop:()=>{}};if(typeof window>"u"||window._runningInNodeJS||Vr)return r;let n={stopped:false,socket:null,opened:null,joined:false,attempts:0,unavailable:false};Vr=n;let i=c=>{if(n.stopped)return;let u=c?.data;if(typeof u!="string")return;let f=null;try{f=JSON.parse(u);}catch{try{f=JSON.parse(decodeURI(u));}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!==t)return;let g=d.seq;typeof g=="string"&&g!==""&&(g=Number(g)),e.fromSocket(g,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 c=n.opened,u=n.joined;if(n.opened=null,n.joined=false,s(),!(!u&&!c))try{let f=this.__socket?await this.__socket:null;if(c&&f===c){await qr.bind(this)();return}u&&f&&ka()===room&&await At.bind(this)({group:null});}catch{}},a=()=>{n.stopped||(s(),!n.unavailable&&(n.attempts>=Ff||(n.attempts+=1,setTimeout(()=>{n.stopped||l();},Lf))));},l=async()=>{try{let c=this.__socket?await this.__socket:null;if(n.stopped){o();return}if(!c){if(!this.session){n.unavailable=!0,o();return}if(await Et.bind(this)(()=>{},0),c=this.__socket?await this.__socket:null,n.stopped){o();return}c&&!n.opened&&(n.opened=c);}if(!c||c.readyState!==1)return;if(c.addEventListener("message",i),c.addEventListener("close",a),n.socket=c,!n.joined&&(await At.bind(this)({group:t}),n.joined=!0,n.stopped)){o();return}}catch{}};return l(),{stop:()=>{n.stopped||(n.stopped=true,Vr===n&&(Vr=null),o());}}}function Wa(t){return t?.status==="running"||t?.status==="pending"}function Mf(t){return !!t&&typeof t=="object"&&!Array.isArray(t)&&typeof t.status=="string"&&typeof t.id=="string"&&"in_queue"in t}function Ga(t,e,r,n){if(!t||typeof t!="string")throw new h('"requestId" should be type: <string>.',{code:"INVALID_PARAMETER"});if(t.includes("#"))return t;if(!e||typeof e!="string"||!r||typeof r!="string")throw new h('"url" and "method" are required to address a request by its short id.',{code:"INVALID_PARAMETER"});return b.Url(e),`[${r.toUpperCase()}]${e.toLowerCase()}#${n}:${t}`}function Ja({id:t,auth:e,service:r,owner:n,latency:i=1e3,queue:s,onResponse:o,onError:a,onStream:l,realtimeGroup:c}){if(typeof i!="number")throw new h('"latency" should be a number.',{code:"INVALID_PARAMETER"});if(i<0)throw new h('"latency" should be a non-negative number.',{code:"INVALID_PARAMETER"});s&&!ke?.[s]&&(ke[s]=new qt({breakWhenError:false,batchSize:1}));let u={stop:null,aborted:false,queue:s};ue[t]=u;let f=null,d=()=>{ue[t]===u&&delete ue[t];},p=()=>new Promise((m,y)=>{let w=false;if(u.aborted){d(),m(Gt(t));return}let _={seq:0},A=ja.call(this,t),S=l&&c?Ka(_,l,A.onTransport):null,T=S?Ha.call(this,c,S):null,N=()=>{A.done(S),T&&T.stop(),S&&S.close();};f=N;let F=0,C=false,x=0,O=async()=>{if(!(w||C)&&!(S&&S.warm()&&Date.now()-F<$a)){C=true;try{for(;;){let M={id:t,service:r,owner:n};l&&(M.since=_.seq),F=Date.now();let J=await I.bind(this)("csr-poll",M,{auth:e});if(w)return;let ve=S?S.fromPoll(J):l?Ba(J,_,l):!1;S&&S.open();let $=Wa(J);if(J?.more&&ve){x=0;continue}if($){x=0;return}if(x=J?.more?x+1:0,J?.more&&x<Va)return;w=!0,o&&o(J),clearInterval(L),N(),d(),m(J);return}}catch(M){if(w)return;w=true,a&&a(M),clearInterval(L),N(),d(),y(M);}finally{C=false;}}},L=setInterval(O,i);S&&O(),u.stop=()=>{w||(w=true,clearInterval(L),N(),d(),m(Gt(t)));};}),g=()=>{let m=ue[t];m&&(m.stop?m.stop():(m.aborted=true,delete ue[t]));};if(s){let m=new Promise((y,w)=>{let _=false,A=ke[s].add([async()=>{try{let S=await p();return _||(_=!0,y(S)),S}catch(S){throw _||(_=true,w(S)),S}}])[0];Wt[t]=A,u.stop=()=>{if(!_){u.aborted=true,f&&f();try{ke[s]&&ke[s].remove(Wt[t]);}catch{}delete Wt[t],d(),_=true,y(Gt(t));}};});return Object.assign(m,{stop:g})}else return Object.assign(p(),{stop:g})}function Ya(t){let e=0,r=[];if(t?.id){if(t.url&&t.method){let n=t.service||this.service;r.push(`[${t.method.toUpperCase()}]${t.url.toLowerCase()}#${n}:${t.id}`);}r.push(t.id);}else if(t?.queue)for(let n in ue)ue[n]?.queue===t.queue&&r.push(n);else for(let n in ue)r.push(n);for(let n of r){let i=ue[n];i&&(i.stop?i.stop():(i.aborted=true,delete ue[n]),e+=1);}return e}function za(t,e){if(!t.queue)throw new h('"queue" is required.',{code:"INVALID_PARAMETER"});let r={service:t.service||this.service,owner:t.owner||this.owner,queue:t.queue+":"};return I.bind(this)("csr-poll",r,{auth:true})}async function Qa(t){let e=false;if(typeof t.poll=="number"&&t.poll<0)throw new h('"poll" should be a non-negative number.',{code:"INVALID_PARAMETER"});let r=t?.onResponse,n=t?.onError,i=t?.onStream,s=typeof t.poll=="number"?t.poll:t.poll?1e3:0;delete t.poll,(s||t.stream)&&!t.queue&&(t.queue=(this.__user?.user_id||"anonymous")+"-"+Ye());let o=c=>{for(let u in c)if(typeof c[u]=="string"&&c[u].includes("$CLIENT_SECRET")){e=true;break}};if(t=b.Params(t,{url:c=>{if(!c||typeof c!="string")throw new h('"url" should be type: <string>.',{code:"INVALID_PARAMETER"});return b.Url(c),c.includes("$CLIENT_SECRET")&&(e=true),c},clientSecretName:"string",method:c=>{if(c&&typeof c!="string")throw new h('"method" should be either "GET" or "POST" or "DELETE" or "PUT".',{code:"INVALID_PARAMETER"});let u=c.toLowerCase();if(u!=="get"&&u!=="post"&&u!=="delete"&&u!=="put")throw new h('"method" should be either "GET" or "POST" or "DELETE" or "PUT".',{code:"INVALID_PARAMETER"});return u},stream:c=>{if(c!=null&&typeof c!="boolean")throw new h('"stream" should be type: <boolean>.',{code:"INVALID_PARAMETER"});return !!c},realtime:c=>{if(c!=null&&typeof c!="boolean")throw new h('"realtime" should be type: <boolean>.',{code:"INVALID_PARAMETER"});return !!c},headers:c=>{if(c&&typeof c!="object")throw new h('"headers" should be type: <object>.',{code:"INVALID_PARAMETER"});return o(c),c},data:c=>{if(c&&typeof c!="object")throw new h('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return o(c),c},params:c=>{if(c&&typeof c!="object")throw new h('"params" should be type: <object>.',{code:"INVALID_PARAMETER"});return o(c),c},expires:"number",queue:"string"},["clientSecretName","method","url"]),t.realtime&&!t.stream)throw new h('"realtime" requires "stream": true.',{code:"INVALID_PARAMETER"});if(!e)throw new h(`At least one parameter value should include "$CLIENT_SECRET" in ${t.method.toLowerCase()==="post"?'"data"':'"params"'} or "headers".`,{code:"INVALID_PARAMETER"});await this.__connection;let a=!!this.__user,l=()=>I.bind(this)("csr",t,{auth:a,tokenHeaders:{accessToken:!!a}}).then(c=>{if(c.status==="running"||c.status==="pending"){let u=`[${t.method.toUpperCase()}]${t.url.toLowerCase()}`,f=t.service||this.service,d=t.owner||this.owner,p=`${u}#${f}:${c.id}`;Object.assign(c,{poll:g=>Ja.call(this,{id:p,auth:a,service:f,owner:d,latency:g?.latency||1e3,queue:t?.queue,onResponse:r,onError:n,onStream:g?.onStream||i,realtimeGroup:c?.realtime_group})});}return r?r(c):c}).catch(c=>{if(n)return n(c);throw c});if(t?.queue){let c="base:"+t.queue;return ke?.[c]||(ke[c]=new qt({breakWhenError:false,batchSize:1})),new Promise((u,f)=>{ke[c].add([async()=>{try{let d=await l();if(s>0){let p=d.poll({latency:s});return u(p),p}return u(d),d}catch(d){throw f(d),d}}]);})}else return l()}async function Xa(t,e){await this.__connection;let r=t.service||this.service,n=t.owner||this.owner;t=b.Params(t,{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=`[${t.method.toUpperCase()}]${t.url.toLowerCase()}#${r}:`,o={id:s,queue:t?.queue,status:t?.status,service:r,owner:n};t?.compact&&(o.compact=true),t?.queue_exact&&(o.queue_exact=true),t?.queue_exclude&&(o.queue_exclude=t.queue_exclude),Object.keys(o).forEach(l=>{o[l]||delete o[l];}),o.queue&&(o.id_prefix=o.id,delete o.id);let a=await I.bind(this)("csr-poll",o,{auth:i,fetchOptions:e});return a.list=a.list.map(l=>{let c={id:l.id,status_code:l.rslv?.status_code||null,response_body:l.rslv?.body||l.rslv?.truncated||null,error:l?.err,created:l?.stmp,updated:l?.utmp,request_body:l?.reqbdy,expires:l?.expt,status:l.stts,queue_name:l?.qid,request_text:l?.reqtxt,response_text:l?.rslvtxt,response_complete_marker:l?.rslvmk!=null?!!l.rslvmk:void 0,compact:l?.cmpct?true:void 0};for(let u in c)c[u]===void 0&&delete c[u];return (c.status==="running"||c.status==="pending")&&(c.poll=u=>Ja.call(this,{id:s+c.id,auth:i,service:r,owner:n,latency:u?.latency||1e3,queue:l?.qid,onResponse:u?.onResponse,onError:u?.onError,onStream:u?.onStream})),c}),a}async function Za(t){await this.__connection,t=b.Params(t,{url:"string",method:["GET","POST","DELETE","PUT"],id:"string",queue:"string"},["url","method","id"]);let e=t?.service||this.service,r=t?.owner||this.owner,n=!!this.__user,i=`[${t.method.toUpperCase()}]${t.url.toLowerCase()}#${e}`,s=t.id,o=`${i}:${s}`,a=t?.queue;return a&&ke?.[a]&&(ke[a].remove(Wt[o]),delete Wt[o]),I.bind(this)("csr-cancel",{id:o,service:e,owner:r},{auth:n})}function ec(t,e){let r=typeof e?.poll=="number"?e.poll:1e3;if(!Number.isFinite(r)||r<0)throw new h('"poll" should be a non-negative number.',{code:"INVALID_PARAMETER"});if(!t||typeof t!="string")throw new h('"requestId" should be type: <string>.',{code:"INVALID_PARAMETER"});if(e?.since!==void 0&&typeof e.since!="number")throw new h('"since" should be a number.',{code:"INVALID_PARAMETER"});if(e?.realtimeGroup!==void 0&&e.realtimeGroup!==null&&typeof e.realtimeGroup!="string")throw new h('"realtimeGroup" should be type: <string>.',{code:"INVALID_PARAMETER"});let n=typeof e?.since=="number"&&e.since>0?e.since:0,i=e?.onStream,s=e?.onResponse,o=e?.onError,a={stopped:false,fullId:t,resolve:null},l=null,c={stop:null,aborted:false},u=()=>{ue[a.fullId]===c&&delete ue[a.fullId];},f=()=>{a.stopped||(a.stopped=true,l&&l(),u(),a.resolve&&a.resolve(Gt(a.fullId)));};c.stop=f;let d=new Promise(async(p,g)=>{a.resolve=p;try{await this.__connection;let m=!!this.__user,y=e?.service||this.service,w=e?.owner||this.owner;if(a.fullId=Ga(t,e?.url,e?.method,y),a.stopped){p(Gt(a.fullId));return}ue[a.fullId]=c;let _={seq:n},A=0,S=ja.call(this,a.fullId),T=i&&e?.realtimeGroup?Ka(_,i,S.onTransport):null,N=T?Ha.call(this,e.realtimeGroup,T):null,F=()=>{S.done(T),N&&N.stop(),T&&T.close();};for(l=F;;){let C=await I.bind(this)("csr-poll",{id:a.fullId,service:y,owner:w,since:_.seq},{auth:m});if(a.stopped)return;if(!Mf(C)){F(),u(),s&&s(C),p(C);return}let x=T?T.fromPoll(C):Ba(C,_,i);T&&T.open();let O=Wa(C);if(C.more&&x){A=0;continue}if(A=C.more?A+1:0,!O&&(!C.more||A>=Va)){F(),u(),s&&s(C),p(C);return}if(await new Promise(L=>setTimeout(L,T&&T.warm()?Math.max(r,$a):r)),a.stopped)return}}catch(m){if(a.stopped)return;l&&l(),u(),o&&o(m),g(m);}});return Object.assign(d,{stop:f})}async function tc(t,e,r){await this.__connection;let n=r?.service||this.service,i=r?.owner||this.owner,s=!!this.__user,o=Ga(t,r?.url,r?.method,n);return I.bind(this)("csr-finalize",{id:o,data:e,service:n,owner:i},{auth:s})}async function rc(t){await this.__connection;let e={name:"string",email:r=>(b.Email(r),r),subject:"string",message:"string"};return t=b.Params(t,e,["name","email","subject","message"]),await I.bind(this)("send-inquiry",t),"SUCCESS: Inquiry has been sent."}async function nc(t,e){if(await this.__connection,Fa&&t instanceof FormData||La&&t instanceof HTMLFormElement||Ma&&t instanceof SubmitEvent){if(!e)throw new h("Url string as a second argument is required when form is passed.",{code:"INVALID_PARAMETER"});let n=j(t);t={url:e,data:n.data,sync:true};}let r={url:n=>b.Url(n),data:n=>n,sync:["boolean",()=>true]};if(Array.isArray(t))for(let n of t)n=b.Params(n,r);else t=b.Params(t,r);return I.bind(this)("post-secure",t,{auth:true})}async function ic(t,e){await this.__connection;let{auth:r=false,method:n="POST",bypassAwaitConnection:i=false,responseType:s,contentType:o,tokenHeaders:a,progress:l}=e||{};if(e=Object.assign({auth:r,method:n,bypassAwaitConnection:i,responseType:s,contentType:o,tokenHeaders:a},{fetchOptions:{progress:l}}),typeof t!="object"&&(o==="application/json"||o===void 0))throw new h('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return I.bind(this)("mock",t,e)}async function sc(t,e){if(await this.__connection,!e?.url||typeof e.url!="string")throw new h('"url" is required in the second argument.',{code:"INVALID_PARAMETER"});b.Url(e.url);let n=(await this.admin_endpoint)?.forward_request;if(!n)throw new h("forwardRequest is not available on this service region yet.",{code:"NOT_EXISTS"});let i=null,s=null,o=Ma&&t instanceof SubmitEvent?t.target:La&&t instanceof HTMLFormElement?t:null;o?i=new FormData(o):Fa&&t instanceof FormData?i=t:t!=null&&(i=JSON.stringify(t),s="application/json");let a={public_identifier:this.__public_identifier,service:this.service,owner:this.owner,forward:{url:e.url,method:e.method||"POST",headers:e.headers||{},apiKeyHeader:e.apiKeyHeader,apiKeyScheme:e.apiKeyScheme}},l=JSON.stringify(a).replace(/[\u007f-\uffff]/g,p=>"\\u"+p.charCodeAt(0).toString(16).padStart(4,"0"));if(l.length>4096)throw new h("Destination url and headers are too large for Content-Meta.",{code:"INVALID_PARAMETER"});let c=this.bearerToken||this.session?.idToken?.jwtToken||null;if(!c)throw new h("User login is required.",{code:"INVALID_REQUEST"});let u={"Content-Meta":l,Authorization:c};s&&(u["Content-Type"]=s);let f=await fetch(n,{method:"POST",headers:u,body:i,signal:e.signal});if(e.responseType==="response")return f;if(!f.ok){let p=await f.text();try{p=JSON.parse(p);}catch{}throw new h(p?.message||(typeof p=="string"?p:JSON.stringify(p)),{code:p?.code||"ERROR"})}if(e.onStream&&f.body){let p=f.body.getReader(),g=new TextDecoder,m="";for(;;){let{done:y,value:w}=await p.read();if(y)break;let _=g.decode(w,{stream:true});m+=_;try{e.onStream(_);}catch(A){console.error(A);}}return m}let d=await f.text();if(e.responseType==="text")return d;try{return JSON.parse(d)}catch{return d}}async function oc(t,e){await this.__connection,t=b.Params(t||{},{access_group:n=>{if(n==="authorized"&&(n=1),n==="public"&&(n=0),typeof n!="number")throw new h('"access_group" should be type number.',{code:"INVALID_PARAMETER"});if(n<0)throw new h('"access_group" should be zero or a positive number.',{code:"INVALID_PARAMETER"});if(n>this.__user.access_group)throw new h("User has no access.",{code:"INVALID_REQUEST"});return n}});let r=await I.bind(this)("get-feed",t,{auth:true,fetchOptions:e});for(let n in r.list)r.list[n]=await Ze.bind(this)(r.list[n]);return r}function Jt(t){if(t===this.__user.user_id)throw new h(`"user_id" cannot be the user's own ID.`,{code:"INVALID_PARAMETER"});return b.UserId(t,'"user_id"')}async function ac(t,e){if(t=j(t,{ignoreEmpty:true}).data,t=b.Params(t,{subscriber:n=>b.UserId(n,'User ID in "subscriber"'),subscription:Jt.bind(this),blocked:"boolean"}),!t.subscriber&&!t.subscription)throw new h('At least either "subscriber" or "subscription" should have a value.',{code:"INVALID_PARAMETER"});let r=await I.bind(this)("get-subscription",t,Object.assign({auth:true},{fetchOptions:e}));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 cc(t){await this.__connection,t=b.Params(t,{user_id:Jt.bind(this),get_feed:["boolean",()=>false],get_notified:["boolean",()=>false],get_email:n=>{if(n&&!this.__user.email||!this.__user.email_verified)throw new h("User has no verified email address.",{code:"INVALID_REQUEST"});return !!n}},["user_id"]);let e=await I.bind(this)("subscription",{subscribe:t.user_id,option:{get_feed:t.get_feed,get_notified:t.get_notified,get_email:t.get_email||false}},{auth:true}),r={};if(e.sub){let n=e.sub.split("#");r.subscriber=n[2],r.subscription=n[0];}else r.subscriber=e.subscriber,r.subscription=e.subscription;return r.timestamp=e?.timestamp||e.stmp,r.blocked=e?.blocked||e.grp.substring(0,1)==="N",Object.assign(r,e.opt),r}async function lc(t){await this.__connection;let{user_id:e}=b.Params(t,{user_id:Jt.bind(this)},["user_id"]);return await I.bind(this)("subscription",{unsubscribe:e},{auth:true})}async function uc(t){await this.__connection;let{user_id:e}=b.Params(t,{user_id:Jt.bind(this)},["user_id"]);return await I.bind(this)("subscription",{block:e},{auth:true})}async function dc(t){await this.__connection;let{user_id:e}=b.Params(t,{user_id:Jt.bind(this)},["user_id"]);return await I.bind(this)("subscription",{unblock:e},{auth:true})}async function fc(t,e){await this.__connection;let r=await Z.bind(this)();t=b.Params(t||{},{user_id:o=>{if(o!==this.__user.user_id&&!r)throw new h("No access.",{code:"INVALID_REQUEST"});return o},group:o=>b.newsletterGroup(o,{allowNull:true})});let n=await I.bind(this)("get-newsletter-subscription",t,{auth:true,fetchOptions:e||null}),i=n?.list||n,s=[];Array.isArray(i)||(i=[]);for(let o of i){let a=o.subt.split("#"),l=true;a[0].charAt(0)==="@"&&(l=false,a[0]=a[0].substring(1));let c=/^\d+$/.test(a[0])?parseInt(a[0]):a[0];s.push({timestamp:o.stmp,group:c,subscribed_email:a[1],active:l});}return n?.list?(n.list=s,n):s}async function hc(t){await this.__connection;let e=b.Params(t||{},{email:r=>Array.isArray(r)&&r.length>0?r.length===1?b.Email(r[0]):r.map(n=>b.Email(n)):b.Email(r),group:r=>b.newsletterGroup(r),redirect:r=>b.Url(r)},this.__user?["group"]:["email","group"]);return I.bind(this)(`subscribe-${this.__user?"":"public-"}newsletter`,e,{auth:!!this.__user})}async function pc(t){await this.__connection;let e=b.Params(t||{},{group:r=>b.newsletterGroup(r,{nameOnly:true}),restriction:r=>{if(typeof r!="number"||!Number.isInteger(r)||r<0||r>99)throw new h('"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 h('"name" should be a string of 60 characters or less.',{code:"INVALID_PARAMETER"});return r}},["group"]);return I.bind(this)("register-newsletter-group",e,{auth:true})}async function gc(t){await this.__connection;let e=b.Params(t||{},{group:r=>b.newsletterGroup(r,{nameOnly:true})},["group"]);return I.bind(this)("delete-newsletter-group",e,{auth:true})}async function mc(){return await this.__connection,I.bind(this)("newsletter-group-endpoint",null,{auth:true})}async function yc(t){await this.__connection,t=b.Params(t,{group:r=>b.newsletterGroup(r,{allowNull:true})},["group"]);let e=Object.assign({action:"unsubscribe"},t);return I.bind(this)("subscribe-newsletter",e,{auth:true})}async function _c(t,e){let r=await Z.bind(this)(),n={message_id:"string",timestamp:"number",read:"number",complaint:"number",subject:"string",bounced:"number"};t||(e=Object.assign({ascending:false},e||{})),t=j(t).data,t=t||{searchFor:"timestamp",value:Date.now(),condition:"<",group:"public"},t=b.Params(t,{searchFor:["message_id","timestamp","subject","complaint","read","bounced"],value:l=>{if(typeof l!==n[t.searchFor])throw new h(`"value" type does not match the type of "${t.searchFor}" index.`,{code:"INVALID_PARAMETER"});if(typeof l=="string"&&!l)throw new h('"value" should not be empty string.',{code:"INVALID_PARAMETER"});return l},range:l=>{if(!t.hasOwnProperty("value")||typeof l!=typeof t.value)throw new h('"range" should match type of "value".',{code:"INVALID_PARAMETER"});return l},condition:[">",">=","=","<","<=","gt","gte","eq","lt","lte",()=>"="],group:l=>{let c=b.newsletterGroup(l);if(c===0)return 0;if(typeof c=="string")return c;if(!this.session)throw new h("User should be logged in.",{code:"INVALID_REQUEST"});if(l==="authorized")return 1;if(!r&&c>parseInt(this.user?.access_group||this.session?.idToken?.payload?.access_group))throw new h("User has no access.",{code:"INVALID_REQUEST"});return c}},["searchFor","value","group"]);let i=t.group===0||typeof t.group=="string"&&!this.__user?"get-public-newsletters":"get-newsletters",s=await I.bind(this)(i,t,Object.assign({method:"get",auth:i==="get-public-newsletters"?!!this.__user:true},{fetchOptions:e})),o={message_id:"mid",timestamp:"stmp",complaint:"cmpl",read:"read",subject:"subj",bounced:"bnce",url:"url",delivered:"delv",group:"grp"},a={message_id:"",timestamp:0,complaint:0,read:0,subject:"",bounced:"",url:"",delivered:0,group:t.group};return s.list=s.list.map(l=>{let c={};for(let u in o)c[u]=l[o[u]]||a[u];return c.bounced=String(c.bounced),c}),s}async function bc(t){let e=b.Params(t,{user_id:n=>b.UserId(n,'"user_id"')},["user_id"]);if(e?.service&&e?.owner?e={service:e?.service,owner:e?.owner,block:e.user_id}:e={block:e.user_id},!await Z.bind(this)()){if(!this.__user)throw new h("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new h("Invalid access.",{code:"INVALID_REQUEST"})}return await I.bind(this)("block-account",e,{auth:true})}async function wc(t){let e=b.Params(t,{user_id:n=>b.UserId(n,'"user_id"')},["user_id"]);if(e?.service&&e?.owner?e={service:e?.service,owner:e?.owner,unblock:e.user_id}:e={unblock:e.user_id},!await Z.bind(this)()){if(!this.__user)throw new h("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new h("Invalid access.",{code:"INVALID_REQUEST"})}return await I.bind(this)("block-account",e,{auth:true})}async function Ec(t){let e=b.Params(t,{user_id:n=>b.UserId(n,'"user_id"')},["user_id"]);if(e?.service&&e?.owner?e={service:e?.service,owner:e?.owner,delete:e.user_id}:e={delete:e.user_id},!await Z.bind(this)()){if(!this.__user)throw new h("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new h("Invalid access.",{code:"INVALID_REQUEST"})}return await I.bind(this)("remove-account",e,{auth:true})}async function Ac(t,e){let r={email:s=>b.Email(s),password:s=>b.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=>b.Birthdate(s),phone_number:s=>b.PhoneNumber(s),picture:s=>{if(s)return b.Url(s)},profile:s=>{if(s)return b.Url(s)},website:s=>{if(s)return b.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 h('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof s!="number"||s<1||s>100)throw new h('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"});return s}},n=b.Params(t,r,["email"]);if(e=b.Params(e,{confirmation_url:s=>{let o=s;if(typeof s=="string")o=b.Url(s);else throw new h('"options.confirmation_url" should be type: <string>.',{code:"INVALID_PARAMETER"});if(o&&!n.email)throw new h('"email" is required for signup confirmation.',{code:"INVALID_PARAMETER"});return o},email_subscription:s=>{if(typeof s!="boolean")throw new h('"options.email_subscription" should be type: <boolean>.',{code:"INVALID_PARAMETER"});if(!e?.confirmation_url)throw new h('"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 h('"options.template" should be type: <object> with "url" and "subject".',{code:"INVALID_PARAMETER"});return {url:b.Url(s.url),subject:s.subject}}}),n.signup_confirmation=e?.confirmation_url||true,n.email_subscription=e?.email_subscription||false,n.template=e?.template||{},!await Z.bind(this)()){if(!this.__user)throw new h("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new h("Invalid access.",{code:"INVALID_REQUEST"})}return await I.bind(this)("admin-signup",n,{auth:true})}async function Sc(t){let e={email:s=>b.Email(s),password:s=>b.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=>b.Birthdate(s),phone_number:s=>b.PhoneNumber(s),picture:s=>s?b.Url(s):"",profile:s=>s?b.Url(s):"",website:s=>s?b.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 h('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof s!="number"||s<1||s>100)throw new h('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"});return s}},r=["email","password"],n=b.Params(t,e,r);if(!await Z.bind(this)()){if(!this.__user)throw new h("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new h("Invalid access.",{code:"INVALID_REQUEST"})}return await I.bind(this)("admin-signup",n,{auth:true})}async function vc(t){if(t=b.Params(t,{user_id:r=>b.UserId(r,'"user_id"'),access_group:r=>{try{typeof r=="string"&&(r=parseInt(r));}catch{throw new h('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof r=="number"&&r>0&&r<100)return r;throw new h('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"})}},["user_id","access_group"]),!await Z.bind(this)()){if(!this.__user)throw new h("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new h("Invalid access.",{code:"INVALID_REQUEST"})}return await I.bind(this)("grant-access",t,{auth:true})}async function Rc(t,e){if(t=b.Params(t,{email:"string"}),!await Z.bind(this)()){if(!this.__user)throw new h("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new h("Invalid access.",{code:"INVALID_REQUEST"})}let n=await I.bind(this)("invitation-list",Object.assign({mode:"search"},t),{fetchOptions:e,auth:true});return n.list=n.list.map(i=>Tt(i.user)),n}async function Tc(t){if(t=b.Params(t,{email:r=>b.Email(r)},["email"]),!await Z.bind(this)()){if(!this.__user)throw new h("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new h("Invalid access.",{code:"INVALID_REQUEST"})}return await I.bind(this)("invitation-list",Object.assign({mode:"cancel"},t),{auth:true})}async function Ic(t){if(t=b.Params(t,{email:r=>b.Email(r)},["email"]),!await Z.bind(this)()){if(!this.__user)throw new h("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new h("Invalid access.",{code:"INVALID_REQUEST"})}return await I.bind(this)("invitation-list",Object.assign({mode:"resend"},t),{auth:true})}async function Pc(t){let e=b.Params(t,{user_id:o=>b.UserId(o,'"user_id"'),email:o=>b.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?b.Birthdate(o):"",phone_number:o=>o?b.PhoneNumber(o):"",email_public:"boolean",phone_number_public:"boolean",address_public:"boolean",gender_public:"boolean",birthdate_public:"boolean",misc:"string",picture:o=>o?b.Url(o):"",profile:o=>o?b.Url(o):"",nickname:"string",website:o=>o?b.Url(o):""},["user_id"]),r=e.service,n=e.owner;if(delete e.service,delete e.owner,Object.keys(e).filter(o=>o!=="user_id"&&e[o]!==void 0).length===0)throw new h("At least one attribute to update is required.",{code:"INVALID_PARAMETER"});if(!await Z.bind(this)()){if(!this.__user)throw new h("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new h("Invalid access.",{code:"INVALID_REQUEST"})}e.email&&(e.preferred_username=(r||this.service)+"-"+X.hash(e.email));let s={attributes:e};return r&&n&&(s.service=r,s.owner=n),await I.bind(this)("admin-edit-profile",s,{auth:true})}async function Uc(t){if(typeof window>"u"||window._runningInNodeJS)throw new h("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.__connection,!t.endpoint)throw new h("Missing parameter: endpoint",{code:"INVALID_PARAMETER"});if(!t.keys||!t.keys.p256dh||!t.keys.auth)throw new h("Missing parameter: keys.p256dh or keys.auth",{code:"INVALID_PARAMETER"});return await I.bind(this)("store-subscription",{endpoint:t.endpoint,keys:t.keys},{auth:true}),"SUCCESS: Subscribed to receive notifications."}async function xc(t){if(typeof window>"u"||window._runningInNodeJS)throw new h("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.__connection,!t.endpoint)throw new h("Missing parameter: endpoint",{code:"INVALID_PARAMETER"});if(!t.keys||!t.keys.p256dh||!t.keys.auth)throw new h("Missing parameter: keys.p256dh or keys.auth",{code:"INVALID_PARAMETER"});return await I.bind(this)("delete-subscription",{endpoint:t.endpoint,keys:t.keys},{auth:true}),"SUCCESS: Unsubscribed from notifications."}async function Cc(){if(typeof window>"u"||window._runningInNodeJS)throw new h("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});return await this.__connection,{VAPIDPublicKey:await I.bind(this)("get-vapid-public-key",null,{auth:true})}}async function kc(t,e){if(typeof window>"u"||window._runningInNodeJS)throw new h("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});await this.__connection;let{title:r,body:n}=j(t||{},{nullIfEmpty:true}).data;if(!r)throw new h("Missing parameter: message title",{code:"INVALID_PARAMETER"});if(!n)throw new h("Missing parameter: message body",{code:"INVALID_PARAMETER"});let i={title:r,body:n};return e?(typeof e=="string"&&(e=[e]),i.user_ids=e):i.user_ids="all_users",await I.bind(this)("push-notification",i,{auth:true}),"SUCCESS: Notification sent."}async function Dc(t){await this.__connection,t=b.Params(t,{spell:"string",name:"string",magic:r=>r},["spell","name"]);await I.bind(this)("castspell",t);return `The spell "${t.spell}" has been cast.`}async function Nc(t){return await this.__connection,t=b.Params(t||{},{search:["spell","name",()=>"spell"],value:"string"}),await I.bind(this)("getspell",t)}async function Oc(t){await this.__connection,t=b.Params(t,{message:"string",name:"string"},["message","name"]);let e=await I.bind(this)("dopamine",t,{auth:true}),r=e?.previous_message?.message,n=e?.previous_message?.name;if(oe())r&&n&&window.alert(`${n} said: ${r}`),window.location.href=e.video;else return r&&n?`${n} said: ${r}
|
|
216
|
+
`,c=new Blob([l],{type:"application/javascript"});He=new Worker(URL.createObjectURL(c)),He.onmessage=u=>{a.readyState===1&&a.send(JSON.stringify({action:"keepAlive"}));},i(a);},a.onmessage=async l=>{let c="";try{c=JSON.parse(decodeURI(l.data)),this.log("socket onmessage",c);}catch{return}let u;switch(!0){case !!c?.["#message"]:u="message";break;case !!c?.["#private"]:u="private";break;case !!c?.["#notice"]:u="notice";break;case !!c?.["#rtc"]:u="rtc";break;case !!c?.["#error"]:u="error";break}if(!u)return;let f={type:u,message:c?.["#rtc"]||c?.["#message"]||c?.["#private"]||c?.["#notice"]||c?.["#error"]||null,sender:c?.["#user_id"]||null,sender_cid:c?.["#scid"]?"cid:"+c["#scid"]:null,sender_rid:c?.["#srid"]||null,code:c?.["#code"]||null};if(u==="notice")t(f);else if(u==="rtc"){if(f.sender!==this.user.user_id){let d=f.message;if(d.hungup){Ae[f.sender_cid]&&(Ae[f.sender_cid](!1),delete Ae[f.sender_cid]),Ce[f.sender_cid]&&delete Ce[f.sender_cid],k?.[f.sender_cid]&&Se.bind(this)({cid:f.sender_cid}),f.type="rtc:closed",t(f);return}if(d.candidate&&pi.bind(this)(d.candidate,f.sender_cid),d.sdpoffer&&(hi.bind(this)(d.sdpoffer,f.sender_cid),Ce[f.sender_cid]||(Ce[f.sender_cid]=f.sender_cid,delete f.message,f.connectRTC=Ua.bind(this)(f),f.type="rtc:incoming",f.hangup=(()=>{k[f.sender_cid]?Se.bind(this)({cid:f.sender_cid}):Ce[f.sender_cid]&&(delete Ce[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),t(f))),d.pickup&&Ae[f.sender_cid]&&(Ae[f.sender_cid](!0),delete Ae[f.sender_cid]),d.sdpanswer&&k[f.sender_cid])if(k[f.sender_cid].signalingState==="have-local-offer")await k[f.sender_cid].setRemoteDescription(new RTCSessionDescription(d.sdpanswer));else throw new h("Invalid signaling state.",{code:"INVALID_REQUEST"})}}else t(f);},a.onclose=()=>{Ht?(this.log("realtime onclose","WebSocket connection closed."),t({type:"close",message:"WebSocket connection closed."})):(this.log("realtime onclose","WebSocket unexpected close."),t({type:"error",message:"Skapi: WebSocket unexpected close."}),wt++,wt<3?(this.log("realtime onclose","Reconnecting to WebSocket server..."+wt),t({type:"reconnect",message:"Reconnecting to WebSocket server..."+wt}),Et.bind(this)(t,3e3,"reconnect")):(this.log("realtime onclose","Max reconnection attempts reached."),t({type:"error",message:"Skapi: Max reconnection attempts reached."})));},a.onerror=()=>{this.log("realtime onerror","WebSocket connection error."),t({type:"error",message:"Skapi: WebSocket connection error."});};}catch(a){o(a);}},e);}),n.value=this.__socket,this.__socket}async function Da(t,e,r){if(typeof window>"u"||window._runningInNodeJS)throw new h("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});let n=this.__socket?await this.__socket:this.__socket;if(!n)throw new h("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});if(!e)throw new h("No recipient.",{code:"INVALID_REQUEST"});await yt.bind(this)(),t=j(t).data;let i="";if(r&&(r=b.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 h("Notification size exceeds 3kb.",{code:"INVALID_PARAMETER"});if(n.readyState===1){try{b.UserId(e),n.send(JSON.stringify({action:"sendMessage",uid:e,content:t,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}),qe!==e)throw new h(`User has not joined to the recipient group. Run joinRealtime({ group: "${e}" })`,{code:"INVALID_REQUEST"});n.send(JSON.stringify({action:"broadcast",rid:e,content:t,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 h("Realtime connection is not open. Try reconnecting with connectRealtime().",{code:"INVALID_REQUEST"})}async function At(t){if(typeof window>"u"||window._runningInNodeJS)throw new h("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});let e=this.__socket?await this.__socket:this.__socket;if(!e)throw new h("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});await yt.bind(this)(),t=j(t,{nullIfEmpty:true}).data;let{group:r=null}=t;if(!r&&!qe)return {type:"success",message:"Left realtime message group."};if(r!==null&&typeof r!="string")throw new h('"group" must be a string | null.',{code:"INVALID_PARAMETER"});return e.readyState===1&&e.send(JSON.stringify({action:"joinRoom",rid:r,token:this.session.accessToken.jwtToken})),qe=r,{type:"success",message:r?`Joined realtime message group: "${r}".`:"Left realtime message group."}}async function Na(t,e){t=b.Params(t,{user_id:n=>b.UserId(n,'User ID in "user_id"'),group:["string",()=>{if(!qe)throw new h('No group has been joined. Otherwise "group" is required.',{code:"INVALID_REQUEST"});return qe}]});let r=await I.bind(this)("get-ws-group",t,{fetchOptions:e,auth:true,method:"post"});return r.list=r.list.map(n=>({user_id:n.uid.split("#")[1],cid:"cid:"+n.cid})),r}async function Oa(t,e){if(await this.__connection,t||(t={searchFor:"group",value:" ",condition:">"}),t=b.Params(t,{searchFor:["group","number_of_users",()=>"group"],value:["string","number",()=>t?.searchFor&&t?.searchFor==="number_of_users"?0:" "],condition:[">",">=","=","<","<=","!=","gt","gte","eq","lt","lte","ne"],range:["string","number"]}),t.condition||(t.value===" "||!t.value?t.condition=">":t.condition="="),t.range&&t.condition&&delete t.condition,t.searchFor==="number_of_users"&&typeof t.value!="number")throw new h('"value" must be a number.',{code:"INVALID_PARAMETER"});if(t.searchFor==="group"&&typeof t.value!="string")throw new h('"value" must be a string.',{code:"INVALID_PARAMETER"});if(t.hasOwnProperty("range")&&typeof t.range!=typeof t.value)throw new h(`"range" must be a ${typeof t.value}.`,{code:"INVALID_PARAMETER"});let r=await I.bind(this)("get-ws-group",t,{fetchOptions:e,auth:true,method:"post"});return r.list=r.list.map(n=>({group:n.rid.split("#")[1],number_of_users:n.cnt})),r}var Fa=typeof FormData<"u",La=typeof HTMLFormElement<"u",Ma=typeof SubmitEvent<"u",ke={},Wt={},ue={};function Gt(t){return Object.freeze({id:t,status:"stopped"})}function qa(t){return !!t&&typeof t=="object"&&t.status==="stopped"}var Va=3;function Ba(t,e,r){let n=false,i=Array.isArray(t?.chunks)?t.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<=e.seq)&&(e.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 t?.last_seq=="number"&&t.last_seq>e.seq&&(e.seq=t.last_seq,n=true),n}var Nf=2e3,$a=5e3,Of=2e3,Ff=5,Lf=1500,Vr=null;function Ka(t,e,r){let n=new Map,i=false,s=false,o=0,a={socket:0,poll:0},l=(d,p,g)=>{if(t.seq=d,!(!e||typeof p!="string"||p===""))try{e(p,d,g);}catch(m){console.error(m);}},c=()=>{for(let d of Array.from(n.keys()))d<=t.seq&&n.delete(d);for(;;){let d=t.seq+1;if(!n.has(d))break;let p=n.get(d);n.delete(d),l(d,p.txt,p.via);}};return {cursor:t,open:()=>{i||s||(i=true,c());},fromPoll:d=>{if(s)return false;let p=t.seq,g=t.seq,m=Array.isArray(d?.chunks)?d.chunks:[];for(let w of m){if(!w||typeof w.seq!="number"||w.seq<=t.seq)continue;let _=!n.has(w.seq);_&&(a.poll++,r&&a.poll===1&&r("poll",w.seq)),n.set(w.seq,{txt:typeof w.txt=="string"?w.txt:"",via:_?"poll":n.get(w.seq).via}),w.seq>g&&(g=w.seq);}typeof d?.last_seq=="number"&&d.last_seq>g&&(g=d.last_seq);let y=Array.from(n.keys()).sort((w,_)=>w-_);for(let w of y){if(w<=t.seq){n.delete(w);continue}if(w>g)break;let _=n.get(w);n.delete(w),l(w,_.txt,_.via);}return g>t.seq&&(t.seq=g),c(),t.seq>p},fromSocket:(d,p)=>{s||typeof d!="number"||!Number.isFinite(d)||(o=Date.now(),!(d<=t.seq)&&(!n.has(d)&&n.size>=Of||(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&&c())));},warm:()=>o!==0&&Date.now()-o<Nf,stats:()=>({socket:a.socket,poll:a.poll}),close:()=>{s=true,n.clear();}}}function ja(t){if(!this||!this.__network_logs)return {onTransport:void 0,done:()=>{}};let e=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:t,first_seq:i,after_ms:Date.now()-e});},done:n=>{if(r||!n)return;r=true;let i=n.stats();console.log("%cSKAPI: stream transport","color: blue;",{id:t,over_websocket:i.socket,over_poll:i.poll,took_ms:Date.now()-e});}}}function Ha(t,e){let r={stop:()=>{}};if(typeof window>"u"||window._runningInNodeJS||Vr)return r;let n={stopped:false,socket:null,opened:null,joined:false,attempts:0,unavailable:false};Vr=n;let i=c=>{if(n.stopped)return;let u=c?.data;if(typeof u!="string")return;let f=null;try{f=JSON.parse(u);}catch{try{f=JSON.parse(decodeURI(u));}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!==t)return;let g=d.seq;typeof g=="string"&&g!==""&&(g=Number(g)),e.fromSocket(g,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 c=n.opened,u=n.joined;if(n.opened=null,n.joined=false,s(),!(!u&&!c))try{let f=this.__socket?await this.__socket:null;if(c&&f===c){await qr.bind(this)();return}u&&f&&ka()===room&&await At.bind(this)({group:null});}catch{}},a=()=>{n.stopped||(s(),!n.unavailable&&(n.attempts>=Ff||(n.attempts+=1,setTimeout(()=>{n.stopped||l();},Lf))));},l=async()=>{try{let c=this.__socket?await this.__socket:null;if(n.stopped){o();return}if(!c){if(!this.session){n.unavailable=!0,o();return}if(await Et.bind(this)(()=>{},0),c=this.__socket?await this.__socket:null,n.stopped){o();return}c&&!n.opened&&(n.opened=c);}if(!c||c.readyState!==1)return;if(c.addEventListener("message",i),c.addEventListener("close",a),n.socket=c,!n.joined&&(await At.bind(this)({group:t}),n.joined=!0,n.stopped)){o();return}}catch{}};return l(),{stop:()=>{n.stopped||(n.stopped=true,Vr===n&&(Vr=null),o());}}}function Wa(t){return t?.status==="running"||t?.status==="pending"}function Mf(t){return !!t&&typeof t=="object"&&!Array.isArray(t)&&typeof t.status=="string"&&typeof t.id=="string"&&"in_queue"in t}function Ga(t,e,r,n){if(!t||typeof t!="string")throw new h('"requestId" should be type: <string>.',{code:"INVALID_PARAMETER"});if(t.includes("#"))return t;if(!e||typeof e!="string"||!r||typeof r!="string")throw new h('"url" and "method" are required to address a request by its short id.',{code:"INVALID_PARAMETER"});return b.Url(e),`[${r.toUpperCase()}]${e.toLowerCase()}#${n}:${t}`}function Ja({id:t,auth:e,service:r,owner:n,latency:i=1e3,queue:s,onResponse:o,onError:a,onStream:l,realtimeGroup:c}){if(typeof i!="number")throw new h('"latency" should be a number.',{code:"INVALID_PARAMETER"});if(i<0)throw new h('"latency" should be a non-negative number.',{code:"INVALID_PARAMETER"});s&&!ke?.[s]&&(ke[s]=new qt({breakWhenError:false,batchSize:1}));let u={stop:null,aborted:false,queue:s};ue[t]=u;let f=null,d=()=>{ue[t]===u&&delete ue[t];},p=()=>new Promise((m,y)=>{let w=false;if(u.aborted){d(),m(Gt(t));return}let _={seq:0},A=ja.call(this,t),S=l&&c?Ka(_,l,A.onTransport):null,T=S?Ha.call(this,c,S):null,N=()=>{A.done(S),T&&T.stop(),S&&S.close();};f=N;let F=0,C=false,x=0,O=async()=>{if(!(w||C)&&!(S&&S.warm()&&Date.now()-F<$a)){C=true;try{for(;;){let M={id:t,service:r,owner:n};l&&(M.since=_.seq),F=Date.now();let J=await I.bind(this)("csr-poll",M,{auth:e});if(w)return;let ve=S?S.fromPoll(J):l?Ba(J,_,l):!1;S&&S.open();let $=Wa(J);if(J?.more&&ve){x=0;continue}if($){x=0;return}if(x=J?.more?x+1:0,J?.more&&x<Va)return;w=!0,o&&o(J),clearInterval(L),N(),d(),m(J);return}}catch(M){if(w)return;w=true,a&&a(M),clearInterval(L),N(),d(),y(M);}finally{C=false;}}},L=setInterval(O,i);S&&O(),u.stop=()=>{w||(w=true,clearInterval(L),N(),d(),m(Gt(t)));};}),g=()=>{let m=ue[t];m&&(m.stop?m.stop():(m.aborted=true,delete ue[t]));};if(s){let m=new Promise((y,w)=>{let _=false,A=ke[s].add([async()=>{try{let S=await p();return _||(_=!0,y(S)),S}catch(S){throw _||(_=true,w(S)),S}}])[0];Wt[t]=A,u.stop=()=>{if(!_){u.aborted=true,f&&f();try{ke[s]&&ke[s].remove(Wt[t]);}catch{}delete Wt[t],d(),_=true,y(Gt(t));}};});return Object.assign(m,{stop:g})}else return Object.assign(p(),{stop:g})}function Ya(t){let e=0,r=[];if(t?.id){if(t.url&&t.method){let n=t.service||this.service;r.push(`[${t.method.toUpperCase()}]${t.url.toLowerCase()}#${n}:${t.id}`);}r.push(t.id);}else if(t?.queue)for(let n in ue)ue[n]?.queue===t.queue&&r.push(n);else for(let n in ue)r.push(n);for(let n of r){let i=ue[n];i&&(i.stop?i.stop():(i.aborted=true,delete ue[n]),e+=1);}return e}function za(t,e){if(!t.queue)throw new h('"queue" is required.',{code:"INVALID_PARAMETER"});let r={service:t.service||this.service,owner:t.owner||this.owner,queue:t.queue+":"};return I.bind(this)("csr-poll",r,{auth:true})}async function Qa(t){let e=false;if(typeof t.poll=="number"&&t.poll<0)throw new h('"poll" should be a non-negative number.',{code:"INVALID_PARAMETER"});let r=t?.onResponse,n=t?.onError,i=t?.onStream,s=typeof t.poll=="number"?t.poll:t.poll?1e3:0;delete t.poll,(s||t.stream)&&!t.queue&&(t.queue=(this.__user?.user_id||"anonymous")+"-"+Ye());let o=c=>{for(let u in c)if(typeof c[u]=="string"&&c[u].includes("$CLIENT_SECRET")){e=true;break}};if(t=b.Params(t,{url:c=>{if(!c||typeof c!="string")throw new h('"url" should be type: <string>.',{code:"INVALID_PARAMETER"});return b.Url(c),c.includes("$CLIENT_SECRET")&&(e=true),c},clientSecretName:"string",method:c=>{if(c&&typeof c!="string")throw new h('"method" should be either "GET" or "POST" or "DELETE" or "PUT".',{code:"INVALID_PARAMETER"});let u=c.toLowerCase();if(u!=="get"&&u!=="post"&&u!=="delete"&&u!=="put")throw new h('"method" should be either "GET" or "POST" or "DELETE" or "PUT".',{code:"INVALID_PARAMETER"});return u},stream:c=>{if(c!=null&&typeof c!="boolean")throw new h('"stream" should be type: <boolean>.',{code:"INVALID_PARAMETER"});return !!c},realtime:c=>{if(c!=null&&typeof c!="boolean")throw new h('"realtime" should be type: <boolean>.',{code:"INVALID_PARAMETER"});return !!c},headers:c=>{if(c&&typeof c!="object")throw new h('"headers" should be type: <object>.',{code:"INVALID_PARAMETER"});return o(c),c},data:c=>{if(c&&typeof c!="object")throw new h('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return o(c),c},params:c=>{if(c&&typeof c!="object")throw new h('"params" should be type: <object>.',{code:"INVALID_PARAMETER"});return o(c),c},expires:"number",queue:"string"},["clientSecretName","method","url"]),t.realtime&&!t.stream)throw new h('"realtime" requires "stream": true.',{code:"INVALID_PARAMETER"});if(!e)throw new h(`At least one parameter value should include "$CLIENT_SECRET" in ${t.method.toLowerCase()==="post"?'"data"':'"params"'} or "headers".`,{code:"INVALID_PARAMETER"});await this.__connection;let a=!!this.__user,l=()=>I.bind(this)("csr",t,{auth:a,tokenHeaders:{accessToken:!!a}}).then(c=>{if(c.status==="running"||c.status==="pending"){let u=`[${t.method.toUpperCase()}]${t.url.toLowerCase()}`,f=t.service||this.service,d=t.owner||this.owner,p=`${u}#${f}:${c.id}`;Object.assign(c,{poll:g=>Ja.call(this,{id:p,auth:a,service:f,owner:d,latency:g?.latency||1e3,queue:t?.queue,onResponse:r,onError:n,onStream:g?.onStream||i,realtimeGroup:c?.realtime_group})});}return r?r(c):c}).catch(c=>{if(n)return n(c);throw c});if(t?.queue){let c="base:"+t.queue;return ke?.[c]||(ke[c]=new qt({breakWhenError:false,batchSize:1})),new Promise((u,f)=>{ke[c].add([async()=>{try{let d=await l();if(s>0){let p=d.poll({latency:s});return u(p),p}return u(d),d}catch(d){throw f(d),d}}]);})}else return l()}async function Xa(t,e){await this.__connection;let r=t.service||this.service,n=t.owner||this.owner;t=b.Params(t,{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=`[${t.method.toUpperCase()}]${t.url.toLowerCase()}#${r}:`,o={id:s,queue:t?.queue,status:t?.status,service:r,owner:n};t?.compact&&(o.compact=true),t?.queue_exact&&(o.queue_exact=true),t?.queue_exclude&&(o.queue_exclude=t.queue_exclude),Object.keys(o).forEach(l=>{o[l]||delete o[l];}),o.queue&&(o.id_prefix=o.id,delete o.id);let a=await I.bind(this)("csr-poll",o,{auth:i,fetchOptions:e});return a.list=a.list.map(l=>{let c={id:l.id,status_code:l.rslv?.status_code||null,response_body:l.rslv?.body||l.rslv?.truncated||null,error:l?.err,created:l?.stmp,updated:l?.utmp,executed:typeof l?.att=="number"?l.att*1e3:void 0,request_body:l?.reqbdy,expires:l?.expt,status:l.stts,queue_name:l?.qid,request_text:l?.reqtxt,response_text:l?.rslvtxt,response_complete_marker:l?.rslvmk!=null?!!l.rslvmk:void 0,compact:l?.cmpct?true:void 0};for(let u in c)c[u]===void 0&&delete c[u];return (c.status==="running"||c.status==="pending")&&(c.poll=u=>Ja.call(this,{id:s+c.id,auth:i,service:r,owner:n,latency:u?.latency||1e3,queue:l?.qid,onResponse:u?.onResponse,onError:u?.onError,onStream:u?.onStream})),c}),a}async function Za(t){await this.__connection,t=b.Params(t,{url:"string",method:["GET","POST","DELETE","PUT"],id:"string",queue:"string"},["url","method","id"]);let e=t?.service||this.service,r=t?.owner||this.owner,n=!!this.__user,i=`[${t.method.toUpperCase()}]${t.url.toLowerCase()}#${e}`,s=t.id,o=`${i}:${s}`,a=t?.queue;return a&&ke?.[a]&&(ke[a].remove(Wt[o]),delete Wt[o]),I.bind(this)("csr-cancel",{id:o,service:e,owner:r},{auth:n})}function ec(t,e){let r=typeof e?.poll=="number"?e.poll:1e3;if(!Number.isFinite(r)||r<0)throw new h('"poll" should be a non-negative number.',{code:"INVALID_PARAMETER"});if(!t||typeof t!="string")throw new h('"requestId" should be type: <string>.',{code:"INVALID_PARAMETER"});if(e?.since!==void 0&&typeof e.since!="number")throw new h('"since" should be a number.',{code:"INVALID_PARAMETER"});if(e?.realtimeGroup!==void 0&&e.realtimeGroup!==null&&typeof e.realtimeGroup!="string")throw new h('"realtimeGroup" should be type: <string>.',{code:"INVALID_PARAMETER"});let n=typeof e?.since=="number"&&e.since>0?e.since:0,i=e?.onStream,s=e?.onResponse,o=e?.onError,a={stopped:false,fullId:t,resolve:null},l=null,c={stop:null,aborted:false},u=()=>{ue[a.fullId]===c&&delete ue[a.fullId];},f=()=>{a.stopped||(a.stopped=true,l&&l(),u(),a.resolve&&a.resolve(Gt(a.fullId)));};c.stop=f;let d=new Promise(async(p,g)=>{a.resolve=p;try{await this.__connection;let m=!!this.__user,y=e?.service||this.service,w=e?.owner||this.owner;if(a.fullId=Ga(t,e?.url,e?.method,y),a.stopped){p(Gt(a.fullId));return}ue[a.fullId]=c;let _={seq:n},A=0,S=ja.call(this,a.fullId),T=i&&e?.realtimeGroup?Ka(_,i,S.onTransport):null,N=T?Ha.call(this,e.realtimeGroup,T):null,F=()=>{S.done(T),N&&N.stop(),T&&T.close();};for(l=F;;){let C=await I.bind(this)("csr-poll",{id:a.fullId,service:y,owner:w,since:_.seq},{auth:m});if(a.stopped)return;if(!Mf(C)){F(),u(),s&&s(C),p(C);return}let x=T?T.fromPoll(C):Ba(C,_,i);T&&T.open();let O=Wa(C);if(C.more&&x){A=0;continue}if(A=C.more?A+1:0,!O&&(!C.more||A>=Va)){F(),u(),s&&s(C),p(C);return}if(await new Promise(L=>setTimeout(L,T&&T.warm()?Math.max(r,$a):r)),a.stopped)return}}catch(m){if(a.stopped)return;l&&l(),u(),o&&o(m),g(m);}});return Object.assign(d,{stop:f})}async function tc(t,e,r){await this.__connection;let n=r?.service||this.service,i=r?.owner||this.owner,s=!!this.__user,o=Ga(t,r?.url,r?.method,n);return I.bind(this)("csr-finalize",{id:o,data:e,service:n,owner:i},{auth:s})}async function rc(t){await this.__connection;let e={name:"string",email:r=>(b.Email(r),r),subject:"string",message:"string"};return t=b.Params(t,e,["name","email","subject","message"]),await I.bind(this)("send-inquiry",t),"SUCCESS: Inquiry has been sent."}async function nc(t,e){if(await this.__connection,Fa&&t instanceof FormData||La&&t instanceof HTMLFormElement||Ma&&t instanceof SubmitEvent){if(!e)throw new h("Url string as a second argument is required when form is passed.",{code:"INVALID_PARAMETER"});let n=j(t);t={url:e,data:n.data,sync:true};}let r={url:n=>b.Url(n),data:n=>n,sync:["boolean",()=>true]};if(Array.isArray(t))for(let n of t)n=b.Params(n,r);else t=b.Params(t,r);return I.bind(this)("post-secure",t,{auth:true})}async function ic(t,e){await this.__connection;let{auth:r=false,method:n="POST",bypassAwaitConnection:i=false,responseType:s,contentType:o,tokenHeaders:a,progress:l}=e||{};if(e=Object.assign({auth:r,method:n,bypassAwaitConnection:i,responseType:s,contentType:o,tokenHeaders:a},{fetchOptions:{progress:l}}),typeof t!="object"&&(o==="application/json"||o===void 0))throw new h('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return I.bind(this)("mock",t,e)}async function sc(t,e){if(await this.__connection,!e?.url||typeof e.url!="string")throw new h('"url" is required in the second argument.',{code:"INVALID_PARAMETER"});b.Url(e.url);let n=(await this.admin_endpoint)?.forward_request;if(!n)throw new h("forwardRequest is not available on this service region yet.",{code:"NOT_EXISTS"});let i=null,s=null,o=Ma&&t instanceof SubmitEvent?t.target:La&&t instanceof HTMLFormElement?t:null;o?i=new FormData(o):Fa&&t instanceof FormData?i=t:t!=null&&(i=JSON.stringify(t),s="application/json");let a={public_identifier:this.__public_identifier,service:this.service,owner:this.owner,forward:{url:e.url,method:e.method||"POST",headers:e.headers||{},apiKeyHeader:e.apiKeyHeader,apiKeyScheme:e.apiKeyScheme}},l=JSON.stringify(a).replace(/[\u007f-\uffff]/g,p=>"\\u"+p.charCodeAt(0).toString(16).padStart(4,"0"));if(l.length>4096)throw new h("Destination url and headers are too large for Content-Meta.",{code:"INVALID_PARAMETER"});let c=this.bearerToken||this.session?.idToken?.jwtToken||null;if(!c)throw new h("User login is required.",{code:"INVALID_REQUEST"});let u={"Content-Meta":l,Authorization:c};s&&(u["Content-Type"]=s);let f=await fetch(n,{method:"POST",headers:u,body:i,signal:e.signal});if(e.responseType==="response")return f;if(!f.ok){let p=await f.text();try{p=JSON.parse(p);}catch{}throw new h(p?.message||(typeof p=="string"?p:JSON.stringify(p)),{code:p?.code||"ERROR"})}if(e.onStream&&f.body){let p=f.body.getReader(),g=new TextDecoder,m="";for(;;){let{done:y,value:w}=await p.read();if(y)break;let _=g.decode(w,{stream:true});m+=_;try{e.onStream(_);}catch(A){console.error(A);}}return m}let d=await f.text();if(e.responseType==="text")return d;try{return JSON.parse(d)}catch{return d}}async function oc(t,e){await this.__connection,t=b.Params(t||{},{access_group:n=>{if(n==="authorized"&&(n=1),n==="public"&&(n=0),typeof n!="number")throw new h('"access_group" should be type number.',{code:"INVALID_PARAMETER"});if(n<0)throw new h('"access_group" should be zero or a positive number.',{code:"INVALID_PARAMETER"});if(n>this.__user.access_group)throw new h("User has no access.",{code:"INVALID_REQUEST"});return n}});let r=await I.bind(this)("get-feed",t,{auth:true,fetchOptions:e});for(let n in r.list)r.list[n]=await Ze.bind(this)(r.list[n]);return r}function Jt(t){if(t===this.__user.user_id)throw new h(`"user_id" cannot be the user's own ID.`,{code:"INVALID_PARAMETER"});return b.UserId(t,'"user_id"')}async function ac(t,e){if(t=j(t,{ignoreEmpty:true}).data,t=b.Params(t,{subscriber:n=>b.UserId(n,'User ID in "subscriber"'),subscription:Jt.bind(this),blocked:"boolean"}),!t.subscriber&&!t.subscription)throw new h('At least either "subscriber" or "subscription" should have a value.',{code:"INVALID_PARAMETER"});let r=await I.bind(this)("get-subscription",t,Object.assign({auth:true},{fetchOptions:e}));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 cc(t){await this.__connection,t=b.Params(t,{user_id:Jt.bind(this),get_feed:["boolean",()=>false],get_notified:["boolean",()=>false],get_email:n=>{if(n&&!this.__user.email||!this.__user.email_verified)throw new h("User has no verified email address.",{code:"INVALID_REQUEST"});return !!n}},["user_id"]);let e=await I.bind(this)("subscription",{subscribe:t.user_id,option:{get_feed:t.get_feed,get_notified:t.get_notified,get_email:t.get_email||false}},{auth:true}),r={};if(e.sub){let n=e.sub.split("#");r.subscriber=n[2],r.subscription=n[0];}else r.subscriber=e.subscriber,r.subscription=e.subscription;return r.timestamp=e?.timestamp||e.stmp,r.blocked=e?.blocked||e.grp.substring(0,1)==="N",Object.assign(r,e.opt),r}async function lc(t){await this.__connection;let{user_id:e}=b.Params(t,{user_id:Jt.bind(this)},["user_id"]);return await I.bind(this)("subscription",{unsubscribe:e},{auth:true})}async function uc(t){await this.__connection;let{user_id:e}=b.Params(t,{user_id:Jt.bind(this)},["user_id"]);return await I.bind(this)("subscription",{block:e},{auth:true})}async function dc(t){await this.__connection;let{user_id:e}=b.Params(t,{user_id:Jt.bind(this)},["user_id"]);return await I.bind(this)("subscription",{unblock:e},{auth:true})}async function fc(t,e){await this.__connection;let r=await Z.bind(this)();t=b.Params(t||{},{user_id:o=>{if(o!==this.__user.user_id&&!r)throw new h("No access.",{code:"INVALID_REQUEST"});return o},group:o=>b.newsletterGroup(o,{allowNull:true})});let n=await I.bind(this)("get-newsletter-subscription",t,{auth:true,fetchOptions:e||null}),i=n?.list||n,s=[];Array.isArray(i)||(i=[]);for(let o of i){let a=o.subt.split("#"),l=true;a[0].charAt(0)==="@"&&(l=false,a[0]=a[0].substring(1));let c=/^\d+$/.test(a[0])?parseInt(a[0]):a[0];s.push({timestamp:o.stmp,group:c,subscribed_email:a[1],active:l});}return n?.list?(n.list=s,n):s}async function hc(t){await this.__connection;let e=b.Params(t||{},{email:r=>Array.isArray(r)&&r.length>0?r.length===1?b.Email(r[0]):r.map(n=>b.Email(n)):b.Email(r),group:r=>b.newsletterGroup(r),redirect:r=>b.Url(r)},this.__user?["group"]:["email","group"]);return I.bind(this)(`subscribe-${this.__user?"":"public-"}newsletter`,e,{auth:!!this.__user})}async function pc(t){await this.__connection;let e=b.Params(t||{},{group:r=>b.newsletterGroup(r,{nameOnly:true}),restriction:r=>{if(typeof r!="number"||!Number.isInteger(r)||r<0||r>99)throw new h('"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 h('"name" should be a string of 60 characters or less.',{code:"INVALID_PARAMETER"});return r}},["group"]);return I.bind(this)("register-newsletter-group",e,{auth:true})}async function gc(t){await this.__connection;let e=b.Params(t||{},{group:r=>b.newsletterGroup(r,{nameOnly:true})},["group"]);return I.bind(this)("delete-newsletter-group",e,{auth:true})}async function mc(){return await this.__connection,I.bind(this)("newsletter-group-endpoint",null,{auth:true})}async function yc(t){await this.__connection,t=b.Params(t,{group:r=>b.newsletterGroup(r,{allowNull:true})},["group"]);let e=Object.assign({action:"unsubscribe"},t);return I.bind(this)("subscribe-newsletter",e,{auth:true})}async function _c(t,e){let r=await Z.bind(this)(),n={message_id:"string",timestamp:"number",read:"number",complaint:"number",subject:"string",bounced:"number"};t||(e=Object.assign({ascending:false},e||{})),t=j(t).data,t=t||{searchFor:"timestamp",value:Date.now(),condition:"<",group:"public"},t=b.Params(t,{searchFor:["message_id","timestamp","subject","complaint","read","bounced"],value:l=>{if(typeof l!==n[t.searchFor])throw new h(`"value" type does not match the type of "${t.searchFor}" index.`,{code:"INVALID_PARAMETER"});if(typeof l=="string"&&!l)throw new h('"value" should not be empty string.',{code:"INVALID_PARAMETER"});return l},range:l=>{if(!t.hasOwnProperty("value")||typeof l!=typeof t.value)throw new h('"range" should match type of "value".',{code:"INVALID_PARAMETER"});return l},condition:[">",">=","=","<","<=","gt","gte","eq","lt","lte",()=>"="],group:l=>{let c=b.newsletterGroup(l);if(c===0)return 0;if(typeof c=="string")return c;if(!this.session)throw new h("User should be logged in.",{code:"INVALID_REQUEST"});if(l==="authorized")return 1;if(!r&&c>parseInt(this.user?.access_group||this.session?.idToken?.payload?.access_group))throw new h("User has no access.",{code:"INVALID_REQUEST"});return c}},["searchFor","value","group"]);let i=t.group===0||typeof t.group=="string"&&!this.__user?"get-public-newsletters":"get-newsletters",s=await I.bind(this)(i,t,Object.assign({method:"get",auth:i==="get-public-newsletters"?!!this.__user:true},{fetchOptions:e})),o={message_id:"mid",timestamp:"stmp",complaint:"cmpl",read:"read",subject:"subj",bounced:"bnce",url:"url",delivered:"delv",group:"grp"},a={message_id:"",timestamp:0,complaint:0,read:0,subject:"",bounced:"",url:"",delivered:0,group:t.group};return s.list=s.list.map(l=>{let c={};for(let u in o)c[u]=l[o[u]]||a[u];return c.bounced=String(c.bounced),c}),s}async function bc(t){let e=b.Params(t,{user_id:n=>b.UserId(n,'"user_id"')},["user_id"]);if(e?.service&&e?.owner?e={service:e?.service,owner:e?.owner,block:e.user_id}:e={block:e.user_id},!await Z.bind(this)()){if(!this.__user)throw new h("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new h("Invalid access.",{code:"INVALID_REQUEST"})}return await I.bind(this)("block-account",e,{auth:true})}async function wc(t){let e=b.Params(t,{user_id:n=>b.UserId(n,'"user_id"')},["user_id"]);if(e?.service&&e?.owner?e={service:e?.service,owner:e?.owner,unblock:e.user_id}:e={unblock:e.user_id},!await Z.bind(this)()){if(!this.__user)throw new h("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new h("Invalid access.",{code:"INVALID_REQUEST"})}return await I.bind(this)("block-account",e,{auth:true})}async function Ec(t){let e=b.Params(t,{user_id:n=>b.UserId(n,'"user_id"')},["user_id"]);if(e?.service&&e?.owner?e={service:e?.service,owner:e?.owner,delete:e.user_id}:e={delete:e.user_id},!await Z.bind(this)()){if(!this.__user)throw new h("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new h("Invalid access.",{code:"INVALID_REQUEST"})}return await I.bind(this)("remove-account",e,{auth:true})}async function Ac(t,e){let r={email:s=>b.Email(s),password:s=>b.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=>b.Birthdate(s),phone_number:s=>b.PhoneNumber(s),picture:s=>{if(s)return b.Url(s)},profile:s=>{if(s)return b.Url(s)},website:s=>{if(s)return b.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 h('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof s!="number"||s<1||s>100)throw new h('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"});return s}},n=b.Params(t,r,["email"]);if(e=b.Params(e,{confirmation_url:s=>{let o=s;if(typeof s=="string")o=b.Url(s);else throw new h('"options.confirmation_url" should be type: <string>.',{code:"INVALID_PARAMETER"});if(o&&!n.email)throw new h('"email" is required for signup confirmation.',{code:"INVALID_PARAMETER"});return o},email_subscription:s=>{if(typeof s!="boolean")throw new h('"options.email_subscription" should be type: <boolean>.',{code:"INVALID_PARAMETER"});if(!e?.confirmation_url)throw new h('"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 h('"options.template" should be type: <object> with "url" and "subject".',{code:"INVALID_PARAMETER"});return {url:b.Url(s.url),subject:s.subject}}}),n.signup_confirmation=e?.confirmation_url||true,n.email_subscription=e?.email_subscription||false,n.template=e?.template||{},!await Z.bind(this)()){if(!this.__user)throw new h("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new h("Invalid access.",{code:"INVALID_REQUEST"})}return await I.bind(this)("admin-signup",n,{auth:true})}async function Sc(t){let e={email:s=>b.Email(s),password:s=>b.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=>b.Birthdate(s),phone_number:s=>b.PhoneNumber(s),picture:s=>s?b.Url(s):"",profile:s=>s?b.Url(s):"",website:s=>s?b.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 h('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof s!="number"||s<1||s>100)throw new h('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"});return s}},r=["email","password"],n=b.Params(t,e,r);if(!await Z.bind(this)()){if(!this.__user)throw new h("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new h("Invalid access.",{code:"INVALID_REQUEST"})}return await I.bind(this)("admin-signup",n,{auth:true})}async function vc(t){if(t=b.Params(t,{user_id:r=>b.UserId(r,'"user_id"'),access_group:r=>{try{typeof r=="string"&&(r=parseInt(r));}catch{throw new h('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof r=="number"&&r>0&&r<100)return r;throw new h('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"})}},["user_id","access_group"]),!await Z.bind(this)()){if(!this.__user)throw new h("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new h("Invalid access.",{code:"INVALID_REQUEST"})}return await I.bind(this)("grant-access",t,{auth:true})}async function Rc(t,e){if(t=b.Params(t,{email:"string"}),!await Z.bind(this)()){if(!this.__user)throw new h("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new h("Invalid access.",{code:"INVALID_REQUEST"})}let n=await I.bind(this)("invitation-list",Object.assign({mode:"search"},t),{fetchOptions:e,auth:true});return n.list=n.list.map(i=>Tt(i.user)),n}async function Tc(t){if(t=b.Params(t,{email:r=>b.Email(r)},["email"]),!await Z.bind(this)()){if(!this.__user)throw new h("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new h("Invalid access.",{code:"INVALID_REQUEST"})}return await I.bind(this)("invitation-list",Object.assign({mode:"cancel"},t),{auth:true})}async function Ic(t){if(t=b.Params(t,{email:r=>b.Email(r)},["email"]),!await Z.bind(this)()){if(!this.__user)throw new h("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new h("Invalid access.",{code:"INVALID_REQUEST"})}return await I.bind(this)("invitation-list",Object.assign({mode:"resend"},t),{auth:true})}async function Pc(t){let e=b.Params(t,{user_id:o=>b.UserId(o,'"user_id"'),email:o=>b.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?b.Birthdate(o):"",phone_number:o=>o?b.PhoneNumber(o):"",email_public:"boolean",phone_number_public:"boolean",address_public:"boolean",gender_public:"boolean",birthdate_public:"boolean",misc:"string",picture:o=>o?b.Url(o):"",profile:o=>o?b.Url(o):"",nickname:"string",website:o=>o?b.Url(o):""},["user_id"]),r=e.service,n=e.owner;if(delete e.service,delete e.owner,Object.keys(e).filter(o=>o!=="user_id"&&e[o]!==void 0).length===0)throw new h("At least one attribute to update is required.",{code:"INVALID_PARAMETER"});if(!await Z.bind(this)()){if(!this.__user)throw new h("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new h("Invalid access.",{code:"INVALID_REQUEST"})}e.email&&(e.preferred_username=(r||this.service)+"-"+X.hash(e.email));let s={attributes:e};return r&&n&&(s.service=r,s.owner=n),await I.bind(this)("admin-edit-profile",s,{auth:true})}async function Uc(t){if(typeof window>"u"||window._runningInNodeJS)throw new h("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.__connection,!t.endpoint)throw new h("Missing parameter: endpoint",{code:"INVALID_PARAMETER"});if(!t.keys||!t.keys.p256dh||!t.keys.auth)throw new h("Missing parameter: keys.p256dh or keys.auth",{code:"INVALID_PARAMETER"});return await I.bind(this)("store-subscription",{endpoint:t.endpoint,keys:t.keys},{auth:true}),"SUCCESS: Subscribed to receive notifications."}async function xc(t){if(typeof window>"u"||window._runningInNodeJS)throw new h("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.__connection,!t.endpoint)throw new h("Missing parameter: endpoint",{code:"INVALID_PARAMETER"});if(!t.keys||!t.keys.p256dh||!t.keys.auth)throw new h("Missing parameter: keys.p256dh or keys.auth",{code:"INVALID_PARAMETER"});return await I.bind(this)("delete-subscription",{endpoint:t.endpoint,keys:t.keys},{auth:true}),"SUCCESS: Unsubscribed from notifications."}async function Cc(){if(typeof window>"u"||window._runningInNodeJS)throw new h("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});return await this.__connection,{VAPIDPublicKey:await I.bind(this)("get-vapid-public-key",null,{auth:true})}}async function kc(t,e){if(typeof window>"u"||window._runningInNodeJS)throw new h("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});await this.__connection;let{title:r,body:n}=j(t||{},{nullIfEmpty:true}).data;if(!r)throw new h("Missing parameter: message title",{code:"INVALID_PARAMETER"});if(!n)throw new h("Missing parameter: message body",{code:"INVALID_PARAMETER"});let i={title:r,body:n};return e?(typeof e=="string"&&(e=[e]),i.user_ids=e):i.user_ids="all_users",await I.bind(this)("push-notification",i,{auth:true}),"SUCCESS: Notification sent."}async function Dc(t){await this.__connection,t=b.Params(t,{spell:"string",name:"string",magic:r=>r},["spell","name"]);await I.bind(this)("castspell",t);return `The spell "${t.spell}" has been cast.`}async function Nc(t){return await this.__connection,t=b.Params(t||{},{search:["spell","name",()=>"spell"],value:"string"}),await I.bind(this)("getspell",t)}async function Oc(t){await this.__connection,t=b.Params(t,{message:"string",name:"string"},["message","name"]);let e=await I.bind(this)("dopamine",t,{auth:true}),r=e?.previous_message?.message,n=e?.previous_message?.name;if(oe())r&&n&&window.alert(`${n} said: ${r}`),window.location.href=e.video;else return r&&n?`${n} said: ${r}
|
|
217
217
|
Watch the video here: ${e.video}`:`Your message has been uploaded for future generations to receive.
|
|
218
|
-
Watch the video here: ${e.video}`}var R=class{constructor(e,r,n,i){this.__version="2.0.
|
|
218
|
+
Watch the video here: ${e.video}`}var R=class{constructor(e,r,n,i){this.__version="2.0.3";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(e){try{return b.UserId(e),!0}catch{return false}},url(e){try{return b.Url(e),!0}catch{return false}},phoneNumber(e){try{return b.PhoneNumber(e),!0}catch{return false}},birthdate(e){try{return b.Birthdate(e),!0}catch{return false}},email(e){try{return b.Email(e),!0}catch{return false}},params(e,r,n){return b.Params(e,r,n)}};this.util={MD5:X,generateRandom:Ye,toBase62:Ts,fromBase62:_e,decodeProjectId:Un,formatServiceId:xn,extractFormData:j,terminatePendingRequests:ea,request:(e,r,n)=>I.bind(this)(e,r,n,{ignoreService:true})};this.__network_logs=false;this.__endpoint_version="v2";this.__public_identifier="";this.bearerToken="";this.registerTicket=ko.bind(this);this.unregisterTicket=Do.bind(this);if(!e||typeof e!="string")throw this._alert("Service ID is required."),new h("Service ID is required.",{code:"INVALID_PARAMETER"});let s=e.trim().toLowerCase().replace(/^<|>$/g,"").replace(/[\s_\-.]+/g,"");if(s==="serviceid"||s==="projectid")throw this._alert(`Replace "${e}" with your actual Project ID.`),new h("Project ID is required.",{code:"INVALID_PARAMETER"});let o=e.split("-").length;if(o===2||o===7)try{let _=Un(e);n&&typeof n=="object"&&(i=n),r&&typeof r=="object"&&(n=r),r=_.owner,e=_.service;}catch{throw this._alert("Service ID is invalid."),new h("Service ID is invalid.",{code:"INVALID_PARAMETER"})}if(!r||typeof r!="string")throw this._alert("Owner ID is invalid."),new h("Owner ID is invalid.",{code:"INVALID_PARAMETER"});if(r!==this.host)try{b.UserId(r,'"owner"');}catch{throw this._alert("Owner ID is invalid."),new h("Owner ID is invalid.",{code:"INVALID_PARAMETER"})}this.service=e,this.owner=r;try{this.project_id=xn(e,r);}catch{this.project_id="";}let c=true,u=false,f=null;if(n&&(typeof n.refetchServiceInfo=="boolean"&&(u=n.refetchServiceInfo),typeof n.autoLogin=="boolean"&&(c=n.autoLogin),n.encryption&&(f=Ys(n.encryption)),typeof n.requestBatchSize=="number")){if(n.requestBatchSize<1)throw new h('"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 d=`https://${this.target_cdn}.cloudfront.net`,p=e.substring(0,4);this.admin_endpoint=fetch(`${d}/${p}/admin-${this.__endpoint_version}.json`).then(_=>_.blob()).then(_=>new Promise((A,S)=>{let T=new FileReader;T.onloadend=()=>A(T.result),T.onerror=S,T.readAsDataURL(_);})).then(_=>{try{return typeof _=="string"?JSON.parse(atob(_.split(",")[1])):null}catch{throw new h("Service does not exist. Create your service from skapi.com",{code:"NOT_EXISTS"})}}),this.record_endpoint=fetch(`${d}/${p}/record-${this.__endpoint_version}.json`).then(_=>_.blob()).then(_=>new Promise((A,S)=>{let T=new FileReader;T.onloadend=()=>A(T.result),T.onerror=S,T.readAsDataURL(_);})).then(_=>{try{return typeof _=="string"?JSON.parse(atob(_.split(",")[1])):null}catch{throw new h("Service does not exist. Create your service from skapi.com",{code:"NOT_EXISTS"})}});let g=oe();if(g&&!window.sessionStorage)throw this._alert("This browser is not supported."),new Error("This browser is not supported.");let m=g?JSON.parse(window.sessionStorage.getItem(`${e}#${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}:${Ye(16)}`);}zs.bind(this)(f),this.__authConnection=(async()=>{let _=await this.admin_endpoint,A={UserPoolId:_.userpool_id,ClientId:_.userpool_client};Pn()&&(A.Storage=window.localStorage),this.userPool=new vn(A);try{this.user||await re.bind(this)().getSession({skipUserUpdateEventTrigger:!0}),this.user&&(!m?.connection&&!c?Me.bind(this)():(f&&mo.bind(this)(),this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user)));}catch{}})();let y=`${this.service}/${this.owner}`,w=g?window.sessionStorage.getItem(`${y}:uniqueids`):null;if(w)try{let _=JSON.parse(w);this.__my_unique_ids=_&&typeof _=="object"&&!Array.isArray(_)?{[y]:_}:{};}catch{this.__my_unique_ids={};}this.__connection=(async()=>{let _=null;await this.record_endpoint,m?.connection||(_=this._updateConnection({refresh:u}));let A=()=>{if(this.__class_properties_has_been_cached)return;let S=()=>{let T={},N=["__startKeyHistory","__disabledAccount","__cached_requests","__request_signup_confirmation","__public_identifier","connection"];if(this.connection){for(let F of N)T[F]=this[F];if(f&&(T.__cached_requests={},T.__startKeyHistory={}),g){let F=`${e}#${r}`;try{window.sessionStorage.setItem(F,JSON.stringify(T));}catch{try{let x=Object.assign({},T,{__cached_requests:{},__startKeyHistory:{}});window.sessionStorage.setItem(F,JSON.stringify(x));}catch{try{window.sessionStorage.removeItem(F);}catch{}}}}this.__class_properties_has_been_cached=true;}};return _ instanceof Promise?_.then(()=>S()):S()};return g&&(window.addEventListener("beforeunload",()=>{this.closeRealtime(),A();}),window.addEventListener("visibilitychange",()=>{A();})),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(e){}get onLogin(){return this._onLoginListeners}set onLogin(e){typeof e=="function"&&this._onLoginListeners.push(e);}get onUserUpdate(){return this._userProfileListeners}set onUserUpdate(e){typeof e=="function"&&this._userProfileListeners.push(e);}_runOnUserUpdateListeners(e){for(let r of this._userProfileListeners)typeof r=="function"&&r(e);}_runOnLoginListeners(e){for(let r of this._onLoginListeners)typeof r=="function"&&r(e);}get onBatchProcess(){return this._onBatchProcessListeners}set onBatchProcess(e){typeof e=="function"&&this._onBatchProcessListeners.push(e);}_alert(e){oe()&&typeof window.alert=="function"&&window.alert(e);}async getConnectionInfo(e){e?.refresh&&(this.__connection instanceof Promise&&await this.__connection,this.__connection=this._updateConnection({refresh:true}));let n=await this.__connection,i=n?.user_agent||(oe()&&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(e){let r=e?.refresh||false;try{this.connection=await I.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,oe()){let r=`Built with:
|
|
219
219
|
%c\r
|
|
220
220
|
$$\\ $$\\ \r
|
|
221
221
|
$$ | \\__|\r
|