@wellesley/ws 1.0.95 → 1.0.112

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.
Files changed (2) hide show
  1. package/index.mjs +3 -12
  2. package/package.json +1 -1
package/index.mjs CHANGED
@@ -1,13 +1,4 @@
1
- import J,{useEffect as w,useState as k,useRef as V}from"https://cdn.jsdelivr.net/npm/react@18.2.0/+esm";import{useSelector as S,useDispatch as C}from"https://cdn.jsdelivr.net/npm/react-redux@9.1.0/+esm";import{createSelector as R,createSlice as I}from"https://cdn.jsdelivr.net/npm/@reduxjs/toolkit@2.2.1/+esm";import{rootReducer as H}from"https://cdn.jsdelivr.net/npm/@wellesley/store@1.0.146";import{userSlice as z,useCurrentUser as Y}from"https://cdn.jsdelivr.net/npm/@wellesley/user@1.0.141";import{api as K,handleBasicResponse as p}from"https://cdn.jsdelivr.net/npm/@wellesley/openapi@1.0.140";import{getErrorMsg as m}from"https://cdn.jsdelivr.net/npm/@wellesley/error-kit@1.0.6";import{toast as l}from"https://cdn.jsdelivr.net/npm/react-toastify@10.0.5/+esm";import{notificationsSlice as x,isUndoNotification as X,notify as Z,NotificationBody as ee}from"https://cdn.jsdelivr.net/npm/@wellesley/notifications@1.0.32";import{useProfileSettings as te,UserKeysSettings as se}from"https://cdn.jsdelivr.net/npm/@wellesley/settings@1.0.73";import{logErrorToSentry as re}from"https://cdn.jsdelivr.net/npm/@wellesley/sentry@1.0.13";import{authSlice as ne}from"https://cdn.jsdelivr.net/npm/@wellesley/auth@1.0.182";const oe=(e,t)=>Object.keys(t).reduce(((e,s)=>e.replace(`$${s}`,t[s])),e),F={messages:[],subscribers:[],unsubscribers:[]},L=e=>e,ie=R(L,(e=>e.subscribers)),ae=R(L,(e=>e.unsubscribers)),ce=R(L,(e=>e.messages)),ue=R([L,(e,t)=>t],((e,t)=>{var s;return null==(s=e.messages)?void 0:s.find((({topic:e})=>e===t))})),_=I({name:"ws",initialState:F,reducers:{subscribe:(e,{payload:t})=>{!e.subscribers.find((e=>e.id===t.id))&&e.subscribers.push(t)},onMessage:(e,{payload:t})=>{e.messages=[t,...e.messages.slice(0,100)]},cleanMessages:e=>{e.messages=F.messages},unsubscribe:(e,{payload:t})=>{const s=e.subscribers.find((e=>e.id===t));s&&e.unsubscribers.push(s)},onUnsubscribe:(e,{payload:t})=>{e.subscribers=e.subscribers.filter((e=>e.id!==t)),e.unsubscribers=e.unsubscribers.filter((e=>e.id!==t))}},selectors:{selectMessages:ce,selectSubscribers:ie,selectUnSubscribers:ae,selectLastUpdateFor:ue}}).injectInto(H),le=e=>`@${e.username}${e.domain?`@${e.domain}`:""}`,M={data:null,isError:!1,isPending:!1,isSuccess:!1},v=I({name:"user",initialState:M,reducers:{reset:e=>{Object.assign(e,M)},setData:(e,{payload:t})=>{e.data=t},updateData:(e,{payload:t})=>{e.data&&Object.assign(e.data,t)},setSuccess:(e,{payload:t})=>{e.isSuccess=t},setPending:(e,{payload:t})=>{e.isPending=t},setIsError:(e,{payload:t})=>{e.isError=t},setError:(e,{payload:t})=>{e.error=t},updateUser:(e,{payload:t})=>{var s;null!=(s=e.data)&&s.users&&(e.data.users=e.data.users.map((e=>t.id===e.id?t:e)))}},selectors:{selectIsError:e=>e.isError,selectError:e=>e.error,selectPending:e=>e.isPending,selectData:e=>e.data,selectAccount:e=>{var t;return null==(t=e.data)?void 0:t.account},selectUsers:e=>{var t;return null==(t=e.data)?void 0:t.users},selectUserById:(e,t)=>{var s;return null==(s=e.data)?void 0:s.users.find((({id:e})=>e===t))},selectCurrentUser:e=>{var t;return null==(t=e.data)?void 0:t.users.find((({id:t})=>{var s;return t===(null==(s=e.data)?void 0:s.selectedUserId)}))},selectSelectedUserId:e=>{var t;return null==(t=e.data)?void 0:t.selectedUserId},selectSuccess:e=>e.isSuccess,selectIsAdmin:e=>{var t;return"ADMIN"===(null==(t=e.data)?void 0:t.account.role)}}}),de={data:null,isPending:!1,isSuccess:!1},U=I({name:"userNoHTML",initialState:de,reducers:{setUser:(e,t)=>{e.data=t.payload},setPending:(e,t)=>{e.isPending=t.payload},setSuccess:(e,{payload:t})=>{e.isSuccess=t},setError:(e,{payload:t})=>{e.error=t}},selectors:{selectUser:e=>e.data,selectPending:e=>e.isPending,selectError:e=>e.error,selectSuccess:e=>e.isSuccess}}),fe=K.enhanceEndpoints({endpoints:{deleteApiV1UsersByUserIdDelete:{async onQueryStarted(e,{queryFulfilled:t}){await p(t)}},getApiV1AccountsProfile:{providesTags:["Secure","Account"],async onQueryStarted(e,{dispatch:t,queryFulfilled:s}){t(v.actions.setPending(!0));try{const e=await p(s);e&&t(v.actions.setData(e.data)),t(v.actions.setSuccess(!0))}catch(e){t(v.actions.setSuccess(!1)),t(v.actions.setIsError(!0)),t(v.actions.setError(e))}finally{t(v.actions.setPending(!1))}}},putApiV1UsersByUserId:{async onQueryStarted(e,{queryFulfilled:t}){await p(t,"User updated succesfully")}},getApiV1Users:{providesTags:["Secure","UserNoHtml"],async onQueryStarted(e,{dispatch:t,queryFulfilled:s}){const r=!e.htmlContent;try{r&&t(U.actions.setPending(!0));const e=await p(s);r&&e&&(t(U.actions.setUser(e.data)),t(U.actions.setSuccess(!0)),t(U.actions.setPending(!1)))}catch(e){r&&(t(U.actions.setSuccess(!1)),t(U.actions.setError(e)),t(U.actions.setPending(!1))),l.error(m(e))}}},postApiV1Users:{invalidatesTags:["Account"],async onQueryStarted(e,{queryFulfilled:t}){try{await t,l.success("User created successfully")}catch(e){const t=e;l.error(409===(null==t?void 0:t.status)?"Username already exists":m(t))}}},getApiV1UsersFollowers:{providesTags:["Follow"],async onQueryStarted(e,{queryFulfilled:t}){await p(t)}},getApiV1UsersByUserIdFollowers:{providesTags:["Follow"],async onQueryStarted(e,{queryFulfilled:t}){await p(t)}},getApiV1UsersFollowees:{providesTags:["Follow"],async onQueryStarted(e,{queryFulfilled:t}){await p(t)}},getApiV1UsersByUserIdFollowing:{providesTags:["Follow"],async onQueryStarted(e,{queryFulfilled:t}){await p(t)}},postApiV1UsersFollowByUsernameAccept:{invalidatesTags:["Follow","Relationship"],async onQueryStarted(e,{queryFulfilled:t}){try{await t,l.success(`Accepted follow request from ${e.username}`)}catch(e){l.error(m(e))}}},postApiV1UsersFollowByUsernameReject:{invalidatesTags:["Follow","Secure","Relationship"],async onQueryStarted(e,{queryFulfilled:t}){try{await t,l.success(`Rejected follow request from ${e.username}`)}catch(e){l.error(m(e))}}},postApiV1UsersFollowByUsername:{invalidatesTags:["Follow","Secure","Relationship"],async onQueryStarted(e,{queryFulfilled:t}){try{await t,l.success(`Follow request sent to ${e.username}`)}catch(e){l.error(m(e))}}},postApiV1UsersFollowByUsernameUndo:{invalidatesTags:["Follow","Secure","Relationship"],async onQueryStarted(e,{queryFulfilled:t}){try{await t,l.success(`You unfollowed ${e.username}`)}catch(e){l.error(m(e))}}},getApiV1Block:{providesTags:["Follow"]},postApiV1BlockByUserId:{invalidatesTags:["Follow","Relationship"],async onQueryStarted(e,{queryFulfilled:t}){await p(t)}},deleteApiV1BlockByUserId:{invalidatesTags:["Follow","Relationship"],async onQueryStarted(e,{queryFulfilled:t}){await p(t)}},deleteApiV1AccountsDelete:{},postApiV1MuteByUserId:{invalidatesTags:["Relationship"],async onQueryStarted(e,{queryFulfilled:t}){await p(t)}},deleteApiV1MuteByUserId:{invalidatesTags:["Relationship"],async onQueryStarted(e,{queryFulfilled:t}){await p(t)}},getApiV1Mute:{async onQueryStarted(e,{queryFulfilled:t}){await p(t)}},getApiV1UsersRelationships:{providesTags:["Relationship"],async onQueryStarted(e,{queryFulfilled:t}){await p(t)}},putApiV1UsersByUserIdState:{invalidatesTags:["Secure"],async onQueryStarted(e,{queryFulfilled:t}){try{await p(t),l.success(`User ${e.userId} state changed to ${e.userState}`)}catch(e){l.error(m(e))}}},putApiV1Notes:{async onQueryStarted(e,{queryFulfilled:t}){try{await p(t),l.success("Note has been updated")}catch(e){l.error(m(e))}}},deleteApiV1NotesByUserId:{async onQueryStarted(e,{queryFulfilled:t}){try{await p(t),l.success("Note has been removed")}catch(e){l.error(m(e))}}},postApiV1UsersFollowByUsernamePend:{async onQueryStarted(e,{queryFulfilled:t}){try{await p(t),l.success(`${e.username} has been removed from followers`)}catch(e){l.error(m(e))}}}}}).injectEndpoints({endpoints:e=>({getInteractionUrl:e.query({query:e=>({url:e,headers:{Accept:"application/activity+json"}}),transformResponse:e=>"string"==typeof e?JSON.parse(e):e})})}),{useGetInteractionUrlQuery:Ge,usePostApiV1UsersMutation:qe,useDeleteApiV1AccountsDeleteMutation:Je,useGetApiV1AccountsProfileQuery:He,usePutApiV1UsersByUserIdMutation:ze,useGetApiV1UsersQuery:Ye,useDeleteApiV1UsersByUserIdDeleteMutation:Ke,usePostApiV1MuteByUserIdMutation:Xe,useDeleteApiV1MuteByUserIdMutation:Ze,useGetApiV1MuteQuery:et,usePutApiV1UsersByUserIdStateMutation:tt,useGetApiV1UsersRelationshipsQuery:pe,usePutApiV1NotesMutation:st,useDeleteApiV1NotesByUserIdMutation:rt,useLazyGetApiV1UsersRelationshipsQuery:he,useLazyGetApiV1GeoQuery:nt,useGetApiV1UsersFollowersQuery:ot,useGetApiV1UsersByUserIdFollowersQuery:it,usePostApiV1UsersFollowByUsernameMutation:at,usePostApiV1UsersFollowByUsernameUndoMutation:ct,usePostApiV1UsersFollowByUsernameRejectMutation:ut,usePostApiV1UsersFollowByUsernameAcceptMutation:lt}=fe,D=["following","followed","blocked","muted","note","blocked_by"],B=({userId:e,currentUserId:t})=>{const s="string"==typeof e,r=s?[e]:(null==e?void 0:e.filter((e=>e!==t)))||[],n=e===t;return{isSingleUser:s,canFetch:!(!r.length||n||!t),safeTargets:r}},ye=({userId:e})=>{const t=S(v.selectors.selectCurrentUser),s=null==t?void 0:t.id,{canFetch:r,isSingleUser:n,safeTargets:o}=B({userId:e,currentUserId:s}),{data:i,isLoading:a}=pe({targets:o,filter:D},{skip:!r}),[c]=he();return{relationship:(n?null==i?void 0:i[e]:i)||{},isLoading:a,updateRelations:({userId:e})=>{const{canFetch:t,safeTargets:r}=B({userId:e,currentUserId:s});t&&c({targets:r,filter:D})}}},dt=({user:e,onUpdate:t})=>{const s=C(),{updateRelations:r}=ye({}),n=S(z.selectors.selectCurrentUser),o=(null==n?void 0:n.username)===(null==e?void 0:e.username),i=oe("user:$username",{username:e?le(e).slice(1):""}),a=S((e=>_.selectors.selectLastUpdateFor(e,i)));w((()=>{if(null==e||!e.username)return;const t=!o;return s(_.actions.subscribe({id:i,topics:[i]})),t?()=>{s(_.actions.unsubscribe(i))}:void 0}),[null==e?void 0:e.username,o]),w((()=>{const e=null==a?void 0:a.data;e&&"string"!=typeof e&&(!o&&r({userId:e.id}),t(e))}),[null==a?void 0:a.data,o])};var Q,j,N={exports:{}},T={};
2
- /**
3
- * @license React
4
- * react-jsx-runtime.production.min.js
5
- *
6
- * Copyright (c) Facebook, Inc. and its affiliates.
7
- *
8
- * This source code is licensed under the MIT license found in the
9
- * LICENSE file in the root directory of this source tree.
10
- */function ge(){if(Q)return T;Q=1;var e=J,t=Symbol.for("react.element"),s=Symbol.for("react.fragment"),r=Object.prototype.hasOwnProperty,n=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,o={key:!0,ref:!0,__self:!0,__source:!0};function i(e,s,i){var a,c={},l=null,u=null;for(a in void 0!==i&&(l=""+i),void 0!==s.key&&(l=""+s.key),void 0!==s.ref&&(u=s.ref),s)r.call(s,a)&&!o.hasOwnProperty(a)&&(c[a]=s[a]);if(e&&e.defaultProps)for(a in s=e.defaultProps)void 0===c[a]&&(c[a]=s[a]);return{$$typeof:t,type:e,key:l,ref:u,props:c,_owner:n.current}}return T.Fragment=s,T.jsx=i,T.jsxs=i,T}function me(){return j||(j=1,N.exports=ge()),N.exports}var _e=me();const $="notification",be=e=>"true"===e,ft=()=>{const e=C(),t=te(),s=be(null==t?void 0:t.notifications.stranger[se.notificationsShowPopup].value),r=S(x.selectors.selectNotifications),{user:n}=Y(),o=`${$}:${null==n?void 0:n.id}`,i=S((e=>_.selectors.selectLastUpdateFor(e,o)));w((()=>{if(null!=n&&n.id)return e(_.actions.subscribe({id:o,topics:[$]})),()=>{e(_.actions.unsubscribe(o))}}),[null==n?void 0:n.id]),w((()=>{null!=i&&i.data&&(X(i)?e(x.actions.undoNotitication(i.data)):"LIKE"===(null==i?void 0:i.data.type)&&null!=r&&r.find((e=>{var t,s;return e.activityId===(null==i?void 0:i.data.activityId)&&(null==(t=e.fromUser)?void 0:t.id)===(null==(s=i.data.fromUser)?void 0:s.id)}))||null!=r&&r.find((e=>e.id===i.data.id))||(e(x.actions.addNotification(i.data)),s&&Z(_e.jsx(ee,{notification:i.data,isPopup:!0}),{})))}),[null==i?void 0:i.data,s])},we=()=>"object"!=typeof window,W=["debug","info","warn","error"],ve=(e,t)=>{const s=W.indexOf(e);return W.indexOf(t)>=s},A=(e,t,s,...r)=>{ve(t,e)&&console.log(`[${e}] ${s}`,...r)},Se=()=>null==window?void 0:window.localStorage.getItem("logger_lvl"),Ue=(e=!we()&&Se()||"warn")=>{let t=e;return{debug:(e,...s)=>A("debug",t,e,...s),info:(e,...s)=>A("info",t,e,...s),warn:(e,...s)=>A("warn",t,e,...s),error:(e,...s)=>(re(e,...s),A("error",t,e,...s)),setLevel:e=>{t=e},getLevel:()=>t}},g=Ue(),Ee=e=>{switch(e.code){case 1e3:return"Normal closure, meaning that the purpose for which the connection was established has been fulfilled.";case 1001:return"An endpoint is 'going away', such as a server going down or a browser having navigated away from a page.";case 1002:return"An endpoint is terminating the connection due to a protocol error.";case 1003:return"An endpoint is terminating the connection because it has received a type of data it cannot accept (e.g., an endpoint that understands only text data MAY send this if it receives a binary message).";case 1004:return"Reserved. The specific meaning might be defined in the future.";case 1005:return"No status code was actually present.";case 1006:return"The connection was closed abnormally, e.g., without sending or receiving a Close control frame.";case 1007:return"An endpoint is terminating the connection because it has received data within a message that was not consistent with the type of the message (e.g., non-UTF-8 data within a text message).";case 1008:return"An endpoint is terminating the connection because it has received a message that 'violates its policy'. This reason is given either if there is no other suitable reason, or if there is a need to hide specific details about the policy.";case 1009:return"An endpoint is terminating the connection because it has received a message that is too big for it to process.";case 1010:return`An endpoint (client) is terminating the connection because it has expected the server to negotiate one or more extension, but the server didn't return them in the response message of the WebSocket handshake. Specifically, the extensions that are needed are: ${e.reason}`;case 1011:return"A server is terminating the connection because it encountered an unexpected condition that prevented it from fulfilling the request.";case 1015:return"The connection was closed due to a failure to perform a TLS handshake (e.g., the server certificate can't be verified).";default:return"Unknown reason."}};
1
+ import{useEffect as d,useRef as y,useState as v}from"https://cdn.jsdelivr.net/npm/react@18.2.0/+esm";import{useDispatch as w,useSelector as g}from"https://cdn.jsdelivr.net/npm/react-redux@9.1.0/+esm";import{createSlice as T}from"https://cdn.jsdelivr.net/npm/@reduxjs/toolkit@2.2.1/+esm";import{rootReducer as C}from"https://cdn.jsdelivr.net/npm/@wellesley/store@1.0.147";import{logErrorToSentry as x}from"https://cdn.jsdelivr.net/npm/@wellesley/sentry@1.0.14";import{authSlice as N}from"https://cdn.jsdelivr.net/npm/@wellesley/auth@1.0.183";const f={messages:[],subscribers:[],unsubscribers:[]},p=T({name:"ws",initialState:f,reducers:{reset:e=>{e.messages=f.messages,e.subscribers=f.subscribers,e.unsubscribers=f.unsubscribers},subscribe:(e,{payload:t})=>{!e.subscribers.find((e=>e.id===t.id))&&e.subscribers.push(t)},onMessage:(e,{payload:t})=>{e.messages=[t,...e.messages.slice(0,100)]},cleanMessages:e=>{e.messages=f.messages},unsubscribe:(e,{payload:t})=>{const n=e.subscribers.find((e=>e.id===t));n&&e.unsubscribers.push(n)},onUnsubscribe:(e,{payload:t})=>{e.subscribers=e.subscribers.filter((e=>e.id!==t)),e.unsubscribers=e.unsubscribers.filter((e=>e.id!==t))}},selectors:{selectMessages:e=>e.messages,selectSubscribers:e=>e.subscribers,selectUnSubscribers:e=>e.unsubscribers,selectLastUpdateFor:(e,t)=>{var n;return null==(n=e.messages)?void 0:n.find((({topic:e})=>e===t))}}}).injectInto(C),R=()=>"object"!=typeof window,m=["debug","info","warn","error"],k=(e,t)=>{const n=m.indexOf(e);return m.indexOf(t)>=n},b=(e,t,n,...r)=>{k(t,e)&&console.log(`[${e}] ${n}`,...r)},D=()=>null==window?void 0:window.localStorage.getItem("logger_lvl"),W=(e=!R()&&D()||"warn")=>{let t=e;return{debug:(e,...n)=>b("debug",t,e,...n),info:(e,...n)=>b("info",t,e,...n),warn:(e,...n)=>b("warn",t,e,...n),error:(e,...n)=>(x(e,...n),b("error",t,e,...n)),setLevel:e=>{t=e},getLevel:()=>t}},a=W(),S=e=>[...new Set(e.flatMap((e=>e.topics)))],P=({isReady:e,socket:t,serverSubscriptions:n})=>{const r=w(),s=g(p.selectors.selectUnSubscribers);d((()=>{var o;if(e&&t){const e=S(s);if(0===e.length)return;try{t.send(JSON.stringify({type:"UNSUBSCRIBE",topics:e})),n.current=null==(o=n.current)?void 0:o.filter((e=>!s.find((t=>t.id===e.id)))),a.debug("WebSocket unsubscribed from: ",e)}catch(e){a.error("WebSocket error when send: ",e)}}s.forEach((e=>{r(p.actions.onUnsubscribe(e.id))}))}),[s,t,e])},I=({isReady:e,socket:t,serverSubscriptions:n})=>{const r=g(p.selectors.selectSubscribers);d((()=>{var s;if(e){a.debug("WebSocket subscribers list: ",r);const e=r.filter((e=>{var t;return!(null!=(t=n.current)&&t.includes(e))})),o=S(e);if(o.length>0)try{null==t||t.send(JSON.stringify({type:"SUBSCRIBE",topics:o})),null==(s=n.current)||s.push(...e),a.debug("WebSocket subscribed to: ",o)}catch(e){a.error("WebSocket error when send: ",e)}}}),[e,r])},U=e=>{switch(e.code){case 1e3:return"Normal closure, meaning that the purpose for which the connection was established has been fulfilled.";case 1001:return"An endpoint is 'going away', such as a server going down or a browser having navigated away from a page.";case 1002:return"An endpoint is terminating the connection due to a protocol error.";case 1003:return"An endpoint is terminating the connection because it has received a type of data it cannot accept (e.g., an endpoint that understands only text data MAY send this if it receives a binary message).";case 1004:return"Reserved. The specific meaning might be defined in the future.";case 1005:return"No status code was actually present.";case 1006:return"The connection was closed abnormally, e.g., without sending or receiving a Close control frame.";case 1007:return"An endpoint is terminating the connection because it has received data within a message that was not consistent with the type of the message (e.g., non-UTF-8 data within a text message).";case 1008:return"An endpoint is terminating the connection because it has received a message that 'violates its policy'. This reason is given either if there is no other suitable reason, or if there is a need to hide specific details about the policy.";case 1009:return"An endpoint is terminating the connection because it has received a message that is too big for it to process.";case 1010:return`An endpoint (client) is terminating the connection because it has expected the server to negotiate one or more extension, but the server didn't return them in the response message of the WebSocket handshake. Specifically, the extensions that are needed are: ${e.reason}`;case 1011:return"A server is terminating the connection because it encountered an unexpected condition that prevented it from fulfilling the request.";case 1015:return"The connection was closed due to a failure to perform a TLS handshake (e.g., the server certificate can't be verified).";default:return"Unknown reason."}},j=({onReady:e,socket:t,serverSubscriptions:n})=>{const r=w();d((()=>{t&&(t.onopen=()=>{n.current=[],e(!0),a.info("Connected to WebSocket server")},t.onmessage=e=>{a.debug("WebSocket receive message: ",JSON.parse(e.data));try{r(p.actions.onMessage({...JSON.parse(e.data),date:(new Date).toISOString()}))}catch(e){a.error("WebSocket:onmessage:parse: ",e)}},t.onclose=t=>{e(!1),a.info("Disconnected from WebSocket server:",U(t))},t.onerror=t=>{e(!1),a.error("WebSocket error:",t)})}),[t])};
11
2
  /*! *****************************************************************************
12
3
  Copyright (c) Microsoft Corporation. All rights reserved.
13
4
  Licensed under the Apache License, Version 2.0 (the "License"); you may not use
@@ -21,10 +12,10 @@ MERCHANTABLITY OR NON-INFRINGEMENT.
21
12
 
22
13
  See the Apache Version 2.0 License for specific language governing permissions
23
14
  and limitations under the License.
24
- ***************************************************************************** */var P=function(e,t){return(P=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var s in t)t.hasOwnProperty(s)&&(e[s]=t[s])})(e,t)};function G(e,t){function s(){this.constructor=e}P(e,t),e.prototype=null===t?Object.create(t):(s.prototype=t.prototype,new s)}function Te(e){var t="function"==typeof Symbol&&e[Symbol.iterator],s=0;return t?t.call(e):{next:function(){return e&&s>=e.length&&(e=void 0),{value:e&&e[s++],done:!e}}}}function Ae(e,t){var s="function"==typeof Symbol&&e[Symbol.iterator];if(!s)return e;var r,n,o=s.call(e),i=[];try{for(;(void 0===t||t-- >0)&&!(r=o.next()).done;)i.push(r.value)}catch(e){n={error:e}}finally{try{r&&!r.done&&(s=o.return)&&s.call(o)}finally{if(n)throw n.error}}return i}function Re(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(Ae(arguments[t]));return e}var q=function(){return function(e,t){this.target=t,this.type=e}}(),Le=function(e){function t(t,s){var r=e.call(this,"error",s)||this;return r.message=t.message,r.error=t,r}return G(t,e),t}(q),Oe=function(e){function t(t,s,r){void 0===t&&(t=1e3),void 0===s&&(s="");var n=e.call(this,"close",r)||this;return n.wasClean=!0,n.code=t,n.reason=s,n}return G(t,e),t}(q),xe=function(){if(typeof WebSocket<"u")return WebSocket},Ne=function(e){return typeof e<"u"&&!!e&&2===e.CLOSING},E={maxReconnectionDelay:1e4,minReconnectionDelay:1e3+4e3*Math.random(),minUptime:5e3,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,maxEnqueuedMessages:1/0,startClosed:!1,debug:!1},Pe=function(){function e(e,t,s){var r=this;void 0===s&&(s={}),this._listeners={error:[],message:[],open:[],close:[]},this._retryCount=-1,this._shouldReconnect=!0,this._connectLock=!1,this._binaryType="blob",this._closeCalled=!1,this._messageQueue=[],this.onclose=null,this.onerror=null,this.onmessage=null,this.onopen=null,this._handleOpen=function(e){r._debug("open event");var t=r._options.minUptime,s=void 0===t?E.minUptime:t;clearTimeout(r._connectTimeout),r._uptimeTimeout=setTimeout((function(){return r._acceptOpen()}),s),r._ws.binaryType=r._binaryType,r._messageQueue.forEach((function(e){return r._ws.send(e)})),r._messageQueue=[],r.onopen&&r.onopen(e),r._listeners.open.forEach((function(t){return r._callEventListener(e,t)}))},this._handleMessage=function(e){r._debug("message event"),r.onmessage&&r.onmessage(e),r._listeners.message.forEach((function(t){return r._callEventListener(e,t)}))},this._handleError=function(e){r._debug("error event",e.message),r._disconnect(void 0,"TIMEOUT"===e.message?"timeout":void 0),r.onerror&&r.onerror(e),r._debug("exec error listeners"),r._listeners.error.forEach((function(t){return r._callEventListener(e,t)})),r._connect()},this._handleClose=function(e){r._debug("close event"),r._clearTimeouts(),r._shouldReconnect&&r._connect(),r.onclose&&r.onclose(e),r._listeners.close.forEach((function(t){return r._callEventListener(e,t)}))},this._url=e,this._protocols=t,this._options=s,this._options.startClosed&&(this._shouldReconnect=!1),this._connect()}return Object.defineProperty(e,"CONNECTING",{get:function(){return 0},enumerable:!0,configurable:!0}),Object.defineProperty(e,"OPEN",{get:function(){return 1},enumerable:!0,configurable:!0}),Object.defineProperty(e,"CLOSING",{get:function(){return 2},enumerable:!0,configurable:!0}),Object.defineProperty(e,"CLOSED",{get:function(){return 3},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"CONNECTING",{get:function(){return e.CONNECTING},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"OPEN",{get:function(){return e.OPEN},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"CLOSING",{get:function(){return e.CLOSING},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"CLOSED",{get:function(){return e.CLOSED},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"binaryType",{get:function(){return this._ws?this._ws.binaryType:this._binaryType},set:function(e){this._binaryType=e,this._ws&&(this._ws.binaryType=e)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"retryCount",{get:function(){return Math.max(this._retryCount,0)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"bufferedAmount",{get:function(){return this._messageQueue.reduce((function(e,t){return"string"==typeof t?e+=t.length:t instanceof Blob?e+=t.size:e+=t.byteLength,e}),0)+(this._ws?this._ws.bufferedAmount:0)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"extensions",{get:function(){return this._ws?this._ws.extensions:""},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"protocol",{get:function(){return this._ws?this._ws.protocol:""},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"readyState",{get:function(){return this._ws?this._ws.readyState:this._options.startClosed?e.CLOSED:e.CONNECTING},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"url",{get:function(){return this._ws?this._ws.url:""},enumerable:!0,configurable:!0}),e.prototype.close=function(e,t){void 0===e&&(e=1e3),this._closeCalled=!0,this._shouldReconnect=!1,this._clearTimeouts(),this._ws?this._ws.readyState!==this.CLOSED?this._ws.close(e,t):this._debug("close: already closed"):this._debug("close enqueued: no ws instance")},e.prototype.reconnect=function(e,t){this._shouldReconnect=!0,this._closeCalled=!1,this._retryCount=-1,this._ws&&this._ws.readyState!==this.CLOSED?(this._disconnect(e,t),this._connect()):this._connect()},e.prototype.send=function(e){if(this._ws&&this._ws.readyState===this.OPEN)this._debug("send",e),this._ws.send(e);else{var t=this._options.maxEnqueuedMessages,s=void 0===t?E.maxEnqueuedMessages:t;this._messageQueue.length<s&&(this._debug("enqueue",e),this._messageQueue.push(e))}},e.prototype.addEventListener=function(e,t){this._listeners[e]&&this._listeners[e].push(t)},e.prototype.dispatchEvent=function(e){var t,s,r=this._listeners[e.type];if(r)try{for(var n=Te(r),o=n.next();!o.done;o=n.next()){var i=o.value;this._callEventListener(e,i)}}catch(e){t={error:e}}finally{try{o&&!o.done&&(s=n.return)&&s.call(n)}finally{if(t)throw t.error}}return!0},e.prototype.removeEventListener=function(e,t){this._listeners[e]&&(this._listeners[e]=this._listeners[e].filter((function(e){return e!==t})))},e.prototype._debug=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this._options.debug&&console.log.apply(console,Re(["RWS>"],e))},e.prototype._getNextDelay=function(){var e=this._options,t=e.reconnectionDelayGrowFactor,s=void 0===t?E.reconnectionDelayGrowFactor:t,r=e.minReconnectionDelay,n=void 0===r?E.minReconnectionDelay:r,o=e.maxReconnectionDelay,i=void 0===o?E.maxReconnectionDelay:o,a=0;return this._retryCount>0&&((a=n*Math.pow(s,this._retryCount-1))>i&&(a=i)),this._debug("next delay",a),a},e.prototype._wait=function(){var e=this;return new Promise((function(t){setTimeout(t,e._getNextDelay())}))},e.prototype._getNextUrl=function(e){if("string"==typeof e)return Promise.resolve(e);if("function"==typeof e){var t=e();if("string"==typeof t)return Promise.resolve(t);if(t.then)return t}throw Error("Invalid URL")},e.prototype._connect=function(){var e=this;if(!this._connectLock&&this._shouldReconnect){this._connectLock=!0;var t=this._options,s=t.maxRetries,r=void 0===s?E.maxRetries:s,n=t.connectionTimeout,o=void 0===n?E.connectionTimeout:n,i=t.WebSocket,a=void 0===i?xe():i;if(this._retryCount>=r)return void this._debug("max retries reached",this._retryCount,">=",r);if(this._retryCount++,this._debug("connect",this._retryCount),this._removeListeners(),!Ne(a))throw Error("No valid WebSocket class provided");this._wait().then((function(){return e._getNextUrl(e._url)})).then((function(t){e._closeCalled||(e._debug("connect",{url:t,protocols:e._protocols}),e._ws=e._protocols?new a(t,e._protocols):new a(t),e._ws.binaryType=e._binaryType,e._connectLock=!1,e._addListeners(),e._connectTimeout=setTimeout((function(){return e._handleTimeout()}),o))}))}},e.prototype._handleTimeout=function(){this._debug("timeout event"),this._handleError(new Le(Error("TIMEOUT"),this))},e.prototype._disconnect=function(e,t){if(void 0===e&&(e=1e3),this._clearTimeouts(),this._ws){this._removeListeners();try{this._ws.close(e,t),this._handleClose(new Oe(e,t,this))}catch{}}},e.prototype._acceptOpen=function(){this._debug("accept open"),this._retryCount=0},e.prototype._callEventListener=function(e,t){"handleEvent"in t?t.handleEvent(e):t(e)},e.prototype._removeListeners=function(){this._ws&&(this._debug("removeListeners"),this._ws.removeEventListener("open",this._handleOpen),this._ws.removeEventListener("close",this._handleClose),this._ws.removeEventListener("message",this._handleMessage),this._ws.removeEventListener("error",this._handleError))},e.prototype._addListeners=function(){this._ws&&(this._debug("addListeners"),this._ws.addEventListener("open",this._handleOpen),this._ws.addEventListener("close",this._handleClose),this._ws.addEventListener("message",this._handleMessage),this._ws.addEventListener("error",this._handleError))},e.prototype._clearTimeouts=function(){clearTimeout(this._connectTimeout),clearTimeout(this._uptimeTimeout)},e}();
15
+ ***************************************************************************** */var _=function(e,t){return(_=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)};function E(e,t){function n(){this.constructor=e}_(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}function M(e){var t="function"==typeof Symbol&&e[Symbol.iterator],n=0;return t?t.call(e):{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}}}function A(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,s,o=n.call(e),i=[];try{for(;(void 0===t||t-- >0)&&!(r=o.next()).done;)i.push(r.value)}catch(e){s={error:e}}finally{try{r&&!r.done&&(n=o.return)&&n.call(o)}finally{if(s)throw s.error}}return i}function G(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(A(arguments[t]));return e}var O=function(){return function(e,t){this.target=t,this.type=e}}(),$=function(e){function t(t,n){var r=e.call(this,"error",n)||this;return r.message=t.message,r.error=t,r}return E(t,e),t}(O),F=function(e){function t(t,n,r){void 0===t&&(t=1e3),void 0===n&&(n="");var s=e.call(this,"close",r)||this;return s.wasClean=!0,s.code=t,s.reason=n,s}return E(t,e),t}(O),Q=function(){if(typeof WebSocket<"u")return WebSocket},q=function(e){return typeof e<"u"&&!!e&&2===e.CLOSING},h={maxReconnectionDelay:1e4,minReconnectionDelay:1e3+4e3*Math.random(),minUptime:5e3,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,maxEnqueuedMessages:1/0,startClosed:!1,debug:!1},B=function(){function e(e,t,n){var r=this;void 0===n&&(n={}),this._listeners={error:[],message:[],open:[],close:[]},this._retryCount=-1,this._shouldReconnect=!0,this._connectLock=!1,this._binaryType="blob",this._closeCalled=!1,this._messageQueue=[],this.onclose=null,this.onerror=null,this.onmessage=null,this.onopen=null,this._handleOpen=function(e){r._debug("open event");var t=r._options.minUptime,n=void 0===t?h.minUptime:t;clearTimeout(r._connectTimeout),r._uptimeTimeout=setTimeout((function(){return r._acceptOpen()}),n),r._ws.binaryType=r._binaryType,r._messageQueue.forEach((function(e){return r._ws.send(e)})),r._messageQueue=[],r.onopen&&r.onopen(e),r._listeners.open.forEach((function(t){return r._callEventListener(e,t)}))},this._handleMessage=function(e){r._debug("message event"),r.onmessage&&r.onmessage(e),r._listeners.message.forEach((function(t){return r._callEventListener(e,t)}))},this._handleError=function(e){r._debug("error event",e.message),r._disconnect(void 0,"TIMEOUT"===e.message?"timeout":void 0),r.onerror&&r.onerror(e),r._debug("exec error listeners"),r._listeners.error.forEach((function(t){return r._callEventListener(e,t)})),r._connect()},this._handleClose=function(e){r._debug("close event"),r._clearTimeouts(),r._shouldReconnect&&r._connect(),r.onclose&&r.onclose(e),r._listeners.close.forEach((function(t){return r._callEventListener(e,t)}))},this._url=e,this._protocols=t,this._options=n,this._options.startClosed&&(this._shouldReconnect=!1),this._connect()}return Object.defineProperty(e,"CONNECTING",{get:function(){return 0},enumerable:!0,configurable:!0}),Object.defineProperty(e,"OPEN",{get:function(){return 1},enumerable:!0,configurable:!0}),Object.defineProperty(e,"CLOSING",{get:function(){return 2},enumerable:!0,configurable:!0}),Object.defineProperty(e,"CLOSED",{get:function(){return 3},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"CONNECTING",{get:function(){return e.CONNECTING},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"OPEN",{get:function(){return e.OPEN},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"CLOSING",{get:function(){return e.CLOSING},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"CLOSED",{get:function(){return e.CLOSED},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"binaryType",{get:function(){return this._ws?this._ws.binaryType:this._binaryType},set:function(e){this._binaryType=e,this._ws&&(this._ws.binaryType=e)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"retryCount",{get:function(){return Math.max(this._retryCount,0)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"bufferedAmount",{get:function(){return this._messageQueue.reduce((function(e,t){return"string"==typeof t?e+=t.length:t instanceof Blob?e+=t.size:e+=t.byteLength,e}),0)+(this._ws?this._ws.bufferedAmount:0)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"extensions",{get:function(){return this._ws?this._ws.extensions:""},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"protocol",{get:function(){return this._ws?this._ws.protocol:""},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"readyState",{get:function(){return this._ws?this._ws.readyState:this._options.startClosed?e.CLOSED:e.CONNECTING},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"url",{get:function(){return this._ws?this._ws.url:""},enumerable:!0,configurable:!0}),e.prototype.close=function(e,t){void 0===e&&(e=1e3),this._closeCalled=!0,this._shouldReconnect=!1,this._clearTimeouts(),this._ws?this._ws.readyState!==this.CLOSED?this._ws.close(e,t):this._debug("close: already closed"):this._debug("close enqueued: no ws instance")},e.prototype.reconnect=function(e,t){this._shouldReconnect=!0,this._closeCalled=!1,this._retryCount=-1,this._ws&&this._ws.readyState!==this.CLOSED?(this._disconnect(e,t),this._connect()):this._connect()},e.prototype.send=function(e){if(this._ws&&this._ws.readyState===this.OPEN)this._debug("send",e),this._ws.send(e);else{var t=this._options.maxEnqueuedMessages,n=void 0===t?h.maxEnqueuedMessages:t;this._messageQueue.length<n&&(this._debug("enqueue",e),this._messageQueue.push(e))}},e.prototype.addEventListener=function(e,t){this._listeners[e]&&this._listeners[e].push(t)},e.prototype.dispatchEvent=function(e){var t,n,r=this._listeners[e.type];if(r)try{for(var s=M(r),o=s.next();!o.done;o=s.next()){var i=o.value;this._callEventListener(e,i)}}catch(e){t={error:e}}finally{try{o&&!o.done&&(n=s.return)&&n.call(s)}finally{if(t)throw t.error}}return!0},e.prototype.removeEventListener=function(e,t){this._listeners[e]&&(this._listeners[e]=this._listeners[e].filter((function(e){return e!==t})))},e.prototype._debug=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this._options.debug&&console.log.apply(console,G(["RWS>"],e))},e.prototype._getNextDelay=function(){var e=this._options,t=e.reconnectionDelayGrowFactor,n=void 0===t?h.reconnectionDelayGrowFactor:t,r=e.minReconnectionDelay,s=void 0===r?h.minReconnectionDelay:r,o=e.maxReconnectionDelay,i=void 0===o?h.maxReconnectionDelay:o,c=0;return this._retryCount>0&&((c=s*Math.pow(n,this._retryCount-1))>i&&(c=i)),this._debug("next delay",c),c},e.prototype._wait=function(){var e=this;return new Promise((function(t){setTimeout(t,e._getNextDelay())}))},e.prototype._getNextUrl=function(e){if("string"==typeof e)return Promise.resolve(e);if("function"==typeof e){var t=e();if("string"==typeof t)return Promise.resolve(t);if(t.then)return t}throw Error("Invalid URL")},e.prototype._connect=function(){var e=this;if(!this._connectLock&&this._shouldReconnect){this._connectLock=!0;var t=this._options,n=t.maxRetries,r=void 0===n?h.maxRetries:n,s=t.connectionTimeout,o=void 0===s?h.connectionTimeout:s,i=t.WebSocket,c=void 0===i?Q():i;if(this._retryCount>=r)return void this._debug("max retries reached",this._retryCount,">=",r);if(this._retryCount++,this._debug("connect",this._retryCount),this._removeListeners(),!q(c))throw Error("No valid WebSocket class provided");this._wait().then((function(){return e._getNextUrl(e._url)})).then((function(t){e._closeCalled||(e._debug("connect",{url:t,protocols:e._protocols}),e._ws=e._protocols?new c(t,e._protocols):new c(t),e._ws.binaryType=e._binaryType,e._connectLock=!1,e._addListeners(),e._connectTimeout=setTimeout((function(){return e._handleTimeout()}),o))}))}},e.prototype._handleTimeout=function(){this._debug("timeout event"),this._handleError(new $(Error("TIMEOUT"),this))},e.prototype._disconnect=function(e,t){if(void 0===e&&(e=1e3),this._clearTimeouts(),this._ws){this._removeListeners();try{this._ws.close(e,t),this._handleClose(new F(e,t,this))}catch{}}},e.prototype._acceptOpen=function(){this._debug("accept open"),this._retryCount=0},e.prototype._callEventListener=function(e,t){"handleEvent"in t?t.handleEvent(e):t(e)},e.prototype._removeListeners=function(){this._ws&&(this._debug("removeListeners"),this._ws.removeEventListener("open",this._handleOpen),this._ws.removeEventListener("close",this._handleClose),this._ws.removeEventListener("message",this._handleMessage),this._ws.removeEventListener("error",this._handleError))},e.prototype._addListeners=function(){this._ws&&(this._debug("addListeners"),this._ws.addEventListener("open",this._handleOpen),this._ws.addEventListener("close",this._handleClose),this._ws.addEventListener("message",this._handleMessage),this._ws.addEventListener("error",this._handleError))},e.prototype._clearTimeouts=function(){clearTimeout(this._connectTimeout),clearTimeout(this._uptimeTimeout)},e}();
25
16
  /*!
26
17
  * Reconnecting WebSocket
27
18
  * by Pedro Ladaria <pedro.ladaria@gmail.com>
28
19
  * https://github.com/pladaria/reconnecting-websocket
29
20
  * License MIT
30
- */const pt=()=>{const e=C(),t=S(ne.selectors.selectToken),s=S(_.selectors.selectSubscribers),r=S(_.selectors.selectUnSubscribers),[n,o]=k(null),[i,a]=k(!1),c=V(null);c.current=n;const l=V([]),u=()=>{var e,t,s;if((null==(e=c.current)?void 0:e.readyState)===(null==(t=c.current)?void 0:t.OPEN))try{a(!1),null==(s=c.current)||s.close()}catch(e){g.error("WebSocket error when close: ",e)}};w((()=>((()=>{const e=location.hostname,s=new Pe(`wss://${e}/api/v1/streaming${t?`?access_token=${t}`:""}`);o(s)})(),()=>u())),[t]),w((()=>{n&&(n.onopen=()=>{a(!0),g.info("Connected to WebSocket server")},n.onmessage=t=>{g.debug("WebSocket receive message: ",JSON.parse(t.data));try{e(_.actions.onMessage({...JSON.parse(t.data),date:(new Date).toISOString()}))}catch(e){g.error("WebSocket:onmessage:parse: ",e)}},n.onclose=e=>{a(!1),g.info("Disconnected from WebSocket server:",Ee(e))},n.onerror=e=>{a(!1),g.error("WebSocket error:",e)})}),[n]),w((()=>()=>u()),[]),w((()=>{if(i){const e=s.filter((e=>!l.current.includes(e)));g.debug("WebSocket subscribers list: ",s),e.forEach((e=>{var t;try{null==(t=c.current)||t.send(JSON.stringify({type:"SUBSCRIBE",topics:e.topics})),g.debug("WebSocket subscibed to: ",e),l.current.push(e)}catch(e){g.error("WebSocket error when send: ",e)}}))}}),[i,s,l.current]),w((()=>{r.forEach((t=>{var s;try{null==(s=c.current)||s.send(JSON.stringify({type:"UNSUBSCRIBE",topics:t.topics})),g.debug("WebSocket unsubscribed from: ",t),e(_.actions.onUnsubscribe(t.id))}catch(e){g.error("WebSocket error when send: ",e)}}))}),[r])};export{oe as fillTopic,ft as useNotifications,dt as useUserUpdate,pt as useWebSocket,_ as wsSlice};
21
+ */const J=({onReady:e})=>{const t=g(N.selectors.selectToken),n=y(null),[r,s]=v(null);n.current=r;const o=()=>{var t,r,s;if((null==(t=n.current)?void 0:t.readyState)===(null==(r=n.current)?void 0:r.OPEN))try{e(!1),null==(s=n.current)||s.close()}catch(e){a.error("WebSocket error when close: ",e)}};return d((()=>()=>o()),[]),d((()=>((()=>{const e=location.hostname,n=new B(`wss://${e}/api/v1/streaming${t?`?access_token=${t}`:""}`);s(n)})(),()=>o())),[t]),{socket:r}},Z=()=>{const[e,t]=v(!1),{socket:n}=J({onReady:t}),r=y([]);j({onReady:t,socket:n,serverSubscriptions:r}),I({isReady:e,socket:n,serverSubscriptions:r}),P({isReady:e,socket:n,serverSubscriptions:r})},ee=(e,t)=>Object.keys(t).reduce(((e,n)=>e.replace(`$${n}`,t[n])),e);export{ee as fillTopic,Z as useWebSocket,p as wsSlice};
package/package.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "1.0.95",
2
+ "version": "1.0.112",
3
3
  "name": "@wellesley/ws",
4
4
  "license": "UNLICENSED",
5
5
  "main": "index.mjs",