skapi-js 2.0.0-rc.3 → 2.0.0-rc.4

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.
@@ -213,9 +213,9 @@ var zs=Object.create;var Fe=Object.defineProperty;var Gr=Object.getOwnPropertyDe
213
213
  }
214
214
 
215
215
  runInterval(); // Start interval
216
- `,o=new Blob([s],{type:"application/javascript"});Te=new Worker(URL.createObjectURL(o)),Te.onmessage=a=>{i.readyState===1&&i.send(JSON.stringify({action:"keepAlive"}));},n(i);},i.onmessage=async s=>{let o="";try{o=JSON.parse(decodeURI(s.data)),this.log("socket onmessage",o);}catch{return}let a;switch(true){case !!o?.["#message"]:a="message";break;case !!o?.["#private"]:a="private";break;case !!o?.["#notice"]:a="notice";break;case !!o?.["#rtc"]:a="rtc";break;case !!o?.["#error"]:a="error";break}if(!a)return;let u={type:a,message:o?.["#rtc"]||o?.["#message"]||o?.["#private"]||o?.["#notice"]||o?.["#error"]||null,sender:o?.["#user_id"]||null,sender_cid:o?.["#scid"]?"cid:"+o["#scid"]:null,sender_rid:o?.["#srid"]||null,code:o?.["#code"]||null};if(a==="notice")r(u);else if(a==="rtc"){if(u.sender!==this.user.user_id){let c=u.message;if(c.hungup){oe[u.sender_cid]&&(oe[u.sender_cid](false),delete oe[u.sender_cid]),ge[u.sender_cid]&&delete ge[u.sender_cid],U?.[u.sender_cid]&&ae.bind(this)({cid:u.sender_cid}),u.type="rtc:closed",r(u);return}if(c.candidate&&$r.bind(this)(c.candidate,u.sender_cid),c.sdpoffer&&(Br.bind(this)(c.sdpoffer,u.sender_cid),ge[u.sender_cid]||(ge[u.sender_cid]=u.sender_cid,delete u.message,u.connectRTC=ts.bind(this)(u),u.type="rtc:incoming",u.hangup=(()=>{U[u.sender_cid]?ae.bind(this)({cid:u.sender_cid}):ge[u.sender_cid]&&(delete ge[u.sender_cid],i.send(JSON.stringify({action:"rtc",uid:u.sender_cid,content:{hungup:this.user.user_id},token:this.session.accessToken.jwtToken})));}).bind(this),r(u))),c.pickup&&oe[u.sender_cid]&&(oe[u.sender_cid](true),delete oe[u.sender_cid]),c.sdpanswer&&U[u.sender_cid])if(U[u.sender_cid].signalingState==="have-local-offer")await U[u.sender_cid].setRemoteDescription(new RTCSessionDescription(c.sdpanswer));else throw new f("Invalid signaling state.",{code:"INVALID_REQUEST"})}}else r(u);},i.onclose=()=>{at?(this.log("realtime onclose","WebSocket connection closed."),r({type:"close",message:"WebSocket connection closed."})):(this.log("realtime onclose","WebSocket unexpected close."),r({type:"error",message:"Skapi: WebSocket unexpected close."}),Ye++,Ye<3?(this.log("realtime onclose","Reconnecting to WebSocket server..."+Ye),r({type:"reconnect",message:"Reconnecting to WebSocket server..."+Ye}),Jt.bind(this)(r,3e3,"reconnect")):(this.log("realtime onclose","Max reconnection attempts reached."),r({type:"error",message:"Skapi: Max reconnection attempts reached."})));},i.onerror=()=>{this.log("realtime onerror","WebSocket connection error."),r({type:"error",message:"Skapi: WebSocket connection error."});};},e);});}async function ss(r,e,t){if(typeof window>"u"||window._runningInNodeJS)throw new f("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});let n=this.__socket?await this.__socket:this.__socket;if(!n)throw new f("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});if(!e)throw new f("No recipient.",{code:"INVALID_REQUEST"});await Je.bind(this)(),r=M(r).data;let i="";if(t&&(t=m.Params(t,{config:{always:"boolean"},title:"string",body:"string"},["title","body"]),i=JSON.stringify({title:t.title,body:t.body}),new Blob([i]).size>3072))throw new f("Notification size exceeds 3kb.",{code:"INVALID_PARAMETER"});if(n.readyState===1){try{m.UserId(e),n.send(JSON.stringify({action:"sendMessage",uid:e,content:r,notification:i,notificationConfig:t?.config||{},token:`IdT:${this.service}:${this.owner}:`+(this.bearerToken||this.session?.idToken?.jwtToken||"null")}));}catch(s){if(this.log("postRealtime:err",{err:s}),Re!==e)throw new f(`User has not joined to the recipient group. Run joinRealtime({ group: "${e}" })`,{code:"INVALID_REQUEST"});n.send(JSON.stringify({action:"broadcast",rid:e,content:r,notification:i,notificationConfig:t?.config||{},token:`IdT:${this.service}:${this.owner}:`+(this.bearerToken||this.session?.idToken?.jwtToken||"null")}));}return {type:"success",message:"Message sent."}}throw new f("Realtime connection is not open. Try reconnecting with connectRealtime().",{code:"INVALID_REQUEST"})}async function Kr(r){if(typeof window>"u"||window._runningInNodeJS)throw new f("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});let e=this.__socket?await this.__socket:this.__socket;if(!e)throw new f("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});await Je.bind(this)(),r=M(r,{nullIfEmpty:true}).data;let{group:t=null}=r;if(!t&&!Re)return {type:"success",message:"Left realtime message group."};if(t!==null&&typeof t!="string")throw new f('"group" must be a string | null.',{code:"INVALID_PARAMETER"});return e.send(JSON.stringify({action:"joinRoom",rid:t,token:this.session.accessToken.jwtToken})),Re=t,{type:"success",message:t?`Joined realtime message group: "${t}".`:"Left realtime message group."}}async function os(r,e){r=m.Params(r,{user_id:n=>m.UserId(n,'User ID in "user_id"'),group:["string",()=>{if(!Re)throw new f('No group has been joined. Otherwise "group" is required.',{code:"INVALID_REQUEST"});return Re}]});let t=await T.bind(this)("get-ws-group",r,{fetchOptions:e,auth:true,method:"post"});return t.list=t.list.map(n=>({user_id:n.uid.split("#")[1],cid:"cid:"+n.cid})),t}async function as(r,e){if(await this.__connection,r||(r={searchFor:"group",value:" ",condition:">"}),r=m.Params(r,{searchFor:["group","number_of_users",()=>"group"],value:["string","number",()=>r?.searchFor&&r?.searchFor==="number_of_users"?0:" "],condition:[">",">=","=","<","<=","!=","gt","gte","eq","lt","lte","ne"],range:["string","number"]}),r.condition||(r.value===" "||!r.value?r.condition=">":r.condition="="),r.range&&r.condition&&delete r.condition,r.searchFor==="number_of_users"&&typeof r.value!="number")throw new f('"value" must be a number.',{code:"INVALID_PARAMETER"});if(r.searchFor==="group"&&typeof r.value!="string")throw new f('"value" must be a string.',{code:"INVALID_PARAMETER"});if(r.hasOwnProperty("range")&&typeof r.range!=typeof r.value)throw new f(`"range" must be a ${typeof r.value}.`,{code:"INVALID_PARAMETER"});let t=await T.bind(this)("get-ws-group",r,{fetchOptions:e,auth:true,method:"post"});return t.list=t.list.map(n=>({group:n.rid.split("#")[1],number_of_users:n.cnt})),t}var us=typeof FormData<"u",cs=typeof HTMLFormElement<"u",ls=typeof SubmitEvent<"u",pe={},ut={},me={};function Hr(r){return Object.freeze({id:r,status:"stopped"})}function ds(r){return !!r&&typeof r=="object"&&r.status==="stopped"}function fs({id:r,auth:e,service:t,owner:n,latency:i=1e3,queue:s,onResponse:o,onError:a}){if(typeof i!="number")throw new f('"latency" should be a number.',{code:"INVALID_PARAMETER"});if(i<0)throw new f('"latency" should be a non-negative number.',{code:"INVALID_PARAMETER"});s&&!pe?.[s]&&(pe[s]=new nt({breakWhenError:false,batchSize:1}));let u={stop:null,aborted:false,queue:s};me[r]=u;let c=()=>{me[r]===u&&delete me[r];},l=()=>new Promise((h,p)=>{let g=false;if(u.aborted){c(),h(Hr(r));return}let _=setInterval(async()=>{try{let w=await T.bind(this)("csr-poll",{id:r,service:t,owner:n},{auth:e});if(w.status==="running"||w.status==="pending"||g)return;g=!0,o&&o(w),clearInterval(_),c(),h(w);}catch(w){if(g)return;g=true,a&&a(w),clearInterval(_),c(),p(w);}},i);u.stop=()=>{g||(g=true,clearInterval(_),c(),h(Hr(r)));};}),d=()=>{let h=me[r];h&&(h.stop?h.stop():(h.aborted=true,delete me[r]));};if(s){let h=new Promise((p,g)=>{let _=false,w=pe[s].add([async()=>{try{let b=await l();return _||(_=!0,p(b)),b}catch(b){throw _||(_=true,g(b)),b}}])[0];ut[r]=w,u.stop=()=>{if(!_){u.aborted=true;try{pe[s]&&pe[s].remove(ut[r]);}catch{}delete ut[r],c(),_=true,p(Hr(r));}};});return Object.assign(h,{stop:d})}else return Object.assign(l(),{stop:d})}function hs(r){let e=0,t=[];if(r?.id){if(r.url&&r.method){let n=r.service||this.service;t.push(`[${r.method.toUpperCase()}]${r.url.toLowerCase()}#${n}:${r.id}`);}t.push(r.id);}else if(r?.queue)for(let n in me)me[n]?.queue===r.queue&&t.push(n);else for(let n in me)t.push(n);for(let n of t){let i=me[n];i&&(i.stop?i.stop():(i.aborted=true,delete me[n]),e+=1);}return e}function gs(r,e){if(!r.queue)throw new f('"queue" is required.',{code:"INVALID_PARAMETER"});let t={service:r.service||this.service,owner:r.owner||this.owner,queue:r.queue+":"};return T.bind(this)("csr-poll",t,{auth:true})}async function ps(r){let e=false;if(typeof r.poll=="number"&&r.poll<0)throw new f('"poll" should be a non-negative number.',{code:"INVALID_PARAMETER"});let t=r?.onResponse,n=r?.onError,i=typeof r.poll=="number"?r.poll:r.poll?1e3:0;delete r.poll,i&&!r.queue&&(r.queue=(this.__user?.user_id||"anonymous")+"-"+De());let s=u=>{for(let c in u)if(typeof u[c]=="string"&&u[c].includes("$CLIENT_SECRET")){e=true;break}};if(r=m.Params(r,{url:u=>{if(!u||typeof u!="string")throw new f('"url" should be type: <string>.',{code:"INVALID_PARAMETER"});return m.Url(u),u.includes("$CLIENT_SECRET")&&(e=true),u},clientSecretName:"string",method:u=>{if(u&&typeof u!="string")throw new f('"method" should be either "GET" or "POST" or "DELETE" or "PUT".',{code:"INVALID_PARAMETER"});let c=u.toLowerCase();if(c!=="get"&&c!=="post"&&c!=="delete"&&c!=="put")throw new f('"method" should be either "GET" or "POST" or "DELETE" or "PUT".',{code:"INVALID_PARAMETER"});return c},headers:u=>{if(u&&typeof u!="object")throw new f('"headers" should be type: <object>.',{code:"INVALID_PARAMETER"});return s(u),u},data:u=>{if(u&&typeof u!="object")throw new f('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return s(u),u},params:u=>{if(u&&typeof u!="object")throw new f('"params" should be type: <object>.',{code:"INVALID_PARAMETER"});return s(u),u},expires:"number",queue:"string"},["clientSecretName","method","url"]),!e)throw new f(`At least one parameter value should include "$CLIENT_SECRET" in ${r.method.toLowerCase()==="post"?'"data"':'"params"'} or "headers".`,{code:"INVALID_PARAMETER"});await this.__connection;let o=!!this.__user,a=()=>T.bind(this)("csr",r,{auth:o,tokenHeaders:{accessToken:!!o}}).then(u=>{if(u.status==="running"||u.status==="pending"){let c=`[${r.method.toUpperCase()}]${r.url.toLowerCase()}`,l=r.service||this.service,d=r.owner||this.owner,h=`${c}#${l}:${u.id}`;Object.assign(u,{poll:p=>fs.call(this,{id:h,auth:o,service:l,owner:d,latency:p?.latency||1e3,queue:r?.queue,onResponse:t,onError:n})});}return t?t(u):u}).catch(u=>{if(n)return n(u);throw u});if(r?.queue){let u="base:"+r.queue;return pe?.[u]||(pe[u]=new nt({breakWhenError:false,batchSize:1})),new Promise((c,l)=>{pe[u].add([async()=>{try{let d=await a();if(i>0){let h=d.poll({latency:i});return c(h),h}return c(d),d}catch(d){throw l(d),d}}]);})}else return a()}async function ms(r,e){await this.__connection;let t=r.service||this.service,n=r.owner||this.owner;r=m.Params(r,{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=`[${r.method.toUpperCase()}]${r.url.toLowerCase()}#${t}:`,o={id:s,queue:r?.queue,status:r?.status,service:t,owner:n};r?.compact&&(o.compact=true),r?.queue_exact&&(o.queue_exact=true),r?.queue_exclude&&(o.queue_exclude=r.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:e});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 l in c)c[l]===void 0&&delete c[l];return (c.status==="running"||c.status==="pending")&&(c.poll=l=>fs.call(this,{id:s+c.id,auth:i,service:t,owner:n,latency:l?.latency||1e3,queue:u?.qid,onResponse:l?.onResponse,onError:l?.onError})),c}),a}async function _s(r){await this.__connection,r=m.Params(r,{url:"string",method:["GET","POST","DELETE","PUT"],id:"string",queue:"string"},["url","method","id"]);let e=r?.service||this.service,t=r?.owner||this.owner,n=!!this.__user,i=`[${r.method.toUpperCase()}]${r.url.toLowerCase()}#${e}`,s=r.id,o=`${i}:${s}`,a=r?.queue;return a&&pe?.[a]&&(pe[a].remove(ut[o]),delete ut[o]),T.bind(this)("csr-cancel",{id:o,service:e,owner:t},{auth:n})}async function bs(r){await this.__connection;let e={name:"string",email:t=>(m.Email(t),t),subject:"string",message:"string"};return r=m.Params(r,e,["name","email","subject","message"]),await T.bind(this)("send-inquiry",r),"SUCCESS: Inquiry has been sent."}async function ys(r,e){if(await this.__connection,us&&r instanceof FormData||cs&&r instanceof HTMLFormElement||ls&&r instanceof SubmitEvent){if(!e)throw new f("Url string as a second argument is required when form is passed.",{code:"INVALID_PARAMETER"});let n=M(r);r={url:e,data:n.data,sync:true};}let t={url:n=>m.Url(n),data:n=>n,sync:["boolean",()=>true]};if(Array.isArray(r))for(let n of r)n=m.Params(n,t);else r=m.Params(r,t);return T.bind(this)("post-secure",r,{auth:true})}async function ws(r,e){await this.__connection;let{auth:t=false,method:n="POST",bypassAwaitConnection:i=false,responseType:s,contentType:o,tokenHeaders:a,progress:u}=e||{};if(e=Object.assign({auth:t,method:n,bypassAwaitConnection:i,responseType:s,contentType:o,tokenHeaders:a},{fetchOptions:{progress:u}}),typeof r!="object"&&(o==="application/json"||o===void 0))throw new f('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return T.bind(this)("mock",r,e)}async function Es(r,e){if(await this.__connection,!e?.url||typeof e.url!="string")throw new f('"url" is required in the second argument.',{code:"INVALID_PARAMETER"});m.Url(e.url);let n=(await this.admin_endpoint)?.forward_request;if(!n)throw new f("forwardRequest is not available on this service region yet.",{code:"NOT_EXISTS"});let i=null,s=null,o=ls&&r instanceof SubmitEvent?r.target:cs&&r instanceof HTMLFormElement?r:null;o?i=new FormData(o):us&&r instanceof FormData?i=r:r!=null&&(i=JSON.stringify(r),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}},u=JSON.stringify(a);if(u.length>4096)throw new f("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 f("User login is required.",{code:"INVALID_REQUEST"});let l={"Content-Meta":u,Authorization:c};s&&(l["Content-Type"]=s);let d=await fetch(n,{method:"POST",headers:l,body:i,signal:e.signal});if(e.responseType==="response")return d;if(!d.ok&&!e.onStream){let p=await d.text();try{p=JSON.parse(p);}catch{}throw new f(p?.message||String(p),{code:p?.code||"ERROR"})}if(e.onStream&&d.body){let p=d.body.getReader(),g=new TextDecoder,_="";for(;;){let{done:w,value:b}=await p.read();if(w)break;let A=g.decode(b,{stream:true});_+=A;try{e.onStream(A);}catch(x){console.error(x);}}return _}let h=await d.text();if(e.responseType==="text")return h;try{return JSON.parse(h)}catch{return h}}async function As(r,e){await this.__connection,r=m.Params(r||{},{access_group:n=>{if(n==="authorized"&&(n=1),n==="public"&&(n=0),typeof n!="number")throw new f('"access_group" should be type number.',{code:"INVALID_PARAMETER"});if(n<0)throw new f('"access_group" should be zero or a positive number.',{code:"INVALID_PARAMETER"});if(n>this.__user.access_group)throw new f("User has no access.",{code:"INVALID_REQUEST"});return n}});let t=await T.bind(this)("get-feed",r,{auth:true,fetchOptions:e});for(let n in t.list)t.list[n]=await ze.bind(this)(t.list[n]);return t}function ct(r){if(r===this.__user.user_id)throw new f(`"user_id" cannot be the user's own ID.`,{code:"INVALID_PARAMETER"});return m.UserId(r,'"user_id"')}async function Ss(r,e){if(r=M(r,{ignoreEmpty:true}).data,r=m.Params(r,{subscriber:n=>m.UserId(n,'User ID in "subscriber"'),subscription:ct.bind(this),blocked:"boolean"}),!r.subscriber&&!r.subscription)throw new f('At least either "subscriber" or "subscription" should have a value.',{code:"INVALID_PARAMETER"});let t=await T.bind(this)("get-subscription",r,Object.assign({auth:true},{fetchOptions:e}));return t.list=t.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})),t}async function vs(r){await this.__connection,r=m.Params(r,{user_id:ct.bind(this),get_feed:["boolean",()=>false],get_notified:["boolean",()=>false],get_email:n=>{if(n&&!this.__user.email||!this.__user.email_verified)throw new f("User has no verified email address.",{code:"INVALID_REQUEST"});return !!n}},["user_id"]);let e=await T.bind(this)("subscription",{subscribe:r.user_id,option:{get_feed:r.get_feed,get_notified:r.get_notified,get_email:r.get_email||false}},{auth:true}),t={};if(e.sub){let n=e.sub.split("#");t.subscriber=n[2],t.subscription=n[0];}else t.subscriber=e.subscriber,t.subscription=e.subscription;return t.timestamp=e?.timestamp||e.stmp,t.blocked=e?.blocked||e.grp.substring(0,1)==="N",Object.assign(t,e.opt),t}async function Ts(r){await this.__connection;let{user_id:e}=m.Params(r,{user_id:ct.bind(this)},["user_id"]);return await T.bind(this)("subscription",{unsubscribe:e},{auth:true})}async function Rs(r){await this.__connection;let{user_id:e}=m.Params(r,{user_id:ct.bind(this)},["user_id"]);return await T.bind(this)("subscription",{block:e},{auth:true})}async function Is(r){await this.__connection;let{user_id:e}=m.Params(r,{user_id:ct.bind(this)},["user_id"]);return await T.bind(this)("subscription",{unblock:e},{auth:true})}async function Ps(r,e){await this.__connection;let t=await H.bind(this)();r=m.Params(r,{user_id:o=>{if(o!==this.__user.user_id&&!t)throw new f("No access.",{code:"INVALID_REQUEST"});return o},group:o=>{if(o==="public"&&(o=0),o==="authorized"&&(o=1),typeof o!="number")throw new f('"group" should be type number | "public" | "authorized".',{code:"INVALID_PARAMETER"});return o}});let n=await T.bind(this)("get-newsletter-subscription",r,{auth:true,fetchOptions:e||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=parseInt(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 xs(r){await this.__connection;let e=m.Params(r||{},{email:t=>Array.isArray(t)&&t.length>0?t.length===1?m.Email(t[0]):t.map(n=>m.Email(n)):m.Email(t),group:["number","public","authorized","admin",t=>{if(typeof t!="string"||t.length>20||!/^[a-zA-Z0-9]+$/.test(t))throw new f('"group" should be an alphanumeric string without spaces and less than 20 characters.',{code:"INVALID_PARAMETER"});return t}],redirect:t=>m.Url(t)},this.__user?["group"]:["email","group"]);return T.bind(this)(`subscribe-${this.__user?"":"public-"}newsletter`,e,{auth:!!this.__user})}async function Us(r){await this.__connection,r=m.Params(r,{group:["number","public","authorized","admin"]},["group"]);let e=Object.assign({action:"unsubscribe"},r);return T.bind(this)("subscribe-newsletter",e,{auth:true})}async function Cs(r,e){let t=await H.bind(this)(),n={message_id:"string",timestamp:"number",read:"number",complaint:"number",subject:"string",bounced:"number"};r||(e=Object.assign({ascending:false},e||{})),r=M(r).data,r=r||{searchFor:"timestamp",value:Date.now(),condition:"<",group:"public"},r=m.Params(r,{searchFor:["message_id","timestamp","subject","complaint","read","bounced"],value:u=>{if(typeof u!==n[r.searchFor])throw new f(`"value" type does not match the type of "${r.searchFor}" index.`,{code:"INVALID_PARAMETER"});if(typeof u=="string"&&!u)throw new f('"value" should not be empty string.',{code:"INVALID_PARAMETER"});return u},range:u=>{if(!r.hasOwnProperty("value")||typeof u!=typeof r.value)throw new f('"range" should match type of "value".',{code:"INVALID_PARAMETER"});return u},condition:[">",">=","=","<","<=","gt","gte","eq","lt","lte",()=>"="],group:u=>{if(u==="public")return 0;if(!this.session)throw new f("User should be logged in.",{code:"INVALID_REQUEST"});if(u==="authorized")return 1;if(typeof u=="number"){if(!t&&u>parseInt(this.user?.access_group||this.session?.idToken?.payload?.access_group))throw new f("User has no access.",{code:"INVALID_REQUEST"});return u}throw new f('"group" should be type: number | "public" | "authorized".',{code:"INVALID_PARAMETER"})}},["searchFor","value","group"]);let i=r.group===0?"get-public-newsletters":"get-newsletters",s=await T.bind(this)(i,r,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"},a={message_id:"",timestamp:0,complaint:0,read:0,subject:"",bounced:"",url:"",delivered:0};return s.list=s.list.map(u=>{let c={};for(let l in o)c[l]=u[o[l]]||a[l];return c.bounced=String(c.bounced),c}),s}async function Ds(r){let e=m.Params(r,{user_id:n=>m.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 H.bind(this)()){if(!this.__user)throw new f("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new f("Invalid access.",{code:"INVALID_REQUEST"})}return await T.bind(this)("block-account",e,{auth:true})}async function ks(r){let e=m.Params(r,{user_id:n=>m.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 H.bind(this)()){if(!this.__user)throw new f("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new f("Invalid access.",{code:"INVALID_REQUEST"})}return await T.bind(this)("block-account",e,{auth:true})}async function Ns(r){let e=m.Params(r,{user_id:n=>m.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 H.bind(this)()){if(!this.__user)throw new f("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new f("Invalid access.",{code:"INVALID_REQUEST"})}return await T.bind(this)("remove-account",e,{auth:true})}async function Fs(r,e){let t={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 f('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof s!="number"||s<1||s>100)throw new f('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"});return s}},n=m.Params(r,t,["email"]);if(e=m.Params(e,{confirmation_url:s=>{let o=s;if(typeof s=="string")o=m.Url(s);else throw new f('"options.confirmation_url" should be type: <string>.',{code:"INVALID_PARAMETER"});if(o&&!n.email)throw new f('"email" is required for signup confirmation.',{code:"INVALID_PARAMETER"});return o},email_subscription:s=>{if(typeof s!="boolean")throw new f('"options.email_subscription" should be type: <boolean>.',{code:"INVALID_PARAMETER"});if(!e?.confirmation_url)throw new f('"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 f('"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=e?.confirmation_url||true,n.email_subscription=e?.email_subscription||false,n.template=e?.template||{},!await H.bind(this)()){if(!this.__user)throw new f("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new f("Invalid access.",{code:"INVALID_REQUEST"})}return await T.bind(this)("admin-signup",n,{auth:true})}async function Ls(r){let e={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 f('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof s!="number"||s<1||s>100)throw new f('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"});return s}},t=["email","password"],n=m.Params(r,e,t);if(!await H.bind(this)()){if(!this.__user)throw new f("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new f("Invalid access.",{code:"INVALID_REQUEST"})}return await T.bind(this)("admin-signup",n,{auth:true})}async function Os(r){if(r=m.Params(r,{user_id:t=>m.UserId(t,'"user_id"'),access_group:t=>{try{typeof t=="string"&&(t=parseInt(t));}catch{throw new f('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof t=="number"&&t>0&&t<100)return t;throw new f('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"})}},["user_id","access_group"]),!await H.bind(this)()){if(!this.__user)throw new f("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new f("Invalid access.",{code:"INVALID_REQUEST"})}return await T.bind(this)("grant-access",r,{auth:true})}async function Ms(r,e){if(r=m.Params(r,{email:"string"}),!await H.bind(this)()){if(!this.__user)throw new f("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new f("Invalid access.",{code:"INVALID_REQUEST"})}let n=await T.bind(this)("invitation-list",Object.assign({mode:"search"},r),{fetchOptions:e,auth:true});return n.list=n.list.map(i=>et(i.user)),n}async function qs(r){if(r=m.Params(r,{email:t=>m.Email(t)},["email"]),!await H.bind(this)()){if(!this.__user)throw new f("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new f("Invalid access.",{code:"INVALID_REQUEST"})}return await T.bind(this)("invitation-list",Object.assign({mode:"cancel"},r),{auth:true})}async function Vs(r){if(r=m.Params(r,{email:t=>m.Email(t)},["email"]),!await H.bind(this)()){if(!this.__user)throw new f("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new f("Invalid access.",{code:"INVALID_REQUEST"})}return await T.bind(this)("invitation-list",Object.assign({mode:"resend"},r),{auth:true})}async function Bs(r){let e=m.Params(r,{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"]),t=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 f("At least one attribute to update is required.",{code:"INVALID_PARAMETER"});if(!await H.bind(this)()){if(!this.__user)throw new f("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new f("Invalid access.",{code:"INVALID_REQUEST"})}e.email&&(e.preferred_username=(t||this.service)+"-"+K.hash(e.email));let s={attributes:e};return t&&n&&(s.service=t,s.owner=n),await T.bind(this)("admin-edit-profile",s,{auth:true})}async function $s(r){if(typeof window>"u"||window._runningInNodeJS)throw new f("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.__connection,!r.endpoint)throw new f("Missing parameter: endpoint",{code:"INVALID_PARAMETER"});if(!r.keys||!r.keys.p256dh||!r.keys.auth)throw new f("Missing parameter: keys.p256dh or keys.auth",{code:"INVALID_PARAMETER"});return await T.bind(this)("store-subscription",{endpoint:r.endpoint,keys:r.keys},{auth:true}),"SUCCESS: Subscribed to receive notifications."}async function js(r){if(typeof window>"u"||window._runningInNodeJS)throw new f("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.__connection,!r.endpoint)throw new f("Missing parameter: endpoint",{code:"INVALID_PARAMETER"});if(!r.keys||!r.keys.p256dh||!r.keys.auth)throw new f("Missing parameter: keys.p256dh or keys.auth",{code:"INVALID_PARAMETER"});return await T.bind(this)("delete-subscription",{endpoint:r.endpoint,keys:r.keys},{auth:true}),"SUCCESS: Unsubscribed from notifications."}async function Ks(){if(typeof window>"u"||window._runningInNodeJS)throw new f("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 Hs(r,e){if(typeof window>"u"||window._runningInNodeJS)throw new f("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});await this.__connection;let{title:t,body:n}=M(r||{},{nullIfEmpty:true}).data;if(!t)throw new f("Missing parameter: message title",{code:"INVALID_PARAMETER"});if(!n)throw new f("Missing parameter: message body",{code:"INVALID_PARAMETER"});let i={title:t,body:n};return e?(typeof e=="string"&&(e=[e]),i.user_ids=e):i.user_ids="all_users",await T.bind(this)("push-notification",i,{auth:true}),"SUCCESS: Notification sent."}async function Ws(r){await this.__connection,r=m.Params(r,{spell:"string",name:"string",magic:t=>t},["spell","name"]);await T.bind(this)("castspell",r);return `The spell "${r.spell}" has been cast.`}async function Js(r){return await this.__connection,r=m.Params(r||{},{search:["spell","name",()=>"spell"],value:"string"}),await T.bind(this)("getspell",r)}async function Gs(r){await this.__connection,r=m.Params(r,{message:"string",name:"string"},["message","name"]);let e=await T.bind(this)("dopamine",r,{auth:true}),t=e?.previous_message?.message,n=e?.previous_message?.name;if(Y())t&&n&&window.alert(`${n} said: ${t}`),window.location.href=e.video;else return t&&n?`${n} said: ${t}
216
+ `,o=new Blob([s],{type:"application/javascript"});Te=new Worker(URL.createObjectURL(o)),Te.onmessage=a=>{i.readyState===1&&i.send(JSON.stringify({action:"keepAlive"}));},n(i);},i.onmessage=async s=>{let o="";try{o=JSON.parse(decodeURI(s.data)),this.log("socket onmessage",o);}catch{return}let a;switch(true){case !!o?.["#message"]:a="message";break;case !!o?.["#private"]:a="private";break;case !!o?.["#notice"]:a="notice";break;case !!o?.["#rtc"]:a="rtc";break;case !!o?.["#error"]:a="error";break}if(!a)return;let u={type:a,message:o?.["#rtc"]||o?.["#message"]||o?.["#private"]||o?.["#notice"]||o?.["#error"]||null,sender:o?.["#user_id"]||null,sender_cid:o?.["#scid"]?"cid:"+o["#scid"]:null,sender_rid:o?.["#srid"]||null,code:o?.["#code"]||null};if(a==="notice")r(u);else if(a==="rtc"){if(u.sender!==this.user.user_id){let c=u.message;if(c.hungup){oe[u.sender_cid]&&(oe[u.sender_cid](false),delete oe[u.sender_cid]),ge[u.sender_cid]&&delete ge[u.sender_cid],U?.[u.sender_cid]&&ae.bind(this)({cid:u.sender_cid}),u.type="rtc:closed",r(u);return}if(c.candidate&&$r.bind(this)(c.candidate,u.sender_cid),c.sdpoffer&&(Br.bind(this)(c.sdpoffer,u.sender_cid),ge[u.sender_cid]||(ge[u.sender_cid]=u.sender_cid,delete u.message,u.connectRTC=ts.bind(this)(u),u.type="rtc:incoming",u.hangup=(()=>{U[u.sender_cid]?ae.bind(this)({cid:u.sender_cid}):ge[u.sender_cid]&&(delete ge[u.sender_cid],i.send(JSON.stringify({action:"rtc",uid:u.sender_cid,content:{hungup:this.user.user_id},token:this.session.accessToken.jwtToken})));}).bind(this),r(u))),c.pickup&&oe[u.sender_cid]&&(oe[u.sender_cid](true),delete oe[u.sender_cid]),c.sdpanswer&&U[u.sender_cid])if(U[u.sender_cid].signalingState==="have-local-offer")await U[u.sender_cid].setRemoteDescription(new RTCSessionDescription(c.sdpanswer));else throw new f("Invalid signaling state.",{code:"INVALID_REQUEST"})}}else r(u);},i.onclose=()=>{at?(this.log("realtime onclose","WebSocket connection closed."),r({type:"close",message:"WebSocket connection closed."})):(this.log("realtime onclose","WebSocket unexpected close."),r({type:"error",message:"Skapi: WebSocket unexpected close."}),Ye++,Ye<3?(this.log("realtime onclose","Reconnecting to WebSocket server..."+Ye),r({type:"reconnect",message:"Reconnecting to WebSocket server..."+Ye}),Jt.bind(this)(r,3e3,"reconnect")):(this.log("realtime onclose","Max reconnection attempts reached."),r({type:"error",message:"Skapi: Max reconnection attempts reached."})));},i.onerror=()=>{this.log("realtime onerror","WebSocket connection error."),r({type:"error",message:"Skapi: WebSocket connection error."});};},e);});}async function ss(r,e,t){if(typeof window>"u"||window._runningInNodeJS)throw new f("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});let n=this.__socket?await this.__socket:this.__socket;if(!n)throw new f("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});if(!e)throw new f("No recipient.",{code:"INVALID_REQUEST"});await Je.bind(this)(),r=M(r).data;let i="";if(t&&(t=m.Params(t,{config:{always:"boolean"},title:"string",body:"string"},["title","body"]),i=JSON.stringify({title:t.title,body:t.body}),new Blob([i]).size>3072))throw new f("Notification size exceeds 3kb.",{code:"INVALID_PARAMETER"});if(n.readyState===1){try{m.UserId(e),n.send(JSON.stringify({action:"sendMessage",uid:e,content:r,notification:i,notificationConfig:t?.config||{},token:`IdT:${this.service}:${this.owner}:`+(this.bearerToken||this.session?.idToken?.jwtToken||"null")}));}catch(s){if(this.log("postRealtime:err",{err:s}),Re!==e)throw new f(`User has not joined to the recipient group. Run joinRealtime({ group: "${e}" })`,{code:"INVALID_REQUEST"});n.send(JSON.stringify({action:"broadcast",rid:e,content:r,notification:i,notificationConfig:t?.config||{},token:`IdT:${this.service}:${this.owner}:`+(this.bearerToken||this.session?.idToken?.jwtToken||"null")}));}return {type:"success",message:"Message sent."}}throw new f("Realtime connection is not open. Try reconnecting with connectRealtime().",{code:"INVALID_REQUEST"})}async function Kr(r){if(typeof window>"u"||window._runningInNodeJS)throw new f("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});let e=this.__socket?await this.__socket:this.__socket;if(!e)throw new f("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});await Je.bind(this)(),r=M(r,{nullIfEmpty:true}).data;let{group:t=null}=r;if(!t&&!Re)return {type:"success",message:"Left realtime message group."};if(t!==null&&typeof t!="string")throw new f('"group" must be a string | null.',{code:"INVALID_PARAMETER"});return e.send(JSON.stringify({action:"joinRoom",rid:t,token:this.session.accessToken.jwtToken})),Re=t,{type:"success",message:t?`Joined realtime message group: "${t}".`:"Left realtime message group."}}async function os(r,e){r=m.Params(r,{user_id:n=>m.UserId(n,'User ID in "user_id"'),group:["string",()=>{if(!Re)throw new f('No group has been joined. Otherwise "group" is required.',{code:"INVALID_REQUEST"});return Re}]});let t=await T.bind(this)("get-ws-group",r,{fetchOptions:e,auth:true,method:"post"});return t.list=t.list.map(n=>({user_id:n.uid.split("#")[1],cid:"cid:"+n.cid})),t}async function as(r,e){if(await this.__connection,r||(r={searchFor:"group",value:" ",condition:">"}),r=m.Params(r,{searchFor:["group","number_of_users",()=>"group"],value:["string","number",()=>r?.searchFor&&r?.searchFor==="number_of_users"?0:" "],condition:[">",">=","=","<","<=","!=","gt","gte","eq","lt","lte","ne"],range:["string","number"]}),r.condition||(r.value===" "||!r.value?r.condition=">":r.condition="="),r.range&&r.condition&&delete r.condition,r.searchFor==="number_of_users"&&typeof r.value!="number")throw new f('"value" must be a number.',{code:"INVALID_PARAMETER"});if(r.searchFor==="group"&&typeof r.value!="string")throw new f('"value" must be a string.',{code:"INVALID_PARAMETER"});if(r.hasOwnProperty("range")&&typeof r.range!=typeof r.value)throw new f(`"range" must be a ${typeof r.value}.`,{code:"INVALID_PARAMETER"});let t=await T.bind(this)("get-ws-group",r,{fetchOptions:e,auth:true,method:"post"});return t.list=t.list.map(n=>({group:n.rid.split("#")[1],number_of_users:n.cnt})),t}var us=typeof FormData<"u",cs=typeof HTMLFormElement<"u",ls=typeof SubmitEvent<"u",pe={},ut={},me={};function Hr(r){return Object.freeze({id:r,status:"stopped"})}function ds(r){return !!r&&typeof r=="object"&&r.status==="stopped"}function fs({id:r,auth:e,service:t,owner:n,latency:i=1e3,queue:s,onResponse:o,onError:a}){if(typeof i!="number")throw new f('"latency" should be a number.',{code:"INVALID_PARAMETER"});if(i<0)throw new f('"latency" should be a non-negative number.',{code:"INVALID_PARAMETER"});s&&!pe?.[s]&&(pe[s]=new nt({breakWhenError:false,batchSize:1}));let u={stop:null,aborted:false,queue:s};me[r]=u;let c=()=>{me[r]===u&&delete me[r];},l=()=>new Promise((h,p)=>{let g=false;if(u.aborted){c(),h(Hr(r));return}let _=setInterval(async()=>{try{let w=await T.bind(this)("csr-poll",{id:r,service:t,owner:n},{auth:e});if(w.status==="running"||w.status==="pending"||g)return;g=!0,o&&o(w),clearInterval(_),c(),h(w);}catch(w){if(g)return;g=true,a&&a(w),clearInterval(_),c(),p(w);}},i);u.stop=()=>{g||(g=true,clearInterval(_),c(),h(Hr(r)));};}),d=()=>{let h=me[r];h&&(h.stop?h.stop():(h.aborted=true,delete me[r]));};if(s){let h=new Promise((p,g)=>{let _=false,w=pe[s].add([async()=>{try{let b=await l();return _||(_=!0,p(b)),b}catch(b){throw _||(_=true,g(b)),b}}])[0];ut[r]=w,u.stop=()=>{if(!_){u.aborted=true;try{pe[s]&&pe[s].remove(ut[r]);}catch{}delete ut[r],c(),_=true,p(Hr(r));}};});return Object.assign(h,{stop:d})}else return Object.assign(l(),{stop:d})}function hs(r){let e=0,t=[];if(r?.id){if(r.url&&r.method){let n=r.service||this.service;t.push(`[${r.method.toUpperCase()}]${r.url.toLowerCase()}#${n}:${r.id}`);}t.push(r.id);}else if(r?.queue)for(let n in me)me[n]?.queue===r.queue&&t.push(n);else for(let n in me)t.push(n);for(let n of t){let i=me[n];i&&(i.stop?i.stop():(i.aborted=true,delete me[n]),e+=1);}return e}function gs(r,e){if(!r.queue)throw new f('"queue" is required.',{code:"INVALID_PARAMETER"});let t={service:r.service||this.service,owner:r.owner||this.owner,queue:r.queue+":"};return T.bind(this)("csr-poll",t,{auth:true})}async function ps(r){let e=false;if(typeof r.poll=="number"&&r.poll<0)throw new f('"poll" should be a non-negative number.',{code:"INVALID_PARAMETER"});let t=r?.onResponse,n=r?.onError,i=typeof r.poll=="number"?r.poll:r.poll?1e3:0;delete r.poll,i&&!r.queue&&(r.queue=(this.__user?.user_id||"anonymous")+"-"+De());let s=u=>{for(let c in u)if(typeof u[c]=="string"&&u[c].includes("$CLIENT_SECRET")){e=true;break}};if(r=m.Params(r,{url:u=>{if(!u||typeof u!="string")throw new f('"url" should be type: <string>.',{code:"INVALID_PARAMETER"});return m.Url(u),u.includes("$CLIENT_SECRET")&&(e=true),u},clientSecretName:"string",method:u=>{if(u&&typeof u!="string")throw new f('"method" should be either "GET" or "POST" or "DELETE" or "PUT".',{code:"INVALID_PARAMETER"});let c=u.toLowerCase();if(c!=="get"&&c!=="post"&&c!=="delete"&&c!=="put")throw new f('"method" should be either "GET" or "POST" or "DELETE" or "PUT".',{code:"INVALID_PARAMETER"});return c},headers:u=>{if(u&&typeof u!="object")throw new f('"headers" should be type: <object>.',{code:"INVALID_PARAMETER"});return s(u),u},data:u=>{if(u&&typeof u!="object")throw new f('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return s(u),u},params:u=>{if(u&&typeof u!="object")throw new f('"params" should be type: <object>.',{code:"INVALID_PARAMETER"});return s(u),u},expires:"number",queue:"string"},["clientSecretName","method","url"]),!e)throw new f(`At least one parameter value should include "$CLIENT_SECRET" in ${r.method.toLowerCase()==="post"?'"data"':'"params"'} or "headers".`,{code:"INVALID_PARAMETER"});await this.__connection;let o=!!this.__user,a=()=>T.bind(this)("csr",r,{auth:o,tokenHeaders:{accessToken:!!o}}).then(u=>{if(u.status==="running"||u.status==="pending"){let c=`[${r.method.toUpperCase()}]${r.url.toLowerCase()}`,l=r.service||this.service,d=r.owner||this.owner,h=`${c}#${l}:${u.id}`;Object.assign(u,{poll:p=>fs.call(this,{id:h,auth:o,service:l,owner:d,latency:p?.latency||1e3,queue:r?.queue,onResponse:t,onError:n})});}return t?t(u):u}).catch(u=>{if(n)return n(u);throw u});if(r?.queue){let u="base:"+r.queue;return pe?.[u]||(pe[u]=new nt({breakWhenError:false,batchSize:1})),new Promise((c,l)=>{pe[u].add([async()=>{try{let d=await a();if(i>0){let h=d.poll({latency:i});return c(h),h}return c(d),d}catch(d){throw l(d),d}}]);})}else return a()}async function ms(r,e){await this.__connection;let t=r.service||this.service,n=r.owner||this.owner;r=m.Params(r,{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=`[${r.method.toUpperCase()}]${r.url.toLowerCase()}#${t}:`,o={id:s,queue:r?.queue,status:r?.status,service:t,owner:n};r?.compact&&(o.compact=true),r?.queue_exact&&(o.queue_exact=true),r?.queue_exclude&&(o.queue_exclude=r.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:e});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 l in c)c[l]===void 0&&delete c[l];return (c.status==="running"||c.status==="pending")&&(c.poll=l=>fs.call(this,{id:s+c.id,auth:i,service:t,owner:n,latency:l?.latency||1e3,queue:u?.qid,onResponse:l?.onResponse,onError:l?.onError})),c}),a}async function _s(r){await this.__connection,r=m.Params(r,{url:"string",method:["GET","POST","DELETE","PUT"],id:"string",queue:"string"},["url","method","id"]);let e=r?.service||this.service,t=r?.owner||this.owner,n=!!this.__user,i=`[${r.method.toUpperCase()}]${r.url.toLowerCase()}#${e}`,s=r.id,o=`${i}:${s}`,a=r?.queue;return a&&pe?.[a]&&(pe[a].remove(ut[o]),delete ut[o]),T.bind(this)("csr-cancel",{id:o,service:e,owner:t},{auth:n})}async function bs(r){await this.__connection;let e={name:"string",email:t=>(m.Email(t),t),subject:"string",message:"string"};return r=m.Params(r,e,["name","email","subject","message"]),await T.bind(this)("send-inquiry",r),"SUCCESS: Inquiry has been sent."}async function ys(r,e){if(await this.__connection,us&&r instanceof FormData||cs&&r instanceof HTMLFormElement||ls&&r instanceof SubmitEvent){if(!e)throw new f("Url string as a second argument is required when form is passed.",{code:"INVALID_PARAMETER"});let n=M(r);r={url:e,data:n.data,sync:true};}let t={url:n=>m.Url(n),data:n=>n,sync:["boolean",()=>true]};if(Array.isArray(r))for(let n of r)n=m.Params(n,t);else r=m.Params(r,t);return T.bind(this)("post-secure",r,{auth:true})}async function ws(r,e){await this.__connection;let{auth:t=false,method:n="POST",bypassAwaitConnection:i=false,responseType:s,contentType:o,tokenHeaders:a,progress:u}=e||{};if(e=Object.assign({auth:t,method:n,bypassAwaitConnection:i,responseType:s,contentType:o,tokenHeaders:a},{fetchOptions:{progress:u}}),typeof r!="object"&&(o==="application/json"||o===void 0))throw new f('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return T.bind(this)("mock",r,e)}async function Es(r,e){if(await this.__connection,!e?.url||typeof e.url!="string")throw new f('"url" is required in the second argument.',{code:"INVALID_PARAMETER"});m.Url(e.url);let n=(await this.admin_endpoint)?.forward_request;if(!n)throw new f("forwardRequest is not available on this service region yet.",{code:"NOT_EXISTS"});let i=null,s=null,o=ls&&r instanceof SubmitEvent?r.target:cs&&r instanceof HTMLFormElement?r:null;o?i=new FormData(o):us&&r instanceof FormData?i=r:r!=null&&(i=JSON.stringify(r),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}},u=JSON.stringify(a);if(u.length>4096)throw new f("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 f("User login is required.",{code:"INVALID_REQUEST"});let l={"Content-Meta":u,Authorization:c};s&&(l["Content-Type"]=s);let d=await fetch(n,{method:"POST",headers:l,body:i,signal:e.signal});if(e.responseType==="response")return d;if(!d.ok){let p=await d.text();try{p=JSON.parse(p);}catch{}throw new f(p?.message||(typeof p=="string"?p:JSON.stringify(p)),{code:p?.code||"ERROR"})}if(e.onStream&&d.body){let p=d.body.getReader(),g=new TextDecoder,_="";for(;;){let{done:w,value:b}=await p.read();if(w)break;let A=g.decode(b,{stream:true});_+=A;try{e.onStream(A);}catch(x){console.error(x);}}return _}let h=await d.text();if(e.responseType==="text")return h;try{return JSON.parse(h)}catch{return h}}async function As(r,e){await this.__connection,r=m.Params(r||{},{access_group:n=>{if(n==="authorized"&&(n=1),n==="public"&&(n=0),typeof n!="number")throw new f('"access_group" should be type number.',{code:"INVALID_PARAMETER"});if(n<0)throw new f('"access_group" should be zero or a positive number.',{code:"INVALID_PARAMETER"});if(n>this.__user.access_group)throw new f("User has no access.",{code:"INVALID_REQUEST"});return n}});let t=await T.bind(this)("get-feed",r,{auth:true,fetchOptions:e});for(let n in t.list)t.list[n]=await ze.bind(this)(t.list[n]);return t}function ct(r){if(r===this.__user.user_id)throw new f(`"user_id" cannot be the user's own ID.`,{code:"INVALID_PARAMETER"});return m.UserId(r,'"user_id"')}async function Ss(r,e){if(r=M(r,{ignoreEmpty:true}).data,r=m.Params(r,{subscriber:n=>m.UserId(n,'User ID in "subscriber"'),subscription:ct.bind(this),blocked:"boolean"}),!r.subscriber&&!r.subscription)throw new f('At least either "subscriber" or "subscription" should have a value.',{code:"INVALID_PARAMETER"});let t=await T.bind(this)("get-subscription",r,Object.assign({auth:true},{fetchOptions:e}));return t.list=t.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})),t}async function vs(r){await this.__connection,r=m.Params(r,{user_id:ct.bind(this),get_feed:["boolean",()=>false],get_notified:["boolean",()=>false],get_email:n=>{if(n&&!this.__user.email||!this.__user.email_verified)throw new f("User has no verified email address.",{code:"INVALID_REQUEST"});return !!n}},["user_id"]);let e=await T.bind(this)("subscription",{subscribe:r.user_id,option:{get_feed:r.get_feed,get_notified:r.get_notified,get_email:r.get_email||false}},{auth:true}),t={};if(e.sub){let n=e.sub.split("#");t.subscriber=n[2],t.subscription=n[0];}else t.subscriber=e.subscriber,t.subscription=e.subscription;return t.timestamp=e?.timestamp||e.stmp,t.blocked=e?.blocked||e.grp.substring(0,1)==="N",Object.assign(t,e.opt),t}async function Ts(r){await this.__connection;let{user_id:e}=m.Params(r,{user_id:ct.bind(this)},["user_id"]);return await T.bind(this)("subscription",{unsubscribe:e},{auth:true})}async function Rs(r){await this.__connection;let{user_id:e}=m.Params(r,{user_id:ct.bind(this)},["user_id"]);return await T.bind(this)("subscription",{block:e},{auth:true})}async function Is(r){await this.__connection;let{user_id:e}=m.Params(r,{user_id:ct.bind(this)},["user_id"]);return await T.bind(this)("subscription",{unblock:e},{auth:true})}async function Ps(r,e){await this.__connection;let t=await H.bind(this)();r=m.Params(r,{user_id:o=>{if(o!==this.__user.user_id&&!t)throw new f("No access.",{code:"INVALID_REQUEST"});return o},group:o=>{if(o==="public"&&(o=0),o==="authorized"&&(o=1),typeof o!="number")throw new f('"group" should be type number | "public" | "authorized".',{code:"INVALID_PARAMETER"});return o}});let n=await T.bind(this)("get-newsletter-subscription",r,{auth:true,fetchOptions:e||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=parseInt(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 xs(r){await this.__connection;let e=m.Params(r||{},{email:t=>Array.isArray(t)&&t.length>0?t.length===1?m.Email(t[0]):t.map(n=>m.Email(n)):m.Email(t),group:["number","public","authorized","admin",t=>{if(typeof t!="string"||t.length>20||!/^[a-zA-Z0-9]+$/.test(t))throw new f('"group" should be an alphanumeric string without spaces and less than 20 characters.',{code:"INVALID_PARAMETER"});return t}],redirect:t=>m.Url(t)},this.__user?["group"]:["email","group"]);return T.bind(this)(`subscribe-${this.__user?"":"public-"}newsletter`,e,{auth:!!this.__user})}async function Us(r){await this.__connection,r=m.Params(r,{group:["number","public","authorized","admin"]},["group"]);let e=Object.assign({action:"unsubscribe"},r);return T.bind(this)("subscribe-newsletter",e,{auth:true})}async function Cs(r,e){let t=await H.bind(this)(),n={message_id:"string",timestamp:"number",read:"number",complaint:"number",subject:"string",bounced:"number"};r||(e=Object.assign({ascending:false},e||{})),r=M(r).data,r=r||{searchFor:"timestamp",value:Date.now(),condition:"<",group:"public"},r=m.Params(r,{searchFor:["message_id","timestamp","subject","complaint","read","bounced"],value:u=>{if(typeof u!==n[r.searchFor])throw new f(`"value" type does not match the type of "${r.searchFor}" index.`,{code:"INVALID_PARAMETER"});if(typeof u=="string"&&!u)throw new f('"value" should not be empty string.',{code:"INVALID_PARAMETER"});return u},range:u=>{if(!r.hasOwnProperty("value")||typeof u!=typeof r.value)throw new f('"range" should match type of "value".',{code:"INVALID_PARAMETER"});return u},condition:[">",">=","=","<","<=","gt","gte","eq","lt","lte",()=>"="],group:u=>{if(u==="public")return 0;if(!this.session)throw new f("User should be logged in.",{code:"INVALID_REQUEST"});if(u==="authorized")return 1;if(typeof u=="number"){if(!t&&u>parseInt(this.user?.access_group||this.session?.idToken?.payload?.access_group))throw new f("User has no access.",{code:"INVALID_REQUEST"});return u}throw new f('"group" should be type: number | "public" | "authorized".',{code:"INVALID_PARAMETER"})}},["searchFor","value","group"]);let i=r.group===0?"get-public-newsletters":"get-newsletters",s=await T.bind(this)(i,r,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"},a={message_id:"",timestamp:0,complaint:0,read:0,subject:"",bounced:"",url:"",delivered:0};return s.list=s.list.map(u=>{let c={};for(let l in o)c[l]=u[o[l]]||a[l];return c.bounced=String(c.bounced),c}),s}async function Ds(r){let e=m.Params(r,{user_id:n=>m.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 H.bind(this)()){if(!this.__user)throw new f("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new f("Invalid access.",{code:"INVALID_REQUEST"})}return await T.bind(this)("block-account",e,{auth:true})}async function ks(r){let e=m.Params(r,{user_id:n=>m.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 H.bind(this)()){if(!this.__user)throw new f("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new f("Invalid access.",{code:"INVALID_REQUEST"})}return await T.bind(this)("block-account",e,{auth:true})}async function Ns(r){let e=m.Params(r,{user_id:n=>m.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 H.bind(this)()){if(!this.__user)throw new f("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new f("Invalid access.",{code:"INVALID_REQUEST"})}return await T.bind(this)("remove-account",e,{auth:true})}async function Fs(r,e){let t={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 f('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof s!="number"||s<1||s>100)throw new f('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"});return s}},n=m.Params(r,t,["email"]);if(e=m.Params(e,{confirmation_url:s=>{let o=s;if(typeof s=="string")o=m.Url(s);else throw new f('"options.confirmation_url" should be type: <string>.',{code:"INVALID_PARAMETER"});if(o&&!n.email)throw new f('"email" is required for signup confirmation.',{code:"INVALID_PARAMETER"});return o},email_subscription:s=>{if(typeof s!="boolean")throw new f('"options.email_subscription" should be type: <boolean>.',{code:"INVALID_PARAMETER"});if(!e?.confirmation_url)throw new f('"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 f('"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=e?.confirmation_url||true,n.email_subscription=e?.email_subscription||false,n.template=e?.template||{},!await H.bind(this)()){if(!this.__user)throw new f("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new f("Invalid access.",{code:"INVALID_REQUEST"})}return await T.bind(this)("admin-signup",n,{auth:true})}async function Ls(r){let e={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 f('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof s!="number"||s<1||s>100)throw new f('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"});return s}},t=["email","password"],n=m.Params(r,e,t);if(!await H.bind(this)()){if(!this.__user)throw new f("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new f("Invalid access.",{code:"INVALID_REQUEST"})}return await T.bind(this)("admin-signup",n,{auth:true})}async function Os(r){if(r=m.Params(r,{user_id:t=>m.UserId(t,'"user_id"'),access_group:t=>{try{typeof t=="string"&&(t=parseInt(t));}catch{throw new f('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof t=="number"&&t>0&&t<100)return t;throw new f('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"})}},["user_id","access_group"]),!await H.bind(this)()){if(!this.__user)throw new f("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new f("Invalid access.",{code:"INVALID_REQUEST"})}return await T.bind(this)("grant-access",r,{auth:true})}async function Ms(r,e){if(r=m.Params(r,{email:"string"}),!await H.bind(this)()){if(!this.__user)throw new f("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new f("Invalid access.",{code:"INVALID_REQUEST"})}let n=await T.bind(this)("invitation-list",Object.assign({mode:"search"},r),{fetchOptions:e,auth:true});return n.list=n.list.map(i=>et(i.user)),n}async function qs(r){if(r=m.Params(r,{email:t=>m.Email(t)},["email"]),!await H.bind(this)()){if(!this.__user)throw new f("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new f("Invalid access.",{code:"INVALID_REQUEST"})}return await T.bind(this)("invitation-list",Object.assign({mode:"cancel"},r),{auth:true})}async function Vs(r){if(r=m.Params(r,{email:t=>m.Email(t)},["email"]),!await H.bind(this)()){if(!this.__user)throw new f("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new f("Invalid access.",{code:"INVALID_REQUEST"})}return await T.bind(this)("invitation-list",Object.assign({mode:"resend"},r),{auth:true})}async function Bs(r){let e=m.Params(r,{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"]),t=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 f("At least one attribute to update is required.",{code:"INVALID_PARAMETER"});if(!await H.bind(this)()){if(!this.__user)throw new f("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new f("Invalid access.",{code:"INVALID_REQUEST"})}e.email&&(e.preferred_username=(t||this.service)+"-"+K.hash(e.email));let s={attributes:e};return t&&n&&(s.service=t,s.owner=n),await T.bind(this)("admin-edit-profile",s,{auth:true})}async function $s(r){if(typeof window>"u"||window._runningInNodeJS)throw new f("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.__connection,!r.endpoint)throw new f("Missing parameter: endpoint",{code:"INVALID_PARAMETER"});if(!r.keys||!r.keys.p256dh||!r.keys.auth)throw new f("Missing parameter: keys.p256dh or keys.auth",{code:"INVALID_PARAMETER"});return await T.bind(this)("store-subscription",{endpoint:r.endpoint,keys:r.keys},{auth:true}),"SUCCESS: Subscribed to receive notifications."}async function js(r){if(typeof window>"u"||window._runningInNodeJS)throw new f("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.__connection,!r.endpoint)throw new f("Missing parameter: endpoint",{code:"INVALID_PARAMETER"});if(!r.keys||!r.keys.p256dh||!r.keys.auth)throw new f("Missing parameter: keys.p256dh or keys.auth",{code:"INVALID_PARAMETER"});return await T.bind(this)("delete-subscription",{endpoint:r.endpoint,keys:r.keys},{auth:true}),"SUCCESS: Unsubscribed from notifications."}async function Ks(){if(typeof window>"u"||window._runningInNodeJS)throw new f("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 Hs(r,e){if(typeof window>"u"||window._runningInNodeJS)throw new f("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});await this.__connection;let{title:t,body:n}=M(r||{},{nullIfEmpty:true}).data;if(!t)throw new f("Missing parameter: message title",{code:"INVALID_PARAMETER"});if(!n)throw new f("Missing parameter: message body",{code:"INVALID_PARAMETER"});let i={title:t,body:n};return e?(typeof e=="string"&&(e=[e]),i.user_ids=e):i.user_ids="all_users",await T.bind(this)("push-notification",i,{auth:true}),"SUCCESS: Notification sent."}async function Ws(r){await this.__connection,r=m.Params(r,{spell:"string",name:"string",magic:t=>t},["spell","name"]);await T.bind(this)("castspell",r);return `The spell "${r.spell}" has been cast.`}async function Js(r){return await this.__connection,r=m.Params(r||{},{search:["spell","name",()=>"spell"],value:"string"}),await T.bind(this)("getspell",r)}async function Gs(r){await this.__connection,r=m.Params(r,{message:"string",name:"string"},["message","name"]);let e=await T.bind(this)("dopamine",r,{auth:true}),t=e?.previous_message?.message,n=e?.previous_message?.name;if(Y())t&&n&&window.alert(`${n} said: ${t}`),window.location.href=e.video;else return t&&n?`${n} said: ${t}
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 S=class{constructor(e,t,n,i){this.__version="2.0.0-rc.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 m.UserId(e),!0}catch{return false}},url(e){try{return m.Url(e),!0}catch{return false}},phoneNumber(e){try{return m.PhoneNumber(e),!0}catch{return false}},birthdate(e){try{return m.Birthdate(e),!0}catch{return false}},email(e){try{return m.Email(e),!0}catch{return false}},params(e,t,n){return m.Params(e,t,n)}};this.util={MD5:K,generateRandom:De,toBase62:ei,fromBase62:ie,decodeProjectId:Ur,formatServiceId:Cr,extractFormData:M,terminatePendingRequests:Ii,request:(e,t,n)=>T.bind(this)(e,t,n,{ignoreService:true})};this.__network_logs=false;this.__endpoint_version="v2";this.__public_identifier="";this.bearerToken="";this.registerTicket=si.bind(this);this.unregisterTicket=oi.bind(this);if(!e||typeof e!="string")throw this._alert("Service ID is required."),new f("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 f("Project ID is required.",{code:"INVALID_PARAMETER"});let o=e.split("-").length;if(o===2||o===7)try{let b=Ur(e);n&&typeof n=="object"&&(i=n),t&&typeof t=="object"&&(n=t),t=b.owner,e=b.service;}catch{throw this._alert("Service ID is invalid."),new f("Service ID is invalid.",{code:"INVALID_PARAMETER"})}if(!t||typeof t!="string")throw this._alert("Owner ID is invalid."),new f("Owner ID is invalid.",{code:"INVALID_PARAMETER"});if(t!==this.host)try{m.UserId(t,'"owner"');}catch{throw this._alert("Owner ID is invalid."),new f("Owner ID is invalid.",{code:"INVALID_PARAMETER"})}this.service=e,this.owner=t;try{this.project_id=Cr(e,t);}catch{this.project_id="";}let c=true,l=false;if(n&&(typeof n.refetchServiceInfo=="boolean"&&(l=n.refetchServiceInfo),typeof n.autoLogin=="boolean"&&(c=n.autoLogin),typeof n.requestBatchSize=="number")){if(n.requestBatchSize<1)throw new f('"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`,h=e.substring(0,4);this.admin_endpoint=fetch(`${d}/${h}/admin-${this.__endpoint_version}.json`).then(b=>b.blob()).then(b=>new Promise((A,x)=>{let I=new FileReader;I.onloadend=()=>A(I.result),I.onerror=x,I.readAsDataURL(b);})).then(b=>{try{return typeof b=="string"?JSON.parse(atob(b.split(",")[1])):null}catch{throw new f("Service does not exist. Create your service from skapi.com",{code:"NOT_EXISTS"})}}),this.record_endpoint=fetch(`${d}/${h}/record-${this.__endpoint_version}.json`).then(b=>b.blob()).then(b=>new Promise((A,x)=>{let I=new FileReader;I.onloadend=()=>A(I.result),I.onerror=x,I.readAsDataURL(b);})).then(b=>{try{return typeof b=="string"?JSON.parse(atob(b.split(",")[1])):null}catch{throw new f("Service does not exist. Create your service from skapi.com",{code:"NOT_EXISTS"})}});let p=Y();if(p&&!window.sessionStorage)throw this._alert("This browser is not supported."),new Error("This browser is not supported.");let g=p?JSON.parse(window.sessionStorage.getItem(`${e}#${t}`)||"null"):null;if(this.log("constructor:restore",g),g?.connection){for(let b in g)this[b]=g[b];g.__public_identifier||(this.__public_identifier=`${this.service}:${this.owner}:${De(16)}`);}this.__authConnection=(async()=>{let b=await this.admin_endpoint,A={UserPoolId:b.userpool_id,ClientId:b.userpool_client};xr()&&(A.Storage=window.localStorage),this.userPool=new Rr(A);try{this.user||await G.bind(this)().getSession({skipUserUpdateEventTrigger:!0}),this.user&&(!g?.connection&&!c?Ae.bind(this)():(this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user)));}catch{}})();let _=`${this.service}/${this.owner}`,w=p?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,g?.connection||(b=this._updateConnection({refresh:l}));let A=()=>{if(this.__class_properties_has_been_cached)return;let x=()=>{let I={},D=["__startKeyHistory","__disabledAccount","__cached_requests","__request_signup_confirmation","__public_identifier","connection"];if(this.connection){for(let F of D)I[F]=this[F];if(p){let F=`${e}#${t}`;try{window.sessionStorage.setItem(F,JSON.stringify(I));}catch{try{let L=Object.assign({},I,{__cached_requests:{},__startKeyHistory:{}});window.sessionStorage.setItem(F,JSON.stringify(L));}catch{try{window.sessionStorage.removeItem(F);}catch{}}}}this.__class_properties_has_been_cached=true;}};return b instanceof Promise?b.then(()=>x()):x()};return p&&(window.addEventListener("beforeunload",()=>{this.closeRealtime(),A();}),window.addEventListener("visibilitychange",()=>{A();})),await b,await this.__authConnection,this.connection})(),this.__connection.then(b=>{((b?.group||0)<3||this.__network_logs)&&this.version();});}get user(){return this.__user&&Object.keys(this.__user).length?JSON.parse(JSON.stringify(this.__user)):null}set user(e){}get onLogin(){return this._onLoginListeners}set onLogin(e){typeof e=="function"&&this._onLoginListeners.push(e);}get onUserUpdate(){return this._userProfileListeners}set onUserUpdate(e){typeof e=="function"&&this._userProfileListeners.push(e);}_runOnUserUpdateListeners(e){for(let t of this._userProfileListeners)typeof t=="function"&&t(e);}_runOnLoginListeners(e){for(let t of this._onLoginListeners)typeof t=="function"&&t(e);}get onBatchProcess(){return this._onBatchProcessListeners}set onBatchProcess(e){typeof e=="function"&&this._onBatchProcessListeners.push(e);}_alert(e){Y()&&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||(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(e){let t=e?.refresh||false;try{this.connection=await T.bind(this)("service",{service:this.service,owner:this.owner,refresh:t},{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 t=`Built with:
218
+ Watch the video here: ${e.video}`}var S=class{constructor(e,t,n,i){this.__version="2.0.0-rc.4";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 m.UserId(e),!0}catch{return false}},url(e){try{return m.Url(e),!0}catch{return false}},phoneNumber(e){try{return m.PhoneNumber(e),!0}catch{return false}},birthdate(e){try{return m.Birthdate(e),!0}catch{return false}},email(e){try{return m.Email(e),!0}catch{return false}},params(e,t,n){return m.Params(e,t,n)}};this.util={MD5:K,generateRandom:De,toBase62:ei,fromBase62:ie,decodeProjectId:Ur,formatServiceId:Cr,extractFormData:M,terminatePendingRequests:Ii,request:(e,t,n)=>T.bind(this)(e,t,n,{ignoreService:true})};this.__network_logs=false;this.__endpoint_version="v2";this.__public_identifier="";this.bearerToken="";this.registerTicket=si.bind(this);this.unregisterTicket=oi.bind(this);if(!e||typeof e!="string")throw this._alert("Service ID is required."),new f("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 f("Project ID is required.",{code:"INVALID_PARAMETER"});let o=e.split("-").length;if(o===2||o===7)try{let b=Ur(e);n&&typeof n=="object"&&(i=n),t&&typeof t=="object"&&(n=t),t=b.owner,e=b.service;}catch{throw this._alert("Service ID is invalid."),new f("Service ID is invalid.",{code:"INVALID_PARAMETER"})}if(!t||typeof t!="string")throw this._alert("Owner ID is invalid."),new f("Owner ID is invalid.",{code:"INVALID_PARAMETER"});if(t!==this.host)try{m.UserId(t,'"owner"');}catch{throw this._alert("Owner ID is invalid."),new f("Owner ID is invalid.",{code:"INVALID_PARAMETER"})}this.service=e,this.owner=t;try{this.project_id=Cr(e,t);}catch{this.project_id="";}let c=true,l=false;if(n&&(typeof n.refetchServiceInfo=="boolean"&&(l=n.refetchServiceInfo),typeof n.autoLogin=="boolean"&&(c=n.autoLogin),typeof n.requestBatchSize=="number")){if(n.requestBatchSize<1)throw new f('"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`,h=e.substring(0,4);this.admin_endpoint=fetch(`${d}/${h}/admin-${this.__endpoint_version}.json`).then(b=>b.blob()).then(b=>new Promise((A,x)=>{let I=new FileReader;I.onloadend=()=>A(I.result),I.onerror=x,I.readAsDataURL(b);})).then(b=>{try{return typeof b=="string"?JSON.parse(atob(b.split(",")[1])):null}catch{throw new f("Service does not exist. Create your service from skapi.com",{code:"NOT_EXISTS"})}}),this.record_endpoint=fetch(`${d}/${h}/record-${this.__endpoint_version}.json`).then(b=>b.blob()).then(b=>new Promise((A,x)=>{let I=new FileReader;I.onloadend=()=>A(I.result),I.onerror=x,I.readAsDataURL(b);})).then(b=>{try{return typeof b=="string"?JSON.parse(atob(b.split(",")[1])):null}catch{throw new f("Service does not exist. Create your service from skapi.com",{code:"NOT_EXISTS"})}});let p=Y();if(p&&!window.sessionStorage)throw this._alert("This browser is not supported."),new Error("This browser is not supported.");let g=p?JSON.parse(window.sessionStorage.getItem(`${e}#${t}`)||"null"):null;if(this.log("constructor:restore",g),g?.connection){for(let b in g)this[b]=g[b];g.__public_identifier||(this.__public_identifier=`${this.service}:${this.owner}:${De(16)}`);}this.__authConnection=(async()=>{let b=await this.admin_endpoint,A={UserPoolId:b.userpool_id,ClientId:b.userpool_client};xr()&&(A.Storage=window.localStorage),this.userPool=new Rr(A);try{this.user||await G.bind(this)().getSession({skipUserUpdateEventTrigger:!0}),this.user&&(!g?.connection&&!c?Ae.bind(this)():(this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user)));}catch{}})();let _=`${this.service}/${this.owner}`,w=p?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,g?.connection||(b=this._updateConnection({refresh:l}));let A=()=>{if(this.__class_properties_has_been_cached)return;let x=()=>{let I={},D=["__startKeyHistory","__disabledAccount","__cached_requests","__request_signup_confirmation","__public_identifier","connection"];if(this.connection){for(let F of D)I[F]=this[F];if(p){let F=`${e}#${t}`;try{window.sessionStorage.setItem(F,JSON.stringify(I));}catch{try{let L=Object.assign({},I,{__cached_requests:{},__startKeyHistory:{}});window.sessionStorage.setItem(F,JSON.stringify(L));}catch{try{window.sessionStorage.removeItem(F);}catch{}}}}this.__class_properties_has_been_cached=true;}};return b instanceof Promise?b.then(()=>x()):x()};return p&&(window.addEventListener("beforeunload",()=>{this.closeRealtime(),A();}),window.addEventListener("visibilitychange",()=>{A();})),await b,await this.__authConnection,this.connection})(),this.__connection.then(b=>{((b?.group||0)<3||this.__network_logs)&&this.version();});}get user(){return this.__user&&Object.keys(this.__user).length?JSON.parse(JSON.stringify(this.__user)):null}set user(e){}get onLogin(){return this._onLoginListeners}set onLogin(e){typeof e=="function"&&this._onLoginListeners.push(e);}get onUserUpdate(){return this._userProfileListeners}set onUserUpdate(e){typeof e=="function"&&this._userProfileListeners.push(e);}_runOnUserUpdateListeners(e){for(let t of this._userProfileListeners)typeof t=="function"&&t(e);}_runOnLoginListeners(e){for(let t of this._onLoginListeners)typeof t=="function"&&t(e);}get onBatchProcess(){return this._onBatchProcessListeners}set onBatchProcess(e){typeof e=="function"&&this._onBatchProcessListeners.push(e);}_alert(e){Y()&&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||(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(e){let t=e?.refresh||false;try{this.connection=await T.bind(this)("service",{service:this.service,owner:this.owner,refresh:t},{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 t=`Built with:
219
219
  %c\r
220
220
  $$\\ $$\\ \r
221
221
  $$ | \\__|\r