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.mjs
CHANGED
|
@@ -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
|
-
`,c=new Blob([u],{type:"application/javascript"});Ee=new Worker(URL.createObjectURL(c)),Ee.onmessage=g=>{a.readyState===1&&a.send(JSON.stringify({action:"keepAlive"}));},i(a);},a.onmessage=async u=>{let c="";try{c=JSON.parse(decodeURI(u.data)),this.log("socket onmessage",c);}catch{return}let g;switch(!0){case !!c?.["#message"]:g="message";break;case !!c?.["#private"]:g="private";break;case !!c?.["#notice"]:g="notice";break;case !!c?.["#rtc"]:g="rtc";break;case !!c?.["#error"]:g="error";break}if(!g)return;let f={type:g,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(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]),ge[f.sender_cid]&&delete ge[f.sender_cid],N?.[f.sender_cid]&&ue.bind(this)({cid:f.sender_cid}),f.type="rtc:closed",e(f);return}if(d.candidate&&Tr.bind(this)(d.candidate,f.sender_cid),d.sdpoffer&&(Ir.bind(this)(d.sdpoffer,f.sender_cid),ge[f.sender_cid]||(ge[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}):ge[f.sender_cid]&&(delete ge[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 l("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 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=m.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{m.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}),be!==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 qe(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&&!be)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})),be=r,{type:"success",message:r?`Joined realtime message group: "${r}".`:"Left realtime message group."}}async function Hi(e,t){e=m.Params(e,{user_id:n=>m.UserId(n,'User ID in "user_id"'),group:["string",()=>{if(!be)throw new l('No group has been joined. Otherwise "group" is required.',{code:"INVALID_REQUEST"});return be}]});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=m.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 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",pe={},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,y)=>{if(e.seq=d,!(!t||typeof p!="string"||p===""))try{t(p,d,y);}catch(h){console.error(h);}},c=()=>{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,c());},fromPoll:d=>{if(s)return false;let p=e.seq,y=e.seq,h=Array.isArray(d?.chunks)?d.chunks:[];for(let w of h){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>y&&(y=w.seq);}typeof d?.last_seq=="number"&&d.last_seq>y&&(y=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>y)break;let b=n.get(w);n.delete(w),u(w,b.txt,b.via);}return y>e.seq&&(e.seq=y),c(),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&&c())));},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=c=>{if(n.stopped)return;let g=c?.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 y=d.seq;typeof y=="string"&&y!==""&&(y=Number(y)),t.fromSocket(y,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,g=n.joined;if(n.opened=null,n.joined=false,s(),!(!g&&!c))try{let f=this.__socket?await this.__socket:null;if(c&&f===c){await Ut.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 c=this.__socket?await this.__socket:null;if(n.stopped){o();return}if(!c){if(!this.session){n.unavailable=!0,o();return}if(await Fe.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 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 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 m.Url(t),`[${r.toUpperCase()}]${t.toLowerCase()}#${n}:${e}`}function os({id:e,auth:t,service:r,owner:n,latency:i=1e3,queue:s,onResponse:o,onError:a,onStream:u,realtimeGroup:c}){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&&!pe?.[s]&&(pe[s]=new Wi({breakWhenError:false,batchSize:1}));let g={stop:null,aborted:false,queue:s};te[e]=g;let f=null,d=()=>{te[e]===g&&delete te[e];},p=()=>new Promise((h,_)=>{let w=false;if(g.aborted){d(),h(ot(e));return}let b={seq:0},E=rs.call(this,e),R=u&&c?ts(b,u,E.onTransport):null,k=R?ns.call(this,c,R):null,U=()=>{E.done(R),k&&k.stop(),R&&R.close();};f=U;let D=0,x=false,v=0,C=async()=>{if(!(w||x)&&!(R&&R.warm()&&Date.now()-D<es)){x=true;try{for(;;){let q={id:e,service:r,owner:n};u&&(q.since=b.seq),D=Date.now();let Q=await T.bind(this)("csr-poll",q,{auth:t});if(w)return;let Ae=R?R.fromPoll(Q):u?Zi(Q,b,u):!1;R&&R.open();let $=is(Q);if(Q?.more&&Ae){v=0;continue}if($){v=0;return}if(v=Q?.more?v+1:0,Q?.more&&v<Xi)return;w=!0,o&&o(Q),clearInterval(L),U(),d(),h(Q);return}}catch(q){if(w)return;w=true,a&&a(q),clearInterval(L),U(),d(),_(q);}finally{x=false;}}},L=setInterval(C,i);R&&C(),g.stop=()=>{w||(w=true,clearInterval(L),U(),d(),h(ot(e)));};}),y=()=>{let h=te[e];h&&(h.stop?h.stop():(h.aborted=true,delete te[e]));};if(s){let h=new Promise((_,w)=>{let b=false,E=pe[s].add([async()=>{try{let R=await p();return b||(b=!0,_(R)),R}catch(R){throw b||(b=true,w(R)),R}}])[0];st[e]=E,g.stop=()=>{if(!b){g.aborted=true,f&&f();try{pe[s]&&pe[s].remove(st[e]);}catch{}delete st[e],d(),b=true,_(ot(e));}};});return Object.assign(h,{stop:y})}else return Object.assign(p(),{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 l('"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 l('"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=c=>{for(let g in c)if(typeof c[g]=="string"&&c[g].includes("$CLIENT_SECRET")){t=true;break}};if(e=m.Params(e,{url:c=>{if(!c||typeof c!="string")throw new l('"url" should be type: <string>.',{code:"INVALID_PARAMETER"});return m.Url(c),c.includes("$CLIENT_SECRET")&&(t=true),c},clientSecretName:"string",method:c=>{if(c&&typeof c!="string")throw new l('"method" should be either "GET" or "POST" or "DELETE" or "PUT".',{code:"INVALID_PARAMETER"});let g=c.toLowerCase();if(g!=="get"&&g!=="post"&&g!=="delete"&&g!=="put")throw new l('"method" should be either "GET" or "POST" or "DELETE" or "PUT".',{code:"INVALID_PARAMETER"});return g},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 o(c),c},data:c=>{if(c&&typeof c!="object")throw new l('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return o(c),c},params:c=>{if(c&&typeof c!="object")throw new l('"params" should be type: <object>.',{code:"INVALID_PARAMETER"});return o(c),c},expires:"number",queue:"string"},["clientSecretName","method","url"]),e.realtime&&!e.stream)throw new l('"realtime" requires "stream": true.',{code:"INVALID_PARAMETER"});if(!t)throw new l(`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(c=>{if(c.status==="running"||c.status==="pending"){let g=`[${e.method.toUpperCase()}]${e.url.toLowerCase()}`,f=e.service||this.service,d=e.owner||this.owner,p=`${g}#${f}:${c.id}`;Object.assign(c,{poll:y=>os.call(this,{id:p,auth:a,service:f,owner:d,latency:y?.latency||1e3,queue:e?.queue,onResponse:r,onError:n,onStream:y?.onStream||i,realtimeGroup:c?.realtime_group})});}return r?r(c):c}).catch(c=>{if(n)return n(c);throw c});if(e?.queue){let c="base:"+e.queue;return pe?.[c]||(pe[c]=new Wi({breakWhenError:false,batchSize:1})),new Promise((g,f)=>{pe[c].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=m.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 c={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,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 c)c[g]===void 0&&delete c[g];return (c.status==="running"||c.status==="pending")&&(c.poll=g=>os.call(this,{id:s+c.id,auth:i,service:r,owner:n,latency:g?.latency||1e3,queue:u?.qid,onResponse:g?.onResponse,onError:g?.onError,onStream:g?.onStream})),c}),a}async function ds(e){await this.__connection,e=m.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&&pe?.[a]&&(pe[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 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},u=null,c={stop:null,aborted:false},g=()=>{te[a.fullId]===c&&delete te[a.fullId];},f=()=>{a.stopped||(a.stopped=true,u&&u(),g(),a.resolve&&a.resolve(ot(a.fullId)));};c.stop=f;let d=new Promise(async(p,y)=>{a.resolve=p;try{await this.__connection;let h=!!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]=c;let b={seq:n},E=0,R=rs.call(this,a.fullId),k=i&&t?.realtimeGroup?ts(b,i,R.onTransport):null,U=k?ns.call(this,t.realtimeGroup,k):null,D=()=>{R.done(k),U&&U.stop(),k&&k.close();};for(u=D;;){let x=await T.bind(this)("csr-poll",{id:a.fullId,service:_,owner:w,since:b.seq},{auth:h});if(a.stopped)return;if(!Na(x)){D(),g(),s&&s(x),p(x);return}let v=k?k.fromPoll(x):Zi(x,b,i);k&&k.open();let C=is(x);if(x.more&&v){E=0;continue}if(E=x.more?E+1:0,!C&&(!x.more||E>=Xi)){D(),g(),s&&s(x),p(x);return}if(await new Promise(L=>setTimeout(L,k&&k.warm()?Math.max(r,es):r)),a.stopped)return}}catch(h){if(a.stopped)return;u&&u(),g(),o&&o(h),y(h);}});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=>(m.Email(r),r),subject:"string",message:"string"};return e=m.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 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=>m.Url(n),data:n=>n,sync:["boolean",()=>true]};if(Array.isArray(e))for(let n of e)n=m.Params(n,r);else e=m.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 l('"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 l('"url" is required in the second argument.',{code:"INVALID_PARAMETER"});m.Url(t.url);let n=(await this.admin_endpoint)?.forward_request;if(!n)throw new l("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 l("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 l("User login is required.",{code:"INVALID_REQUEST"});let g={"Content-Meta":u,Authorization:c};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 l(p?.message||(typeof p=="string"?p:JSON.stringify(p)),{code:p?.code||"ERROR"})}if(t.onStream&&f.body){let p=f.body.getReader(),y=new TextDecoder,h="";for(;;){let{done:_,value:w}=await p.read();if(_)break;let b=y.decode(w,{stream:true});h+=b;try{t.onStream(b);}catch(E){console.error(E);}}return h}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=m.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 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 l(`"user_id" cannot be the user's own ID.`,{code:"INVALID_PARAMETER"});return m.UserId(e,'"user_id"')}async function _s(e,t){if(e=j(e,{ignoreEmpty:true}).data,e=m.Params(e,{subscriber:n=>m.UserId(n,'User ID in "subscriber"'),subscription:at.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 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=m.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 l("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}=m.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}=m.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}=m.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=m.Params(e||{},{user_id:o=>{if(o!==this.__user.user_id&&!r)throw new l("No access.",{code:"INVALID_REQUEST"});return o},group:o=>m.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 c=/^\d+$/.test(a[0])?parseInt(a[0]):a[0];s.push({timestamp:o.stmp,group:c,subscribed_email:a[1],active:u});}return n?.list?(n.list=s,n):s}async function Ts(e){await this.__connection;let t=m.Params(e||{},{email:r=>Array.isArray(r)&&r.length>0?r.length===1?m.Email(r[0]):r.map(n=>m.Email(n)):m.Email(r),group:r=>m.newsletterGroup(r),redirect:r=>m.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=m.Params(e||{},{group:r=>m.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 T.bind(this)("register-newsletter-group",t,{auth:true})}async function Ss(e){await this.__connection;let t=m.Params(e||{},{group:r=>m.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=m.Params(e,{group:r=>m.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=m.Params(e,{searchFor:["message_id","timestamp","subject","complaint","read","bounced"],value:u=>{if(typeof u!==n[e.searchFor])throw new l(`"value" type does not match the type of "${e.searchFor}" index.`,{code:"INVALID_PARAMETER"});if(typeof u=="string"&&!u)throw new l('"value" should not be empty string.',{code:"INVALID_PARAMETER"});return u},range:u=>{if(!e.hasOwnProperty("value")||typeof u!=typeof e.value)throw new l('"range" should match type of "value".',{code:"INVALID_PARAMETER"});return u},condition:[">",">=","=","<","<=","gt","gte","eq","lt","lte",()=>"="],group:u=>{let c=m.newsletterGroup(u);if(c===0)return 0;if(typeof c=="string")return c;if(!this.session)throw new l("User should be logged in.",{code:"INVALID_REQUEST"});if(u==="authorized")return 1;if(!r&&c>parseInt(this.user?.access_group||this.session?.idToken?.payload?.access_group))throw new l("User has no access.",{code:"INVALID_REQUEST"});return c}},["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 c={};for(let g in o)c[g]=u[o[g]]||a[g];return c.bounced=String(c.bounced),c}),s}async function Us(e){let t=m.Params(e,{user_id:n=>m.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 T.bind(this)("block-account",t,{auth:true})}async function Ds(e){let t=m.Params(e,{user_id:n=>m.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 T.bind(this)("block-account",t,{auth:true})}async function xs(e){let t=m.Params(e,{user_id:n=>m.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 T.bind(this)("remove-account",t,{auth:true})}async function Cs(e,t){let r={email:s=>m.Email(s),password:s=>m.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=>m.Birthdate(s),phone_number:s=>m.PhoneNumber(s),picture:s=>{if(s)return m.Url(s)},profile:s=>{if(s)return m.Url(s)},website:s=>{if(s)return m.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=m.Params(e,r,["email"]);if(t=m.Params(t,{confirmation_url:s=>{let o=s;if(typeof s=="string")o=m.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:m.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 T.bind(this)("admin-signup",n,{auth:true})}async function Ls(e){let t={email:s=>m.Email(s),password:s=>m.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=>m.Birthdate(s),phone_number:s=>m.PhoneNumber(s),picture:s=>s?m.Url(s):"",profile:s=>s?m.Url(s):"",website:s=>s?m.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=m.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 T.bind(this)("admin-signup",n,{auth:true})}async function Os(e){if(e=m.Params(e,{user_id:r=>m.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 T.bind(this)("grant-access",e,{auth:true})}async function Ms(e,t){if(e=m.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 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=m.Params(e,{email:r=>m.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 T.bind(this)("invitation-list",Object.assign({mode:"cancel"},e),{auth:true})}async function qs(e){if(e=m.Params(e,{email:r=>m.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 T.bind(this)("invitation-list",Object.assign({mode:"resend"},e),{auth:true})}async function Vs(e){let t=m.Params(e,{user_id:o=>m.UserId(o,'"user_id"'),email:o=>m.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?m.Birthdate(o):"",phone_number:o=>o?m.PhoneNumber(o):"",email_public:"boolean",phone_number_public:"boolean",address_public:"boolean",gender_public:"boolean",birthdate_public:"boolean",misc:"string",picture:o=>o?m.Url(o):"",profile:o=>o?m.Url(o):"",nickname:"string",website:o=>o?m.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 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"})}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 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 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 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 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 l("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 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 T.bind(this)("push-notification",i,{auth:true}),"SUCCESS: Notification sent."}async function Hs(e){await this.__connection,e=m.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=m.Params(e||{},{search:["spell","name",()=>"spell"],value:"string"}),await T.bind(this)("getspell",e)}async function Ws(e){await this.__connection,e=m.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
|
+
`,c=new Blob([u],{type:"application/javascript"});Ee=new Worker(URL.createObjectURL(c)),Ee.onmessage=g=>{a.readyState===1&&a.send(JSON.stringify({action:"keepAlive"}));},i(a);},a.onmessage=async u=>{let c="";try{c=JSON.parse(decodeURI(u.data)),this.log("socket onmessage",c);}catch{return}let g;switch(!0){case !!c?.["#message"]:g="message";break;case !!c?.["#private"]:g="private";break;case !!c?.["#notice"]:g="notice";break;case !!c?.["#rtc"]:g="rtc";break;case !!c?.["#error"]:g="error";break}if(!g)return;let f={type:g,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(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]),ge[f.sender_cid]&&delete ge[f.sender_cid],N?.[f.sender_cid]&&ue.bind(this)({cid:f.sender_cid}),f.type="rtc:closed",e(f);return}if(d.candidate&&Tr.bind(this)(d.candidate,f.sender_cid),d.sdpoffer&&(Ir.bind(this)(d.sdpoffer,f.sender_cid),ge[f.sender_cid]||(ge[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}):ge[f.sender_cid]&&(delete ge[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 l("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 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=m.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{m.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}),be!==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 qe(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&&!be)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})),be=r,{type:"success",message:r?`Joined realtime message group: "${r}".`:"Left realtime message group."}}async function Hi(e,t){e=m.Params(e,{user_id:n=>m.UserId(n,'User ID in "user_id"'),group:["string",()=>{if(!be)throw new l('No group has been joined. Otherwise "group" is required.',{code:"INVALID_REQUEST"});return be}]});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=m.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 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",pe={},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,y)=>{if(e.seq=d,!(!t||typeof p!="string"||p===""))try{t(p,d,y);}catch(h){console.error(h);}},c=()=>{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,c());},fromPoll:d=>{if(s)return false;let p=e.seq,y=e.seq,h=Array.isArray(d?.chunks)?d.chunks:[];for(let w of h){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>y&&(y=w.seq);}typeof d?.last_seq=="number"&&d.last_seq>y&&(y=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>y)break;let b=n.get(w);n.delete(w),u(w,b.txt,b.via);}return y>e.seq&&(e.seq=y),c(),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&&c())));},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=c=>{if(n.stopped)return;let g=c?.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 y=d.seq;typeof y=="string"&&y!==""&&(y=Number(y)),t.fromSocket(y,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,g=n.joined;if(n.opened=null,n.joined=false,s(),!(!g&&!c))try{let f=this.__socket?await this.__socket:null;if(c&&f===c){await Ut.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 c=this.__socket?await this.__socket:null;if(n.stopped){o();return}if(!c){if(!this.session){n.unavailable=!0,o();return}if(await Fe.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 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 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 m.Url(t),`[${r.toUpperCase()}]${t.toLowerCase()}#${n}:${e}`}function os({id:e,auth:t,service:r,owner:n,latency:i=1e3,queue:s,onResponse:o,onError:a,onStream:u,realtimeGroup:c}){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&&!pe?.[s]&&(pe[s]=new Wi({breakWhenError:false,batchSize:1}));let g={stop:null,aborted:false,queue:s};te[e]=g;let f=null,d=()=>{te[e]===g&&delete te[e];},p=()=>new Promise((h,_)=>{let w=false;if(g.aborted){d(),h(ot(e));return}let b={seq:0},E=rs.call(this,e),R=u&&c?ts(b,u,E.onTransport):null,k=R?ns.call(this,c,R):null,U=()=>{E.done(R),k&&k.stop(),R&&R.close();};f=U;let D=0,x=false,v=0,C=async()=>{if(!(w||x)&&!(R&&R.warm()&&Date.now()-D<es)){x=true;try{for(;;){let q={id:e,service:r,owner:n};u&&(q.since=b.seq),D=Date.now();let Q=await T.bind(this)("csr-poll",q,{auth:t});if(w)return;let Ae=R?R.fromPoll(Q):u?Zi(Q,b,u):!1;R&&R.open();let $=is(Q);if(Q?.more&&Ae){v=0;continue}if($){v=0;return}if(v=Q?.more?v+1:0,Q?.more&&v<Xi)return;w=!0,o&&o(Q),clearInterval(L),U(),d(),h(Q);return}}catch(q){if(w)return;w=true,a&&a(q),clearInterval(L),U(),d(),_(q);}finally{x=false;}}},L=setInterval(C,i);R&&C(),g.stop=()=>{w||(w=true,clearInterval(L),U(),d(),h(ot(e)));};}),y=()=>{let h=te[e];h&&(h.stop?h.stop():(h.aborted=true,delete te[e]));};if(s){let h=new Promise((_,w)=>{let b=false,E=pe[s].add([async()=>{try{let R=await p();return b||(b=!0,_(R)),R}catch(R){throw b||(b=true,w(R)),R}}])[0];st[e]=E,g.stop=()=>{if(!b){g.aborted=true,f&&f();try{pe[s]&&pe[s].remove(st[e]);}catch{}delete st[e],d(),b=true,_(ot(e));}};});return Object.assign(h,{stop:y})}else return Object.assign(p(),{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 l('"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 l('"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=c=>{for(let g in c)if(typeof c[g]=="string"&&c[g].includes("$CLIENT_SECRET")){t=true;break}};if(e=m.Params(e,{url:c=>{if(!c||typeof c!="string")throw new l('"url" should be type: <string>.',{code:"INVALID_PARAMETER"});return m.Url(c),c.includes("$CLIENT_SECRET")&&(t=true),c},clientSecretName:"string",method:c=>{if(c&&typeof c!="string")throw new l('"method" should be either "GET" or "POST" or "DELETE" or "PUT".',{code:"INVALID_PARAMETER"});let g=c.toLowerCase();if(g!=="get"&&g!=="post"&&g!=="delete"&&g!=="put")throw new l('"method" should be either "GET" or "POST" or "DELETE" or "PUT".',{code:"INVALID_PARAMETER"});return g},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 o(c),c},data:c=>{if(c&&typeof c!="object")throw new l('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return o(c),c},params:c=>{if(c&&typeof c!="object")throw new l('"params" should be type: <object>.',{code:"INVALID_PARAMETER"});return o(c),c},expires:"number",queue:"string"},["clientSecretName","method","url"]),e.realtime&&!e.stream)throw new l('"realtime" requires "stream": true.',{code:"INVALID_PARAMETER"});if(!t)throw new l(`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(c=>{if(c.status==="running"||c.status==="pending"){let g=`[${e.method.toUpperCase()}]${e.url.toLowerCase()}`,f=e.service||this.service,d=e.owner||this.owner,p=`${g}#${f}:${c.id}`;Object.assign(c,{poll:y=>os.call(this,{id:p,auth:a,service:f,owner:d,latency:y?.latency||1e3,queue:e?.queue,onResponse:r,onError:n,onStream:y?.onStream||i,realtimeGroup:c?.realtime_group})});}return r?r(c):c}).catch(c=>{if(n)return n(c);throw c});if(e?.queue){let c="base:"+e.queue;return pe?.[c]||(pe[c]=new Wi({breakWhenError:false,batchSize:1})),new Promise((g,f)=>{pe[c].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=m.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 c={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 c)c[g]===void 0&&delete c[g];return (c.status==="running"||c.status==="pending")&&(c.poll=g=>os.call(this,{id:s+c.id,auth:i,service:r,owner:n,latency:g?.latency||1e3,queue:u?.qid,onResponse:g?.onResponse,onError:g?.onError,onStream:g?.onStream})),c}),a}async function ds(e){await this.__connection,e=m.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&&pe?.[a]&&(pe[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 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},u=null,c={stop:null,aborted:false},g=()=>{te[a.fullId]===c&&delete te[a.fullId];},f=()=>{a.stopped||(a.stopped=true,u&&u(),g(),a.resolve&&a.resolve(ot(a.fullId)));};c.stop=f;let d=new Promise(async(p,y)=>{a.resolve=p;try{await this.__connection;let h=!!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]=c;let b={seq:n},E=0,R=rs.call(this,a.fullId),k=i&&t?.realtimeGroup?ts(b,i,R.onTransport):null,U=k?ns.call(this,t.realtimeGroup,k):null,D=()=>{R.done(k),U&&U.stop(),k&&k.close();};for(u=D;;){let x=await T.bind(this)("csr-poll",{id:a.fullId,service:_,owner:w,since:b.seq},{auth:h});if(a.stopped)return;if(!Na(x)){D(),g(),s&&s(x),p(x);return}let v=k?k.fromPoll(x):Zi(x,b,i);k&&k.open();let C=is(x);if(x.more&&v){E=0;continue}if(E=x.more?E+1:0,!C&&(!x.more||E>=Xi)){D(),g(),s&&s(x),p(x);return}if(await new Promise(L=>setTimeout(L,k&&k.warm()?Math.max(r,es):r)),a.stopped)return}}catch(h){if(a.stopped)return;u&&u(),g(),o&&o(h),y(h);}});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=>(m.Email(r),r),subject:"string",message:"string"};return e=m.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 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=>m.Url(n),data:n=>n,sync:["boolean",()=>true]};if(Array.isArray(e))for(let n of e)n=m.Params(n,r);else e=m.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 l('"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 l('"url" is required in the second argument.',{code:"INVALID_PARAMETER"});m.Url(t.url);let n=(await this.admin_endpoint)?.forward_request;if(!n)throw new l("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 l("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 l("User login is required.",{code:"INVALID_REQUEST"});let g={"Content-Meta":u,Authorization:c};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 l(p?.message||(typeof p=="string"?p:JSON.stringify(p)),{code:p?.code||"ERROR"})}if(t.onStream&&f.body){let p=f.body.getReader(),y=new TextDecoder,h="";for(;;){let{done:_,value:w}=await p.read();if(_)break;let b=y.decode(w,{stream:true});h+=b;try{t.onStream(b);}catch(E){console.error(E);}}return h}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=m.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 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 l(`"user_id" cannot be the user's own ID.`,{code:"INVALID_PARAMETER"});return m.UserId(e,'"user_id"')}async function _s(e,t){if(e=j(e,{ignoreEmpty:true}).data,e=m.Params(e,{subscriber:n=>m.UserId(n,'User ID in "subscriber"'),subscription:at.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 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=m.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 l("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}=m.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}=m.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}=m.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=m.Params(e||{},{user_id:o=>{if(o!==this.__user.user_id&&!r)throw new l("No access.",{code:"INVALID_REQUEST"});return o},group:o=>m.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 c=/^\d+$/.test(a[0])?parseInt(a[0]):a[0];s.push({timestamp:o.stmp,group:c,subscribed_email:a[1],active:u});}return n?.list?(n.list=s,n):s}async function Ts(e){await this.__connection;let t=m.Params(e||{},{email:r=>Array.isArray(r)&&r.length>0?r.length===1?m.Email(r[0]):r.map(n=>m.Email(n)):m.Email(r),group:r=>m.newsletterGroup(r),redirect:r=>m.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=m.Params(e||{},{group:r=>m.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 T.bind(this)("register-newsletter-group",t,{auth:true})}async function Ss(e){await this.__connection;let t=m.Params(e||{},{group:r=>m.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=m.Params(e,{group:r=>m.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=m.Params(e,{searchFor:["message_id","timestamp","subject","complaint","read","bounced"],value:u=>{if(typeof u!==n[e.searchFor])throw new l(`"value" type does not match the type of "${e.searchFor}" index.`,{code:"INVALID_PARAMETER"});if(typeof u=="string"&&!u)throw new l('"value" should not be empty string.',{code:"INVALID_PARAMETER"});return u},range:u=>{if(!e.hasOwnProperty("value")||typeof u!=typeof e.value)throw new l('"range" should match type of "value".',{code:"INVALID_PARAMETER"});return u},condition:[">",">=","=","<","<=","gt","gte","eq","lt","lte",()=>"="],group:u=>{let c=m.newsletterGroup(u);if(c===0)return 0;if(typeof c=="string")return c;if(!this.session)throw new l("User should be logged in.",{code:"INVALID_REQUEST"});if(u==="authorized")return 1;if(!r&&c>parseInt(this.user?.access_group||this.session?.idToken?.payload?.access_group))throw new l("User has no access.",{code:"INVALID_REQUEST"});return c}},["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 c={};for(let g in o)c[g]=u[o[g]]||a[g];return c.bounced=String(c.bounced),c}),s}async function Us(e){let t=m.Params(e,{user_id:n=>m.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 T.bind(this)("block-account",t,{auth:true})}async function Ds(e){let t=m.Params(e,{user_id:n=>m.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 T.bind(this)("block-account",t,{auth:true})}async function xs(e){let t=m.Params(e,{user_id:n=>m.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 T.bind(this)("remove-account",t,{auth:true})}async function Cs(e,t){let r={email:s=>m.Email(s),password:s=>m.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=>m.Birthdate(s),phone_number:s=>m.PhoneNumber(s),picture:s=>{if(s)return m.Url(s)},profile:s=>{if(s)return m.Url(s)},website:s=>{if(s)return m.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=m.Params(e,r,["email"]);if(t=m.Params(t,{confirmation_url:s=>{let o=s;if(typeof s=="string")o=m.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:m.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 T.bind(this)("admin-signup",n,{auth:true})}async function Ls(e){let t={email:s=>m.Email(s),password:s=>m.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=>m.Birthdate(s),phone_number:s=>m.PhoneNumber(s),picture:s=>s?m.Url(s):"",profile:s=>s?m.Url(s):"",website:s=>s?m.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=m.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 T.bind(this)("admin-signup",n,{auth:true})}async function Os(e){if(e=m.Params(e,{user_id:r=>m.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 T.bind(this)("grant-access",e,{auth:true})}async function Ms(e,t){if(e=m.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 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=m.Params(e,{email:r=>m.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 T.bind(this)("invitation-list",Object.assign({mode:"cancel"},e),{auth:true})}async function qs(e){if(e=m.Params(e,{email:r=>m.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 T.bind(this)("invitation-list",Object.assign({mode:"resend"},e),{auth:true})}async function Vs(e){let t=m.Params(e,{user_id:o=>m.UserId(o,'"user_id"'),email:o=>m.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?m.Birthdate(o):"",phone_number:o=>o?m.PhoneNumber(o):"",email_public:"boolean",phone_number_public:"boolean",address_public:"boolean",gender_public:"boolean",birthdate_public:"boolean",misc:"string",picture:o=>o?m.Url(o):"",profile:o=>o?m.Url(o):"",nickname:"string",website:o=>o?m.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 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"})}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 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 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 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 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 l("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 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 T.bind(this)("push-notification",i,{auth:true}),"SUCCESS: Notification sent."}async function Hs(e){await this.__connection,e=m.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=m.Params(e||{},{search:["spell","name",()=>"spell"],value:"string"}),await T.bind(this)("getspell",e)}async function Ws(e){await this.__connection,e=m.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}
|
|
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 I=class{constructor(t,r,n,i){this.__version="2.0.
|
|
217
|
+
Watch the video here: ${t.video}`}var I=class{constructor(t,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(t){try{return m.UserId(t),!0}catch{return false}},url(t){try{return m.Url(t),!0}catch{return false}},phoneNumber(t){try{return m.PhoneNumber(t),!0}catch{return false}},birthdate(t){try{return m.Birthdate(t),!0}catch{return false}},email(t){try{return m.Email(t),!0}catch{return false}},params(t,r,n){return m.Params(t,r,n)}};this.util={MD5:G,generateRandom:Re,toBase62:Mr,fromBase62:se,decodeProjectId:Vt,formatServiceId:$t,extractFormData:j,terminatePendingRequests:di,request:(t,r,n)=>T.bind(this)(t,r,n,{ignoreService:true})};this.__network_logs=false;this.__endpoint_version="v2";this.__public_identifier="";this.bearerToken="";this.registerTicket=Bn.bind(this);this.unregisterTicket=Kn.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 b=Vt(t);n&&typeof n=="object"&&(i=n),r&&typeof r=="object"&&(n=r),r=b.owner,t=b.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{m.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=$t(t,r);}catch{this.project_id="";}let c=true,g=false,f=null;if(n&&(typeof n.refetchServiceInfo=="boolean"&&(g=n.refetchServiceInfo),typeof n.autoLogin=="boolean"&&(c=n.autoLogin),n.encryption&&(f=an(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 d=`https://${this.target_cdn}.cloudfront.net`,p=t.substring(0,4);this.admin_endpoint=fetch(`${d}/${p}/admin-${this.__endpoint_version}.json`).then(b=>b.blob()).then(b=>new Promise((E,R)=>{let k=new FileReader;k.onloadend=()=>E(k.result),k.onerror=R,k.readAsDataURL(b);})).then(b=>{try{return typeof b=="string"?JSON.parse(atob(b.split(",")[1])):null}catch{throw new l("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(b=>b.blob()).then(b=>new Promise((E,R)=>{let k=new FileReader;k.onloadend=()=>E(k.result),k.onerror=R,k.readAsDataURL(b);})).then(b=>{try{return typeof b=="string"?JSON.parse(atob(b.split(",")[1])):null}catch{throw new l("Service does not exist. Create your service from skapi.com",{code:"NOT_EXISTS"})}});let y=Y();if(y&&!window.sessionStorage)throw this._alert("This browser is not supported."),new Error("This browser is not supported.");let h=y?JSON.parse(window.sessionStorage.getItem(`${t}#${r}`)||"null"):null;if(this.log("constructor:restore",h),h?.connection){for(let b in h)this[b]=h[b];h.__public_identifier||(this.__public_identifier=`${this.service}:${this.owner}:${Re(16)}`);}ln.bind(this)(f),this.__authConnection=(async()=>{let b=await this.admin_endpoint,E={UserPoolId:b.userpool_id,ClientId:b.userpool_client};qt()&&(E.Storage=window.localStorage),this.userPool=new CognitoUserPool(E);try{this.user||await J.bind(this)().getSession({skipUserUpdateEventTrigger:!0}),this.user&&(!h?.connection&&!c?ye.bind(this)():(f&&Sn.bind(this)(),this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user)));}catch{}})();let _=`${this.service}/${this.owner}`,w=y?window.sessionStorage.getItem(`${_}:uniqueids`):null;if(w)try{let b=JSON.parse(w);this.__my_unique_ids=b&&typeof b=="object"&&!Array.isArray(b)?{[_]:b}:{};}catch{this.__my_unique_ids={};}this.__connection=(async()=>{let b=null;await this.record_endpoint,h?.connection||(b=this._updateConnection({refresh:g}));let E=()=>{if(this.__class_properties_has_been_cached)return;let R=()=>{let k={},U=["__startKeyHistory","__disabledAccount","__cached_requests","__request_signup_confirmation","__public_identifier","connection"];if(this.connection){for(let D of U)k[D]=this[D];if(f&&(k.__cached_requests={},k.__startKeyHistory={}),y){let D=`${t}#${r}`;try{window.sessionStorage.setItem(D,JSON.stringify(k));}catch{try{let v=Object.assign({},k,{__cached_requests:{},__startKeyHistory:{}});window.sessionStorage.setItem(D,JSON.stringify(v));}catch{try{window.sessionStorage.removeItem(D);}catch{}}}}this.__class_properties_has_been_cached=true;}};return b instanceof Promise?b.then(()=>R()):R()};return y&&(window.addEventListener("beforeunload",()=>{this.closeRealtime(),E();}),window.addEventListener("visibilitychange",()=>{E();})),await b,await this.__authConnection,this.connection})(),this.__connection.then(b=>{((b?.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){Y()&&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||(Y()&&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 T.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,Y()){let r=`Built with:
|
|
218
218
|
%c\r
|
|
219
219
|
$$\\ $$\\ \r
|
|
220
220
|
$$ | \\__|\r
|