skapi-js 1.5.3 → 1.5.4-beta.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/skapi.browser.mjs +5 -5
- package/dist/skapi.browser.mjs.map +1 -1
- package/dist/skapi.cjs +2 -2
- package/dist/skapi.cjs.map +1 -1
- package/dist/skapi.js +5 -5
- 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.cjs
CHANGED
|
@@ -212,9 +212,9 @@ var Fn=Object.defineProperty;var Mn=Object.getOwnPropertyDescriptor;var ee=(n=>t
|
|
|
212
212
|
}
|
|
213
213
|
|
|
214
214
|
runInterval(); // Start interval
|
|
215
|
-
`,o=new Blob([s],{type:"application/javascript"});Z=new Worker(URL.createObjectURL(o)),Z.onmessage=a=>{i.readyState===1&&i.send(JSON.stringify({action:"keepAlive"}));},r(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 l={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")n(l);else if(a==="rtc"){if(l.sender!==this.user.user_id){let d=l.message;if(d.hungup){B[l.sender_cid]&&(B[l.sender_cid](false),delete B[l.sender_cid]),W[l.sender_cid]&&delete W[l.sender_cid],I?.[l.sender_cid]&&K.bind(this)({cid:l.sender_cid}),l.type="rtc:closed",n(l);return}if(d.candidate&&je.bind(this)(d.candidate,l.sender_cid),d.sdpoffer&&(qe.bind(this)(d.sdpoffer,l.sender_cid),W[l.sender_cid]||(W[l.sender_cid]=l.sender_cid,delete l.message,l.connectRTC=Gt.bind(this)(l),l.type="rtc:incoming",l.hangup=(()=>{I[l.sender_cid]?K.bind(this)({cid:l.sender_cid}):W[l.sender_cid]&&(delete W[l.sender_cid],i.send(JSON.stringify({action:"rtc",uid:l.sender_cid,content:{hungup:this.user.user_id},token:this.session.accessToken.jwtToken})));}).bind(this),n(l))),d.pickup&&B[l.sender_cid]&&(B[l.sender_cid](true),delete B[l.sender_cid]),d.sdpanswer&&I[l.sender_cid])if(I[l.sender_cid].signalingState==="have-local-offer")await I[l.sender_cid].setRemoteDescription(new RTCSessionDescription(d.sdpanswer));else throw new c("Invalid signaling state.",{code:"INVALID_REQUEST"})}}else n(l);},i.onclose=()=>{ge?(this.log("realtime onclose","WebSocket connection closed."),n({type:"close",message:"WebSocket connection closed."})):(this.log("realtime onclose","WebSocket unexpected close."),n({type:"error",message:"Skapi: WebSocket unexpected close."}),se++,se<3?(this.log("realtime onclose","Reconnecting to WebSocket server..."+se),n({type:"reconnect",message:"Reconnecting to WebSocket server..."+se}),ke.bind(this)(n,3e3,"reconnect")):(this.log("realtime onclose","Max reconnection attempts reached."),n({type:"error",message:"Skapi: Max reconnection attempts reached."})));},i.onerror=()=>{this.log("realtime onerror","WebSocket connection error."),n({type:"error",message:"Skapi: WebSocket connection error."});};},e);});}async function en(n,e,t){if(typeof window>"u"||window._runningInNodeJS)throw new c("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});let r=this.__socket?await this.__socket:this.__socket;if(!r)throw new c("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});if(!e)throw new c("No recipient.",{code:"INVALID_REQUEST"});await ne.bind(this)(),n=N(n).data;let i="";if(t&&(t=g.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 c("Notification size exceeds 3kb.",{code:"INVALID_PARAMETER"});if(r.readyState===1){try{g.UserId(e),r.send(JSON.stringify({action:"sendMessage",uid:e,content:n,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}),Y!==e)throw new c(`User has not joined to the recipient group. Run joinRealtime({ group: "${e}" })`,{code:"INVALID_REQUEST"});r.send(JSON.stringify({action:"broadcast",rid:e,content:n,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 c("Realtime connection is not open. Try reconnecting with connectRealtime().",{code:"INVALID_REQUEST"})}async function Ke(n){if(typeof window>"u"||window._runningInNodeJS)throw new c("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});let e=this.__socket?await this.__socket:this.__socket;if(!e)throw new c("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});await ne.bind(this)(),n=N(n,{nullIfEmpty:true}).data;let{group:t=null}=n;if(!t&&!Y)return {type:"success",message:"Left realtime message group."};if(t!==null&&typeof t!="string")throw new c('"group" must be a string | null.',{code:"INVALID_PARAMETER"});return e.send(JSON.stringify({action:"joinRoom",rid:t,token:this.session.accessToken.jwtToken})),Y=t,{type:"success",message:t?`Joined realtime message group: "${t}".`:"Left realtime message group."}}async function tn(n,e){n=g.Params(n,{user_id:r=>g.UserId(r,'User ID in "user_id"'),group:["string",()=>{if(!Y)throw new c('No group has been joined. Otherwise "group" is required.',{code:"INVALID_REQUEST"});return Y}]});let t=await w.bind(this)("get-ws-group",n,{fetchOptions:e,auth:true,method:"post"});return t.list=t.list.map(r=>({user_id:r.uid.split("#")[1],cid:"cid:"+r.cid})),t}async function nn(n,e){if(await this.__connection,n||(n={searchFor:"group",value:" ",condition:">"}),n=g.Params(n,{searchFor:["group","number_of_users",()=>"group"],value:["string","number",()=>n?.searchFor&&n?.searchFor==="number_of_users"?0:" "],condition:[">",">=","=","<","<=","!=","gt","gte","eq","lt","lte","ne"],range:["string","number"]}),n.condition||(n.value===" "||!n.value?n.condition=">":n.condition="="),n.range&&n.condition&&delete n.condition,n.searchFor==="number_of_users"&&typeof n.value!="number")throw new c('"value" must be a number.',{code:"INVALID_PARAMETER"});if(n.searchFor==="group"&&typeof n.value!="string")throw new c('"value" must be a string.',{code:"INVALID_PARAMETER"});if(n.hasOwnProperty("range")&&typeof n.range!=typeof n.value)throw new c(`"range" must be a ${typeof n.value}.`,{code:"INVALID_PARAMETER"});let t=await w.bind(this)("get-ws-group",n,{fetchOptions:e,auth:true,method:"post"});return t.list=t.list.map(r=>({group:r.rid.split("#")[1],number_of_users:r.cnt})),t}var Ur=typeof FormData<"u",Nr=typeof HTMLFormElement<"u",Cr=typeof SubmitEvent<"u";function rn({id:n,auth:e,service:t,owner:r,latency:i=1e3}){return new Promise((s,o)=>{let a=setInterval(async()=>{try{let l=await w.bind(this)("csr-poll",{id:n,service:t,owner:r},{auth:e});if(l.status==="pending")return;clearInterval(a),s(l);}catch(l){clearInterval(a),o(l);}},i);})}async function sn(n){let e=false,t=typeof n.poll=="number"?n.poll:0;n.poll=!!n.poll;let r=s=>{for(let o in s)if(typeof s[o]=="string"&&s[o].includes("$CLIENT_SECRET")){e=true;break}};if(n=g.Params(n,{url:s=>{if(!s||typeof s!="string")throw new c('"url" should be type: <string>.',{code:"INVALID_PARAMETER"});return g.Url(s),s.includes("$CLIENT_SECRET")&&(e=true),s},clientSecretName:"string",method:s=>{if(s&&typeof s!="string")throw new c('"method" should be either "GET" or "POST" or "DELETE" or "PUT".',{code:"INVALID_PARAMETER"});let o=s.toLowerCase();if(o!=="get"&&o!=="post"&&o!=="delete"&&o!=="put")throw new c('"method" should be either "GET" or "POST" or "DELETE" or "PUT".',{code:"INVALID_PARAMETER"});return o},headers:s=>{if(s&&typeof s!="object")throw new c('"headers" should be type: <object>.',{code:"INVALID_PARAMETER"});return r(s),s},data:s=>{if(s&&typeof s!="object")throw new c('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return r(s),s},params:s=>{if(s&&typeof s!="object")throw new c('"params" should be type: <object>.',{code:"INVALID_PARAMETER"});return r(s),s},poll:"boolean",expires:"number"},["clientSecretName","method","url"]),!e)throw new c(`At least one parameter value should include "$CLIENT_SECRET" in ${n.method.toLowerCase()==="post"?'"data"':'"params"'} or "headers".`,{code:"INVALID_PARAMETER"});await this.__connection;let i=!!this.__user;return w.bind(this)("csr",n,{auth:i,tokenHeaders:{accessToken:!!i}}).then(s=>{if(t&&s.id&&s.status==="pending"){let a=`[${n.method.toUpperCase()}]${n.url.toLowerCase()}`+":"+s.id;return rn.call(this,{id:a,auth:i,service:n.service,owner:n.owner,latency:t})}else return s})}async function on(n,e){await this.__connection;let t=!!n.poll,r=typeof n.poll=="number"?n.poll:1e3;n=g.Params(n,{url:"string",method:["GET","POST","DELETE","PUT"]},["url","method"]);let i=!!this.__user,s=`[${n.method.toUpperCase()}]${n.url.toLowerCase()}:`,o=await w.bind(this)("csr-poll",{id:s,service:n.service,owner:n.owner},{auth:i,fetchOptions:e}),a=[];return o.list=o.list.map(l=>{let d={id:l.id,status_code:l.rslv?.status_code||null,response_body:l.rslv?.body||l.rslv?.truncated||null,error:l.err,updated:l.utmp,request_body:l.reqbdy,expires:l.stts!=="pending"?l.expt:null,status:l.stts||null};return t&&d.status==="pending"&&typeof d.id=="string"&&a.push(d.id),d}),t&&(o.pending=a.map(l=>rn.call(this,{id:s+l,auth:i,service:n.service,owner:n.owner,latency:r}).then(d=>({...d})).catch(d=>({error:d,id:l})))),o}async function an(n){await this.__connection;let e={name:"string",email:t=>(g.Email(t),t),subject:"string",message:"string"};return n=g.Params(n,e,["name","email","subject","message"]),await w.bind(this)("send-inquiry",n),"SUCCESS: Inquiry has been sent."}async function cn(n,e){if(await this.__connection,Ur&&n instanceof FormData||Nr&&n instanceof HTMLFormElement||Cr&&n instanceof SubmitEvent){if(!e)throw new c("Url string as a second argument is required when form is passed.",{code:"INVALID_PARAMETER"});let r=N(n);n={url:e,data:r.data,sync:true};}let t={url:r=>g.Url(r),data:r=>r,sync:["boolean",()=>true]};if(Array.isArray(n))for(let r of n)r=g.Params(r,t);else n=g.Params(n,t);return w.bind(this)("post-secure",n,{auth:true})}async function ln(n,e){await this.__connection;let{auth:t=false,method:r="POST",bypassAwaitConnection:i=false,responseType:s,contentType:o,tokenHeaders:a,progress:l}=e||{};if(e=Object.assign({auth:t,method:r,bypassAwaitConnection:i,responseType:s,contentType:o,tokenHeaders:a},{fetchOptions:{progress:l}}),typeof n!="object"&&(o==="application/json"||o===void 0))throw new c('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return w.bind(this)("mock",n,e)}async function un(n,e){await this.__connection,n=g.Params(n||{},{access_group:r=>{if(r==="authorized"&&(r=1),r==="public"&&(r=0),typeof r!="number")throw new c('"access_group" should be type number.',{code:"INVALID_PARAMETER"});if(r<0)throw new c('"access_group" should be zero or a positive number.',{code:"INVALID_PARAMETER"});if(r>this.__user.access_group)throw new c("User has no access.",{code:"INVALID_REQUEST"});return r}});let t=await w.bind(this)("get-feed",n,{auth:true,fetchOptions:e});for(let r in t.list)t.list[r]=await ie.bind(this)(t.list[r]);return t}function fe(n){if(n===this.__user.user_id)throw new c(`"user_id" cannot be the user's own ID.`,{code:"INVALID_PARAMETER"});return g.UserId(n,'"user_id"')}async function dn(n,e){if(n=N(n,{ignoreEmpty:true}).data,n=g.Params(n,{subscriber:r=>g.UserId(r,'User ID in "subscriber"'),subscription:fe.bind(this),blocked:"boolean"}),!n.subscriber&&!n.subscription)throw new c('At least either "subscriber" or "subscription" should have a value.',{code:"INVALID_PARAMETER"});let t=await w.bind(this)("get-subscription",n,Object.assign({auth:true},{fetchOptions:e}));return t.list=t.list.map((r=>{let i={};if(r.sub){let s=r.sub.split("#");i.subscriber=s[2],i.subscription=s[0];}else i.subscriber=r.subscriber,i.subscription=r.subscription;return i.timestamp=r?.timestamp||r.stmp,i.blocked=r?.blocked||r.grp.substring(0,1)==="N",Object.assign(i,r.opt),i})),t}async function gn(n){await this.__connection,n=g.Params(n,{user_id:fe.bind(this),get_feed:["boolean",()=>false],get_notified:["boolean",()=>false],get_email:r=>{if(r&&!this.__user.email||!this.__user.email_verified)throw new c("User has no verified email address.",{code:"INVALID_REQUEST"});return !!r}},["user_id"]);let e=await w.bind(this)("subscription",{subscribe:n.user_id,option:{get_feed:n.get_feed,get_notified:n.get_notified,get_email:n.get_email||false}},{auth:true}),t={};if(e.sub){let r=e.sub.split("#");t.subscriber=r[2],t.subscription=r[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 fn(n){await this.__connection;let{user_id:e}=g.Params(n,{user_id:fe.bind(this)},["user_id"]);return await w.bind(this)("subscription",{unsubscribe:e},{auth:true})}async function hn(n){await this.__connection;let{user_id:e}=g.Params(n,{user_id:fe.bind(this)},["user_id"]);return await w.bind(this)("subscription",{block:e},{auth:true})}async function pn(n){await this.__connection;let{user_id:e}=g.Params(n,{user_id:fe.bind(this)},["user_id"]);return await w.bind(this)("subscription",{unblock:e},{auth:true})}async function mn(n,e){await this.__connection;let t=await M.bind(this)();n=g.Params(n,{user_id:o=>{if(o!==this.__user.user_id&&!t)throw new c("No access.",{code:"INVALID_REQUEST"});return o},group:o=>{if(o==="public"&&(o=0),o==="authorized"&&(o=1),typeof o!="number")throw new c('"group" should be type number | "public" | "authorized".',{code:"INVALID_PARAMETER"});return o}});let r=await w.bind(this)("get-newsletter-subscription",n,{auth:true,fetchOptions:e||null}),i=r?.list||r,s=[];Array.isArray(i)||(i=[]);for(let o of i){let a=o.subt.split("#"),l=true;a[0].charAt(0)==="@"&&(l=false,a[0]=a[0].substring(1));let d=parseInt(a[0]);s.push({timestamp:o.stmp,group:d,subscribed_email:a[1],active:l});}return r?.list?(r.list=s,r):s}async function _n(n){await this.__connection;let e=g.Params(n||{},{email:t=>Array.isArray(t)&&t.length>0?t.length===1?g.Email(t[0]):t.map(r=>g.Email(r)):g.Email(t),group:["number","public","authorized","admin",t=>{if(typeof t!="string"||t.length>20||!/^[a-zA-Z0-9]+$/.test(t))throw new c('"group" should be an alphanumeric string without spaces and less than 20 characters.',{code:"INVALID_PARAMETER"});return t}],redirect:t=>g.Url(t)},this.__user?["group"]:["email","group"]);return w.bind(this)(`subscribe-${this.__user?"":"public-"}newsletter`,e,{auth:!!this.__user})}async function bn(n){await this.__connection,n=g.Params(n,{group:["number","public","authorized","admin"]},["group"]);let e=Object.assign({action:"unsubscribe"},n);return w.bind(this)("subscribe-newsletter",e,{auth:true})}async function yn(n,e){let t=await M.bind(this)(),r={message_id:"string",timestamp:"number",read:"number",complaint:"number",subject:"string",bounced:"number"};n||(e=Object.assign({ascending:false},e||{})),n=N(n).data,n=n||{searchFor:"timestamp",value:Date.now(),condition:"<",group:"public"},n=g.Params(n,{searchFor:["message_id","timestamp","subject","complaint","read","bounced"],value:l=>{if(typeof l!==r[n.searchFor])throw new c(`"value" type does not match the type of "${n.searchFor}" index.`,{code:"INVALID_PARAMETER"});if(typeof l=="string"&&!l)throw new c('"value" should not be empty string.',{code:"INVALID_PARAMETER"});return l},range:l=>{if(!n.hasOwnProperty("value")||typeof l!=typeof n.value)throw new c('"range" should match type of "value".',{code:"INVALID_PARAMETER"});return l},condition:[">",">=","=","<","<=","gt","gte","eq","lt","lte",()=>"="],group:l=>{if(l==="public")return 0;if(!this.session)throw new c("User should be logged in.",{code:"INVALID_REQUEST"});if(l==="authorized")return 1;if(typeof l=="number"){if(!t&&l>parseInt(this.user?.access_group||this.session?.idToken?.payload?.access_group))throw new c("User has no access.",{code:"INVALID_REQUEST"});return l}throw new c('"group" should be type: number | "public" | "authorized".',{code:"INVALID_PARAMETER"})}},["searchFor","value","group"]);let i=n.group===0?"get-public-newsletters":"get-newsletters",s=await w.bind(this)(i,n,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(l=>{let d={};for(let h in o)d[h]=l[o[h]]||a[h];return d.bounced=String(d.bounced),d}),s}async function wn(n){let e=g.Params(n,{user_id:r=>g.UserId(r,'"user_id"')},["user_id"]);if(e?.service&&e?.owner?e={service:e?.service,owner:e?.owner,block:e.user_id}:e={block:e.user_id},!await M.bind(this)()){if(!this.__user)throw new c("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new c("Invalid access.",{code:"INVALID_REQUEST"})}return await w.bind(this)("block-account",e,{auth:true})}async function En(n){let e=g.Params(n,{user_id:r=>g.UserId(r,'"user_id"')},["user_id"]);if(e?.service&&e?.owner?e={service:e?.service,owner:e?.owner,unblock:e.user_id}:e={unblock:e.user_id},!await M.bind(this)()){if(!this.__user)throw new c("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new c("Invalid access.",{code:"INVALID_REQUEST"})}return await w.bind(this)("block-account",e,{auth:true})}async function Rn(n){let e=g.Params(n,{user_id:r=>g.UserId(r,'"user_id"')},["user_id"]);if(e?.service&&e?.owner?e={service:e?.service,owner:e?.owner,delete:e.user_id}:e={delete:e.user_id},!await M.bind(this)()){if(!this.__user)throw new c("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new c("Invalid access.",{code:"INVALID_REQUEST"})}return await w.bind(this)("remove-account",e,{auth:true})}async function An(n,e){let t={email:s=>g.Email(s),password:s=>g.Password(s),name:"string",username:"string",gender:"string",address:s=>{if(!s)return "";if(typeof s=="string")return s;if(typeof s=="object")return JSON.stringify(s)},birthdate:s=>g.Birthdate(s),phone_number:s=>g.PhoneNumber(s),picture:s=>{if(s)return g.Url(s)},profile:s=>{if(s)return g.Url(s)},website:s=>{if(s)return g.Url(s)},nickname:"string",misc:"string",email_public:["boolean",()=>false],gender_public:["boolean",()=>false],address_public:["boolean",()=>false],birthdate_public:["boolean",()=>false],phone_number_public:["boolean",()=>false],openid_id:"string",access_group:s=>{try{typeof s=="string"&&(s=s==="admin"?99:parseInt(s));}catch{throw new c('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof s!="number"||s<1||s>100)throw new c('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"});return s}},r=g.Params(n,t,["email"]);if(e=g.Params(e,{confirmation_url:s=>{let o=s;if(typeof s=="string")o=g.Url(s);else throw new c('"options.confirmation_url" should be type: <string>.',{code:"INVALID_PARAMETER"});if(o&&!r.email)throw new c('"email" is required for signup confirmation.',{code:"INVALID_PARAMETER"});return o},email_subscription:s=>{if(typeof s!="boolean")throw new c('"options.email_subscription" should be type: <boolean>.',{code:"INVALID_PARAMETER"});if(!e?.confirmation_url)throw new c('"options.confirmation_url" is required for email subscription.',{code:"INVALID_PARAMETER"});return s},template:s=>{if(typeof s!="object"||!s.url||!s.subject)throw new c('"options.template" should be type: <object> with "url" and "subject".',{code:"INVALID_PARAMETER"});return {url:g.Url(s.url),subject:s.subject}}}),r.signup_confirmation=e?.confirmation_url||true,r.email_subscription=e?.email_subscription||false,r.template=e?.template||{},!await M.bind(this)()){if(!this.__user)throw new c("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new c("Invalid access.",{code:"INVALID_REQUEST"})}return await w.bind(this)("admin-signup",r,{auth:true})}async function In(n){let e={email:i=>g.Email(i),password:i=>g.Password(i),openid_id:"string",name:"string",username:"string",gender:"string",address:i=>{if(!i)return "";if(typeof i=="string")return i;if(typeof i=="object")return JSON.stringify(i)},birthdate:i=>g.Birthdate(i),phone_number:i=>g.PhoneNumber(i),picture:i=>i?g.Url(i):"",profile:i=>i?g.Url(i):"",website:i=>i?g.Url(i):"",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:i=>{try{typeof i=="string"&&(i=parseInt(i));}catch{throw new c('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof i!="number"||i<1||i>100)throw new c('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"});return i}},t=g.Params(n,e,["email","password"]);if(!await M.bind(this)()){if(!this.__user)throw new c("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new c("Invalid access.",{code:"INVALID_REQUEST"})}return await w.bind(this)("admin-signup",t,{auth:true})}async function Tn(n){if(n=g.Params(n,{user_id:t=>g.UserId(t,'"user_id"'),access_group:t=>{try{typeof t=="string"&&(t=parseInt(t));}catch{throw new c('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof t=="number"&&t>0&&t<100)return t;throw new c('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"})}},["user_id","access_group"]),!await M.bind(this)()){if(!this.__user)throw new c("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new c("Invalid access.",{code:"INVALID_REQUEST"})}return await w.bind(this)("grant-access",n,{auth:true})}async function Pn(n,e){if(n=g.Params(n,{email:"string"}),!await M.bind(this)()){if(!this.__user)throw new c("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new c("Invalid access.",{code:"INVALID_REQUEST"})}let r=await w.bind(this)("invitation-list",Object.assign({mode:"search"},n),{fetchOptions:e,auth:true});return r.list=r.list.map(i=>ae(i.user)),r}async function Sn(n){if(n=g.Params(n,{email:t=>g.Email(t)},["email"]),!await M.bind(this)()){if(!this.__user)throw new c("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new c("Invalid access.",{code:"INVALID_REQUEST"})}return await w.bind(this)("invitation-list",Object.assign({mode:"cancel"},n),{auth:true})}async function kn(n){if(n=g.Params(n,{email:t=>g.Email(t)},["email"]),!await M.bind(this)()){if(!this.__user)throw new c("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new c("Invalid access.",{code:"INVALID_REQUEST"})}return await w.bind(this)("invitation-list",Object.assign({mode:"resend"},n),{auth:true})}async function xn(n){if(typeof window>"u"||window._runningInNodeJS)throw new c("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.__connection,!n.endpoint)throw new c("Missing parameter: endpoint",{code:"INVALID_PARAMETER"});if(!n.keys||!n.keys.p256dh||!n.keys.auth)throw new c("Missing parameter: keys.p256dh or keys.auth",{code:"INVALID_PARAMETER"});return await w.bind(this)("store-subscription",{endpoint:n.endpoint,keys:n.keys},{auth:true}),"SUCCESS: Subscribed to receive notifications."}async function vn(n){if(typeof window>"u"||window._runningInNodeJS)throw new c("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.__connection,!n.endpoint)throw new c("Missing parameter: endpoint",{code:"INVALID_PARAMETER"});if(!n.keys||!n.keys.p256dh||!n.keys.auth)throw new c("Missing parameter: keys.p256dh or keys.auth",{code:"INVALID_PARAMETER"});return await w.bind(this)("delete-subscription",{endpoint:n.endpoint,keys:n.keys},{auth:true}),"SUCCESS: Unsubscribed from notifications."}async function Dn(){if(typeof window>"u"||window._runningInNodeJS)throw new c("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});return await this.__connection,{VAPIDPublicKey:await w.bind(this)("get-vapid-public-key",null,{auth:true})}}async function Un(n,e){if(typeof window>"u"||window._runningInNodeJS)throw new c("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});await this.__connection;let{title:t,body:r}=N(n||{},{nullIfEmpty:true}).data;if(!t)throw new c("Missing parameter: message title",{code:"INVALID_PARAMETER"});if(!r)throw new c("Missing parameter: message body",{code:"INVALID_PARAMETER"});let i={title:t,body:r};return e?(typeof e=="string"&&(e=[e]),i.user_ids=e):i.user_ids="all_users",await w.bind(this)("push-notification",i,{auth:true}),"SUCCESS: Notification sent."}async function Nn(n){await this.__connection,n=g.Params(n,{spell:"string",name:"string",magic:t=>t},["spell","name"]);await w.bind(this)("castspell",n);return `The spell "${n.spell}" has been cast.`}async function Cn(n){return await this.__connection,n=g.Params(n||{},{search:["spell","name",()=>"spell"],value:"string"}),await w.bind(this)("getspell",n)}async function Ln(n){await this.__connection,n=g.Params(n,{message:"string",name:"string"},["message","name"]);let e=await w.bind(this)("dopamine",n,{auth:true}),t=e?.previous_message?.message,r=e?.previous_message?.name;if($())t&&r&&window.alert(`${r} said: ${t}`),window.location.href=e.video;else return t&&r?`${r} said: ${t}
|
|
215
|
+
`,o=new Blob([s],{type:"application/javascript"});Z=new Worker(URL.createObjectURL(o)),Z.onmessage=a=>{i.readyState===1&&i.send(JSON.stringify({action:"keepAlive"}));},r(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 l={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")n(l);else if(a==="rtc"){if(l.sender!==this.user.user_id){let d=l.message;if(d.hungup){B[l.sender_cid]&&(B[l.sender_cid](false),delete B[l.sender_cid]),W[l.sender_cid]&&delete W[l.sender_cid],I?.[l.sender_cid]&&K.bind(this)({cid:l.sender_cid}),l.type="rtc:closed",n(l);return}if(d.candidate&&je.bind(this)(d.candidate,l.sender_cid),d.sdpoffer&&(qe.bind(this)(d.sdpoffer,l.sender_cid),W[l.sender_cid]||(W[l.sender_cid]=l.sender_cid,delete l.message,l.connectRTC=Gt.bind(this)(l),l.type="rtc:incoming",l.hangup=(()=>{I[l.sender_cid]?K.bind(this)({cid:l.sender_cid}):W[l.sender_cid]&&(delete W[l.sender_cid],i.send(JSON.stringify({action:"rtc",uid:l.sender_cid,content:{hungup:this.user.user_id},token:this.session.accessToken.jwtToken})));}).bind(this),n(l))),d.pickup&&B[l.sender_cid]&&(B[l.sender_cid](true),delete B[l.sender_cid]),d.sdpanswer&&I[l.sender_cid])if(I[l.sender_cid].signalingState==="have-local-offer")await I[l.sender_cid].setRemoteDescription(new RTCSessionDescription(d.sdpanswer));else throw new c("Invalid signaling state.",{code:"INVALID_REQUEST"})}}else n(l);},i.onclose=()=>{ge?(this.log("realtime onclose","WebSocket connection closed."),n({type:"close",message:"WebSocket connection closed."})):(this.log("realtime onclose","WebSocket unexpected close."),n({type:"error",message:"Skapi: WebSocket unexpected close."}),se++,se<3?(this.log("realtime onclose","Reconnecting to WebSocket server..."+se),n({type:"reconnect",message:"Reconnecting to WebSocket server..."+se}),ke.bind(this)(n,3e3,"reconnect")):(this.log("realtime onclose","Max reconnection attempts reached."),n({type:"error",message:"Skapi: Max reconnection attempts reached."})));},i.onerror=()=>{this.log("realtime onerror","WebSocket connection error."),n({type:"error",message:"Skapi: WebSocket connection error."});};},e);});}async function en(n,e,t){if(typeof window>"u"||window._runningInNodeJS)throw new c("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});let r=this.__socket?await this.__socket:this.__socket;if(!r)throw new c("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});if(!e)throw new c("No recipient.",{code:"INVALID_REQUEST"});await ne.bind(this)(),n=N(n).data;let i="";if(t&&(t=g.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 c("Notification size exceeds 3kb.",{code:"INVALID_PARAMETER"});if(r.readyState===1){try{g.UserId(e),r.send(JSON.stringify({action:"sendMessage",uid:e,content:n,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}),Y!==e)throw new c(`User has not joined to the recipient group. Run joinRealtime({ group: "${e}" })`,{code:"INVALID_REQUEST"});r.send(JSON.stringify({action:"broadcast",rid:e,content:n,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 c("Realtime connection is not open. Try reconnecting with connectRealtime().",{code:"INVALID_REQUEST"})}async function Ke(n){if(typeof window>"u"||window._runningInNodeJS)throw new c("WebSocket is not supported in Node.js environment.",{code:"NOT_SUPPORTED"});let e=this.__socket?await this.__socket:this.__socket;if(!e)throw new c("No realtime connection. Execute connectRealtime() before this method.",{code:"INVALID_REQUEST"});await ne.bind(this)(),n=N(n,{nullIfEmpty:true}).data;let{group:t=null}=n;if(!t&&!Y)return {type:"success",message:"Left realtime message group."};if(t!==null&&typeof t!="string")throw new c('"group" must be a string | null.',{code:"INVALID_PARAMETER"});return e.send(JSON.stringify({action:"joinRoom",rid:t,token:this.session.accessToken.jwtToken})),Y=t,{type:"success",message:t?`Joined realtime message group: "${t}".`:"Left realtime message group."}}async function tn(n,e){n=g.Params(n,{user_id:r=>g.UserId(r,'User ID in "user_id"'),group:["string",()=>{if(!Y)throw new c('No group has been joined. Otherwise "group" is required.',{code:"INVALID_REQUEST"});return Y}]});let t=await w.bind(this)("get-ws-group",n,{fetchOptions:e,auth:true,method:"post"});return t.list=t.list.map(r=>({user_id:r.uid.split("#")[1],cid:"cid:"+r.cid})),t}async function nn(n,e){if(await this.__connection,n||(n={searchFor:"group",value:" ",condition:">"}),n=g.Params(n,{searchFor:["group","number_of_users",()=>"group"],value:["string","number",()=>n?.searchFor&&n?.searchFor==="number_of_users"?0:" "],condition:[">",">=","=","<","<=","!=","gt","gte","eq","lt","lte","ne"],range:["string","number"]}),n.condition||(n.value===" "||!n.value?n.condition=">":n.condition="="),n.range&&n.condition&&delete n.condition,n.searchFor==="number_of_users"&&typeof n.value!="number")throw new c('"value" must be a number.',{code:"INVALID_PARAMETER"});if(n.searchFor==="group"&&typeof n.value!="string")throw new c('"value" must be a string.',{code:"INVALID_PARAMETER"});if(n.hasOwnProperty("range")&&typeof n.range!=typeof n.value)throw new c(`"range" must be a ${typeof n.value}.`,{code:"INVALID_PARAMETER"});let t=await w.bind(this)("get-ws-group",n,{fetchOptions:e,auth:true,method:"post"});return t.list=t.list.map(r=>({group:r.rid.split("#")[1],number_of_users:r.cnt})),t}var Ur=typeof FormData<"u",Nr=typeof HTMLFormElement<"u",Cr=typeof SubmitEvent<"u";function rn({id:n,auth:e,service:t,owner:r,latency:i=1e3}){return new Promise((s,o)=>{let a=setInterval(async()=>{try{let l=await w.bind(this)("csr-poll",{id:n,service:t,owner:r},{auth:e});if(l.status==="pending")return;clearInterval(a),s(l);}catch(l){clearInterval(a),o(l);}},i);})}async function sn(n){let e=false,t=typeof n.poll=="number"?n.poll:0;n.poll=!!n.poll;let r=s=>{for(let o in s)if(typeof s[o]=="string"&&s[o].includes("$CLIENT_SECRET")){e=true;break}};if(n=g.Params(n,{url:s=>{if(!s||typeof s!="string")throw new c('"url" should be type: <string>.',{code:"INVALID_PARAMETER"});return g.Url(s),s.includes("$CLIENT_SECRET")&&(e=true),s},clientSecretName:"string",method:s=>{if(s&&typeof s!="string")throw new c('"method" should be either "GET" or "POST" or "DELETE" or "PUT".',{code:"INVALID_PARAMETER"});let o=s.toLowerCase();if(o!=="get"&&o!=="post"&&o!=="delete"&&o!=="put")throw new c('"method" should be either "GET" or "POST" or "DELETE" or "PUT".',{code:"INVALID_PARAMETER"});return o},headers:s=>{if(s&&typeof s!="object")throw new c('"headers" should be type: <object>.',{code:"INVALID_PARAMETER"});return r(s),s},data:s=>{if(s&&typeof s!="object")throw new c('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return r(s),s},params:s=>{if(s&&typeof s!="object")throw new c('"params" should be type: <object>.',{code:"INVALID_PARAMETER"});return r(s),s},poll:"boolean",expires:"number",queId:"string"},["clientSecretName","method","url"]),!e)throw new c(`At least one parameter value should include "$CLIENT_SECRET" in ${n.method.toLowerCase()==="post"?'"data"':'"params"'} or "headers".`,{code:"INVALID_PARAMETER"});await this.__connection;let i=!!this.__user;return w.bind(this)("csr",n,{auth:i,tokenHeaders:{accessToken:!!i}}).then(s=>{if(t&&s.id&&s.status==="pending"){let a=`[${n.method.toUpperCase()}]${n.url.toLowerCase()}`+":"+s.id;return rn.call(this,{id:a,auth:i,service:n.service,owner:n.owner,que_id:n.queId,latency:t})}else return s})}async function on(n,e){await this.__connection;let t=!!n.poll,r=typeof n.poll=="number"?n.poll:1e3;n=g.Params(n,{url:"string",method:["GET","POST","DELETE","PUT"],queId:"string"},["url","method"]);let i=!!this.__user,s=`[${n.method.toUpperCase()}]${n.url.toLowerCase()}`;n.queId&&(s+="#"+n.queId),s+=":";let o=await w.bind(this)("csr-poll",{id:s,service:n.service,owner:n.owner},{auth:i,fetchOptions:e}),a=[];return o.list=o.list.map(l=>{let d={id:l.id,status_code:l.rslv?.status_code||null,response_body:l.rslv?.body||l.rslv?.truncated||null,error:l.err,updated:l.utmp,request_body:l.reqbdy,expires:l.stts!=="pending"?l.expt:null,status:l.stts||null};return t&&d.status==="pending"&&typeof d.id=="string"&&a.push(d.id),d}),t&&(o.pending=a.map(l=>rn.call(this,{id:s+l,auth:i,service:n.service,owner:n.owner,latency:r}).then(d=>({...d})).catch(d=>({error:d,id:l})))),o}async function an(n){await this.__connection;let e={name:"string",email:t=>(g.Email(t),t),subject:"string",message:"string"};return n=g.Params(n,e,["name","email","subject","message"]),await w.bind(this)("send-inquiry",n),"SUCCESS: Inquiry has been sent."}async function cn(n,e){if(await this.__connection,Ur&&n instanceof FormData||Nr&&n instanceof HTMLFormElement||Cr&&n instanceof SubmitEvent){if(!e)throw new c("Url string as a second argument is required when form is passed.",{code:"INVALID_PARAMETER"});let r=N(n);n={url:e,data:r.data,sync:true};}let t={url:r=>g.Url(r),data:r=>r,sync:["boolean",()=>true]};if(Array.isArray(n))for(let r of n)r=g.Params(r,t);else n=g.Params(n,t);return w.bind(this)("post-secure",n,{auth:true})}async function ln(n,e){await this.__connection;let{auth:t=false,method:r="POST",bypassAwaitConnection:i=false,responseType:s,contentType:o,tokenHeaders:a,progress:l}=e||{};if(e=Object.assign({auth:t,method:r,bypassAwaitConnection:i,responseType:s,contentType:o,tokenHeaders:a},{fetchOptions:{progress:l}}),typeof n!="object"&&(o==="application/json"||o===void 0))throw new c('"data" should be type: <object>.',{code:"INVALID_PARAMETER"});return w.bind(this)("mock",n,e)}async function un(n,e){await this.__connection,n=g.Params(n||{},{access_group:r=>{if(r==="authorized"&&(r=1),r==="public"&&(r=0),typeof r!="number")throw new c('"access_group" should be type number.',{code:"INVALID_PARAMETER"});if(r<0)throw new c('"access_group" should be zero or a positive number.',{code:"INVALID_PARAMETER"});if(r>this.__user.access_group)throw new c("User has no access.",{code:"INVALID_REQUEST"});return r}});let t=await w.bind(this)("get-feed",n,{auth:true,fetchOptions:e});for(let r in t.list)t.list[r]=await ie.bind(this)(t.list[r]);return t}function fe(n){if(n===this.__user.user_id)throw new c(`"user_id" cannot be the user's own ID.`,{code:"INVALID_PARAMETER"});return g.UserId(n,'"user_id"')}async function dn(n,e){if(n=N(n,{ignoreEmpty:true}).data,n=g.Params(n,{subscriber:r=>g.UserId(r,'User ID in "subscriber"'),subscription:fe.bind(this),blocked:"boolean"}),!n.subscriber&&!n.subscription)throw new c('At least either "subscriber" or "subscription" should have a value.',{code:"INVALID_PARAMETER"});let t=await w.bind(this)("get-subscription",n,Object.assign({auth:true},{fetchOptions:e}));return t.list=t.list.map((r=>{let i={};if(r.sub){let s=r.sub.split("#");i.subscriber=s[2],i.subscription=s[0];}else i.subscriber=r.subscriber,i.subscription=r.subscription;return i.timestamp=r?.timestamp||r.stmp,i.blocked=r?.blocked||r.grp.substring(0,1)==="N",Object.assign(i,r.opt),i})),t}async function gn(n){await this.__connection,n=g.Params(n,{user_id:fe.bind(this),get_feed:["boolean",()=>false],get_notified:["boolean",()=>false],get_email:r=>{if(r&&!this.__user.email||!this.__user.email_verified)throw new c("User has no verified email address.",{code:"INVALID_REQUEST"});return !!r}},["user_id"]);let e=await w.bind(this)("subscription",{subscribe:n.user_id,option:{get_feed:n.get_feed,get_notified:n.get_notified,get_email:n.get_email||false}},{auth:true}),t={};if(e.sub){let r=e.sub.split("#");t.subscriber=r[2],t.subscription=r[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 fn(n){await this.__connection;let{user_id:e}=g.Params(n,{user_id:fe.bind(this)},["user_id"]);return await w.bind(this)("subscription",{unsubscribe:e},{auth:true})}async function hn(n){await this.__connection;let{user_id:e}=g.Params(n,{user_id:fe.bind(this)},["user_id"]);return await w.bind(this)("subscription",{block:e},{auth:true})}async function pn(n){await this.__connection;let{user_id:e}=g.Params(n,{user_id:fe.bind(this)},["user_id"]);return await w.bind(this)("subscription",{unblock:e},{auth:true})}async function mn(n,e){await this.__connection;let t=await M.bind(this)();n=g.Params(n,{user_id:o=>{if(o!==this.__user.user_id&&!t)throw new c("No access.",{code:"INVALID_REQUEST"});return o},group:o=>{if(o==="public"&&(o=0),o==="authorized"&&(o=1),typeof o!="number")throw new c('"group" should be type number | "public" | "authorized".',{code:"INVALID_PARAMETER"});return o}});let r=await w.bind(this)("get-newsletter-subscription",n,{auth:true,fetchOptions:e||null}),i=r?.list||r,s=[];Array.isArray(i)||(i=[]);for(let o of i){let a=o.subt.split("#"),l=true;a[0].charAt(0)==="@"&&(l=false,a[0]=a[0].substring(1));let d=parseInt(a[0]);s.push({timestamp:o.stmp,group:d,subscribed_email:a[1],active:l});}return r?.list?(r.list=s,r):s}async function _n(n){await this.__connection;let e=g.Params(n||{},{email:t=>Array.isArray(t)&&t.length>0?t.length===1?g.Email(t[0]):t.map(r=>g.Email(r)):g.Email(t),group:["number","public","authorized","admin",t=>{if(typeof t!="string"||t.length>20||!/^[a-zA-Z0-9]+$/.test(t))throw new c('"group" should be an alphanumeric string without spaces and less than 20 characters.',{code:"INVALID_PARAMETER"});return t}],redirect:t=>g.Url(t)},this.__user?["group"]:["email","group"]);return w.bind(this)(`subscribe-${this.__user?"":"public-"}newsletter`,e,{auth:!!this.__user})}async function bn(n){await this.__connection,n=g.Params(n,{group:["number","public","authorized","admin"]},["group"]);let e=Object.assign({action:"unsubscribe"},n);return w.bind(this)("subscribe-newsletter",e,{auth:true})}async function yn(n,e){let t=await M.bind(this)(),r={message_id:"string",timestamp:"number",read:"number",complaint:"number",subject:"string",bounced:"number"};n||(e=Object.assign({ascending:false},e||{})),n=N(n).data,n=n||{searchFor:"timestamp",value:Date.now(),condition:"<",group:"public"},n=g.Params(n,{searchFor:["message_id","timestamp","subject","complaint","read","bounced"],value:l=>{if(typeof l!==r[n.searchFor])throw new c(`"value" type does not match the type of "${n.searchFor}" index.`,{code:"INVALID_PARAMETER"});if(typeof l=="string"&&!l)throw new c('"value" should not be empty string.',{code:"INVALID_PARAMETER"});return l},range:l=>{if(!n.hasOwnProperty("value")||typeof l!=typeof n.value)throw new c('"range" should match type of "value".',{code:"INVALID_PARAMETER"});return l},condition:[">",">=","=","<","<=","gt","gte","eq","lt","lte",()=>"="],group:l=>{if(l==="public")return 0;if(!this.session)throw new c("User should be logged in.",{code:"INVALID_REQUEST"});if(l==="authorized")return 1;if(typeof l=="number"){if(!t&&l>parseInt(this.user?.access_group||this.session?.idToken?.payload?.access_group))throw new c("User has no access.",{code:"INVALID_REQUEST"});return l}throw new c('"group" should be type: number | "public" | "authorized".',{code:"INVALID_PARAMETER"})}},["searchFor","value","group"]);let i=n.group===0?"get-public-newsletters":"get-newsletters",s=await w.bind(this)(i,n,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(l=>{let d={};for(let h in o)d[h]=l[o[h]]||a[h];return d.bounced=String(d.bounced),d}),s}async function wn(n){let e=g.Params(n,{user_id:r=>g.UserId(r,'"user_id"')},["user_id"]);if(e?.service&&e?.owner?e={service:e?.service,owner:e?.owner,block:e.user_id}:e={block:e.user_id},!await M.bind(this)()){if(!this.__user)throw new c("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new c("Invalid access.",{code:"INVALID_REQUEST"})}return await w.bind(this)("block-account",e,{auth:true})}async function En(n){let e=g.Params(n,{user_id:r=>g.UserId(r,'"user_id"')},["user_id"]);if(e?.service&&e?.owner?e={service:e?.service,owner:e?.owner,unblock:e.user_id}:e={unblock:e.user_id},!await M.bind(this)()){if(!this.__user)throw new c("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new c("Invalid access.",{code:"INVALID_REQUEST"})}return await w.bind(this)("block-account",e,{auth:true})}async function Rn(n){let e=g.Params(n,{user_id:r=>g.UserId(r,'"user_id"')},["user_id"]);if(e?.service&&e?.owner?e={service:e?.service,owner:e?.owner,delete:e.user_id}:e={delete:e.user_id},!await M.bind(this)()){if(!this.__user)throw new c("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new c("Invalid access.",{code:"INVALID_REQUEST"})}return await w.bind(this)("remove-account",e,{auth:true})}async function An(n,e){let t={email:s=>g.Email(s),password:s=>g.Password(s),name:"string",username:"string",gender:"string",address:s=>{if(!s)return "";if(typeof s=="string")return s;if(typeof s=="object")return JSON.stringify(s)},birthdate:s=>g.Birthdate(s),phone_number:s=>g.PhoneNumber(s),picture:s=>{if(s)return g.Url(s)},profile:s=>{if(s)return g.Url(s)},website:s=>{if(s)return g.Url(s)},nickname:"string",misc:"string",email_public:["boolean",()=>false],gender_public:["boolean",()=>false],address_public:["boolean",()=>false],birthdate_public:["boolean",()=>false],phone_number_public:["boolean",()=>false],openid_id:"string",access_group:s=>{try{typeof s=="string"&&(s=s==="admin"?99:parseInt(s));}catch{throw new c('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof s!="number"||s<1||s>100)throw new c('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"});return s}},r=g.Params(n,t,["email"]);if(e=g.Params(e,{confirmation_url:s=>{let o=s;if(typeof s=="string")o=g.Url(s);else throw new c('"options.confirmation_url" should be type: <string>.',{code:"INVALID_PARAMETER"});if(o&&!r.email)throw new c('"email" is required for signup confirmation.',{code:"INVALID_PARAMETER"});return o},email_subscription:s=>{if(typeof s!="boolean")throw new c('"options.email_subscription" should be type: <boolean>.',{code:"INVALID_PARAMETER"});if(!e?.confirmation_url)throw new c('"options.confirmation_url" is required for email subscription.',{code:"INVALID_PARAMETER"});return s},template:s=>{if(typeof s!="object"||!s.url||!s.subject)throw new c('"options.template" should be type: <object> with "url" and "subject".',{code:"INVALID_PARAMETER"});return {url:g.Url(s.url),subject:s.subject}}}),r.signup_confirmation=e?.confirmation_url||true,r.email_subscription=e?.email_subscription||false,r.template=e?.template||{},!await M.bind(this)()){if(!this.__user)throw new c("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new c("Invalid access.",{code:"INVALID_REQUEST"})}return await w.bind(this)("admin-signup",r,{auth:true})}async function In(n){let e={email:i=>g.Email(i),password:i=>g.Password(i),openid_id:"string",name:"string",username:"string",gender:"string",address:i=>{if(!i)return "";if(typeof i=="string")return i;if(typeof i=="object")return JSON.stringify(i)},birthdate:i=>g.Birthdate(i),phone_number:i=>g.PhoneNumber(i),picture:i=>i?g.Url(i):"",profile:i=>i?g.Url(i):"",website:i=>i?g.Url(i):"",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:i=>{try{typeof i=="string"&&(i=parseInt(i));}catch{throw new c('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof i!="number"||i<1||i>100)throw new c('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"});return i}},t=g.Params(n,e,["email","password"]);if(!await M.bind(this)()){if(!this.__user)throw new c("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new c("Invalid access.",{code:"INVALID_REQUEST"})}return await w.bind(this)("admin-signup",t,{auth:true})}async function Tn(n){if(n=g.Params(n,{user_id:t=>g.UserId(t,'"user_id"'),access_group:t=>{try{typeof t=="string"&&(t=parseInt(t));}catch{throw new c('"access_group" is invalid. Should be type <number>.',{code:"INVALID_PARAMETER"})}if(typeof t=="number"&&t>0&&t<100)return t;throw new c('"access_group" is invalid. Should be type <number> of range 1~99',{code:"INVALID_PARAMETER"})}},["user_id","access_group"]),!await M.bind(this)()){if(!this.__user)throw new c("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new c("Invalid access.",{code:"INVALID_REQUEST"})}return await w.bind(this)("grant-access",n,{auth:true})}async function Pn(n,e){if(n=g.Params(n,{email:"string"}),!await M.bind(this)()){if(!this.__user)throw new c("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new c("Invalid access.",{code:"INVALID_REQUEST"})}let r=await w.bind(this)("invitation-list",Object.assign({mode:"search"},n),{fetchOptions:e,auth:true});return r.list=r.list.map(i=>ae(i.user)),r}async function Sn(n){if(n=g.Params(n,{email:t=>g.Email(t)},["email"]),!await M.bind(this)()){if(!this.__user)throw new c("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new c("Invalid access.",{code:"INVALID_REQUEST"})}return await w.bind(this)("invitation-list",Object.assign({mode:"cancel"},n),{auth:true})}async function kn(n){if(n=g.Params(n,{email:t=>g.Email(t)},["email"]),!await M.bind(this)()){if(!this.__user)throw new c("User needs to login.",{code:"INVALID_REQUEST"});if(this.__user.access_group<90)throw new c("Invalid access.",{code:"INVALID_REQUEST"})}return await w.bind(this)("invitation-list",Object.assign({mode:"resend"},n),{auth:true})}async function xn(n){if(typeof window>"u"||window._runningInNodeJS)throw new c("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.__connection,!n.endpoint)throw new c("Missing parameter: endpoint",{code:"INVALID_PARAMETER"});if(!n.keys||!n.keys.p256dh||!n.keys.auth)throw new c("Missing parameter: keys.p256dh or keys.auth",{code:"INVALID_PARAMETER"});return await w.bind(this)("store-subscription",{endpoint:n.endpoint,keys:n.keys},{auth:true}),"SUCCESS: Subscribed to receive notifications."}async function vn(n){if(typeof window>"u"||window._runningInNodeJS)throw new c("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});if(await this.__connection,!n.endpoint)throw new c("Missing parameter: endpoint",{code:"INVALID_PARAMETER"});if(!n.keys||!n.keys.p256dh||!n.keys.auth)throw new c("Missing parameter: keys.p256dh or keys.auth",{code:"INVALID_PARAMETER"});return await w.bind(this)("delete-subscription",{endpoint:n.endpoint,keys:n.keys},{auth:true}),"SUCCESS: Unsubscribed from notifications."}async function Dn(){if(typeof window>"u"||window._runningInNodeJS)throw new c("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});return await this.__connection,{VAPIDPublicKey:await w.bind(this)("get-vapid-public-key",null,{auth:true})}}async function Un(n,e){if(typeof window>"u"||window._runningInNodeJS)throw new c("Push Notifications are not supported in Node.js environment.",{code:"NOT_SUPPORTED"});await this.__connection;let{title:t,body:r}=N(n||{},{nullIfEmpty:true}).data;if(!t)throw new c("Missing parameter: message title",{code:"INVALID_PARAMETER"});if(!r)throw new c("Missing parameter: message body",{code:"INVALID_PARAMETER"});let i={title:t,body:r};return e?(typeof e=="string"&&(e=[e]),i.user_ids=e):i.user_ids="all_users",await w.bind(this)("push-notification",i,{auth:true}),"SUCCESS: Notification sent."}async function Nn(n){await this.__connection,n=g.Params(n,{spell:"string",name:"string",magic:t=>t},["spell","name"]);await w.bind(this)("castspell",n);return `The spell "${n.spell}" has been cast.`}async function Cn(n){return await this.__connection,n=g.Params(n||{},{search:["spell","name",()=>"spell"],value:"string"}),await w.bind(this)("getspell",n)}async function Ln(n){await this.__connection,n=g.Params(n,{message:"string",name:"string"},["message","name"]);let e=await w.bind(this)("dopamine",n,{auth:true}),t=e?.previous_message?.message,r=e?.previous_message?.name;if($())t&&r&&window.alert(`${r} said: ${t}`),window.location.href=e.video;else return t&&r?`${r} said: ${t}
|
|
216
216
|
Watch the video here: ${e.video}`:`Your message has been uploaded for future generations to receive.
|
|
217
|
-
Watch the video here: ${e.video}`}var b=class{constructor(e,t,r,i){this.__version="1.5.
|
|
217
|
+
Watch the video here: ${e.video}`}var b=class{constructor(e,t,r,i){this.__version="1.5.4-beta.0";this.session=null;this.connection=null;this.__my_unique_ids={};this.userPool=null;this.__socket=null;this.__mediaStream=null;this.host="skapi";this.hostDomain="skapi.com";this.target_cdn="d3e9syvbtso631";this.customApiDomain="skapi.dev";this.requestBatchSize=30;this.__disabledAccount=null;this.__cached_requests={};this.__startKeyHistory={};this.__request_signup_confirmation=null;this.__private_access_key={};this.__class_properties_has_been_cached=false;this.__user=null;this._userProfileListeners=[];this._onLoginListeners=[];this._onBatchProcessListeners=[];this.validate={userId(e){try{return g.UserId(e),!0}catch{return false}},url(e){try{return g.Url(e),!0}catch{return false}},phoneNumber(e){try{return g.PhoneNumber(e),!0}catch{return false}},birthdate(e){try{return g.Birthdate(e),!0}catch{return false}},email(e){try{return g.Email(e),!0}catch{return false}},params(e,t,r){return g.Params(e,t,r)}};this.util={MD5:V,generateRandom:oe,toBase62:Xe,fromBase62:j,decodeServiceId:Ue,formatServiceId:Ze,extractFormData:N,terminatePendingRequests:Tt,request:(e,t,r)=>w.bind(this)(e,t,r,{ignoreService:true})};this.__network_logs=false;this.__endpoint_version="v1";this.__public_identifier="";this.bearerToken="";this.registerTicket=rt.bind(this);this.unregisterTicket=it.bind(this);if(!e||typeof e!="string")throw this._alert("Service ID is required."),new c("Service ID is required.",{code:"INVALID_PARAMETER"});let s=e.split("-").length;if(s===2||s===7)try{let f=Ue(e);r&&typeof r=="object"&&(i=r),t&&typeof t=="object"&&(r=t),t=f.owner,e=f.service;}catch{throw this._alert("Service ID is invalid."),new c("Service ID is invalid.",{code:"INVALID_PARAMETER"})}if(!t||typeof t!="string")throw this._alert("Owner ID is invalid."),new c("Owner ID is invalid.",{code:"INVALID_PARAMETER"});if(e.toLowerCase()==="service_id")throw this._alert('Replace "service_id" with your actual Service ID.'),new c("Service ID is required.",{code:"INVALID_PARAMETER"});if(t!==this.host)try{g.UserId(t,'"owner"');}catch{throw this._alert("Owner ID is invalid."),new c("Owner ID is invalid.",{code:"INVALID_PARAMETER"})}this.service=e,this.owner=t;let l=true;if(r&&(typeof r.autoLogin=="boolean"&&(l=r.autoLogin),typeof r.requestBatchSize=="number")){if(r.requestBatchSize<1)throw new c('"requestBatchSize" must be greater than 0.',{code:"INVALID_PARAMETER"});this.requestBatchSize=r.requestBatchSize;}r?.eventListener&&typeof r.eventListener=="object"&&(r.eventListener?.onLogin&&typeof r.eventListener.onLogin=="function"&&(this.onLogin=r.eventListener.onLogin),r.eventListener?.onUserUpdate&&typeof r.eventListener.onUserUpdate=="function"&&(this.onUserUpdate=r.eventListener.onUserUpdate),r.eventListener?.onBatchProcess&&typeof r.eventListener.onBatchProcess=="function"&&(this.onBatchProcess=r.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(f=>f.blob()).then(f=>new Promise((A,P)=>{let _=new FileReader;_.onloadend=()=>A(_.result),_.onerror=P,_.readAsDataURL(f);})).then(f=>{try{return typeof f=="string"?JSON.parse(atob(f.split(",")[1])):null}catch{throw new c("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(f=>f.blob()).then(f=>new Promise((A,P)=>{let _=new FileReader;_.onloadend=()=>A(_.result),_.onerror=P,_.readAsDataURL(f);})).then(f=>{try{return typeof f=="string"?JSON.parse(atob(f.split(",")[1])):null}catch{throw new c("Service does not exist. Create your service from skapi.com",{code:"NOT_EXISTS"})}});let u=$();if(u&&!window.sessionStorage)throw this._alert("This browser is not supported."),new Error("This browser is not supported.");let m=u?JSON.parse(window.sessionStorage.getItem(`${e}#${t}`)||"null"):null;if(this.log("constructor:restore",m),m?.connection){for(let f in m)this[f]=m[f];m.__public_identifier||(this.__public_identifier=`${this.service}:${this.owner}:${oe(16)}`);}this.__authConnection=(async()=>{let f=await this.admin_endpoint,A={UserPoolId:f.userpool_id,ClientId:f.userpool_client};De()&&(A.Storage=window.localStorage),this.userPool=new amazonCognitoIdentityJs.CognitoUserPool(A);try{this.user||await F.bind(this)().getSession({skipUserUpdateEventTrigger:!0}),this.user&&(!m?.connection&&!l?G.bind(this)():(this._runOnLoginListeners(this.user),this._runOnUserUpdateListeners(this.user)));}catch{}})();let R=u?window.sessionStorage.getItem(`${this.service}:uniqueids`):null;if(R)try{this.__my_unique_ids=JSON.parse(R);}catch{this.__my_unique_ids={};}this.__connection=(async()=>{let f=null;await this.record_endpoint,m?.connection||(f=this._updateConnection());let A=()=>{if(this.__class_properties_has_been_cached)return;let P=()=>{let _={},x=["__startKeyHistory","__disabledAccount","__cached_requests","__request_signup_confirmation","__public_identifier","connection"];if(this.connection){for(let k of x)_[k]=this[k];u&&window.sessionStorage.setItem(`${e}#${t}`,JSON.stringify(_)),this.__class_properties_has_been_cached=true;}};return f instanceof Promise?f.then(()=>P()):P()};return u&&(window.addEventListener("beforeunload",()=>{this.closeRealtime(),A();}),window.addEventListener("visibilitychange",()=>{A();})),await f,await this.__authConnection,this.connection})(),this.__connection.then(f=>{((f?.group||0)<3||this.__network_logs)&&this.version();});}get user(){return this.__user&&Object.keys(this.__user).length?JSON.parse(JSON.stringify(this.__user)):null}set user(e){}get onLogin(){return this._onLoginListeners}set onLogin(e){typeof e=="function"&&this._onLoginListeners.push(e);}get onUserUpdate(){return this._userProfileListeners}set onUserUpdate(e){typeof e=="function"&&this._userProfileListeners.push(e);}_runOnUserUpdateListeners(e){for(let t of this._userProfileListeners)typeof t=="function"&&t(e);}_runOnLoginListeners(e){for(let t of this._onLoginListeners)typeof t=="function"&&t(e);}get onBatchProcess(){return this._onBatchProcessListeners}set onBatchProcess(e){typeof e=="function"&&this._onBatchProcessListeners.push(e);}_alert(e){$()&&typeof window.alert=="function"&&window.alert(e);}async getConnectionInfo(){let e=await this.__connection,t=e?.user_agent||($()&&typeof window.navigator?.userAgent=="string"?window.navigator.userAgent:`skapi-node/${globalThis?.process?.versions?.node||"unknown"}`);return {user_ip:e.ip,user_agent:t,user_location:e.locale,service_name:e.service_name,version:this.__version}}async _updateConnection(){try{this.connection=await w.bind(this)("service",{service:this.service,owner:this.owner},{bypassAwaitConnection:!0,method:"get"});}catch(e){throw this.log("connection fail",e),this._alert("Service is not available: "+(e.message||e.toString())),this.connection=null,e}return this.connection}async version(){if(await this.__connection,$()){let t=`Built with:
|
|
218
218
|
%c\r
|
|
219
219
|
$$\\ $$\\ \r
|
|
220
220
|
$$ | \\__|\r
|