@wuisdk/plugin-wss 0.1.15 → 0.1.17

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/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import "@wuisdk/plugin-auth";
2
2
  import { WuiContext, WuiPlugin } from "@wuisdk/core";
3
- //#region src/status.code.d.ts
3
+ //#region src/types/status.d.ts
4
4
  export declare const CONN_STATUS_CODES: {
5
5
  readonly CONNECTED: "CONNECTED";
6
6
  readonly DISCONNECTED: "DISCONNECTED";
@@ -36,7 +36,7 @@ export type ConnStatusCode = (typeof CONN_STATUS_CODES)[keyof typeof CONN_STATUS
36
36
  export type AuthErrorCode = (typeof AUTH_ERROR_CODES)[keyof typeof AUTH_ERROR_CODES];
37
37
  export type AuthSuccessCode = (typeof AUTH_SUCCESS_CODES)[keyof typeof AUTH_SUCCESS_CODES];
38
38
  //#endregion
39
- //#region src/ws.types.d.ts
39
+ //#region src/types/socket.d.ts
40
40
  export interface WSParams {
41
41
  url: string;
42
42
  app: string;
@@ -66,7 +66,8 @@ export declare const WSMsgType: {
66
66
  };
67
67
  export type WSMsgType = (typeof WSMsgType)[keyof typeof WSMsgType];
68
68
  export type DirectMsgType = (typeof DirectMsgType)[keyof typeof DirectMsgType];
69
- export type WSTopic = 'server.time' | 'server.logs' | 'server.status' | 'client.online' | 'client.status';
69
+ export type DefaultTopic = 'server.time' | 'server.logs' | 'server.status' | 'client.online' | 'client.status' | 'channel.status';
70
+ export type WSTopic = DefaultTopic | (string & {});
70
71
  export interface WSMessage<T = unknown> {
71
72
  type: WSMsgType;
72
73
  topic?: string;
@@ -79,16 +80,28 @@ export interface StatusPayload {
79
80
  status: StatusCode;
80
81
  message: string;
81
82
  }
82
- export type AuthAction = 'verify' | 'refresh' | 'expired';
83
- export interface AuthPayload {
84
- action: AuthAction;
85
- token?: string;
86
- }
87
83
  export interface TimePayload {
88
84
  time: string;
89
85
  unix: number;
90
86
  }
91
- export type CmdAction = 'CONRST' | 'LOGOUT' | 'CMDRUN' | 'GETLOG';
87
+ export declare const AuthAction: {
88
+ readonly verify: "verify";
89
+ readonly refresh: "refresh";
90
+ readonly expired: "expired";
91
+ };
92
+ export type AuthAction = (typeof AuthAction)[keyof typeof AuthAction];
93
+ export interface AuthPayload {
94
+ action: AuthAction;
95
+ token?: string;
96
+ }
97
+ export declare const DefaultCmd: {
98
+ readonly CONRST: "CONRST";
99
+ readonly LOGOUT: "LOGOUT";
100
+ readonly CMDRUN: "CMDRUN";
101
+ readonly GETLOG: "GETLOG";
102
+ };
103
+ export type DefaultCmd = (typeof DefaultCmd)[keyof typeof DefaultCmd];
104
+ export type CmdAction = DefaultCmd | (string & {});
92
105
  export interface DirectPayload<T = unknown> {
93
106
  action?: CmdAction;
94
107
  payload?: T;
@@ -99,7 +112,7 @@ export interface NotifyPayload {
99
112
  body: string;
100
113
  }
101
114
  //#endregion
102
- //#region src/types.d.ts
115
+ //#region src/types/types.d.ts
103
116
  declare module '@wuisdk/core' {
104
117
  interface WuiPluginMap {
105
118
  readonly wss: IWssService;
@@ -120,7 +133,7 @@ interface IWssService {
120
133
  post(packet: WSMessage): void;
121
134
  direct(type: DirectMsgType, targetId: string, data: DirectPayload): void;
122
135
  publish(topic: WSTopic, data: unknown): void;
123
- subscribe<T>(topic: WSTopic, callback: (data: T) => void, signal?: AbortSignal): () => void;
136
+ subscribe<T>(topic: WSTopic, callback: (data: T, senderId?: string) => void, signal?: AbortSignal): () => void;
124
137
  }
125
138
  //#endregion
126
139
  //#region src/service.d.ts
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import{a as e,i as t,n,o as r,r as i,t as a}from"./ws.types-DuEMwpzC.js";import"@wuisdk/plugin-auth";var o=`@wuisdk/plugin-wss`,s=`0.1.15`,c=class{options;name=`wui-wss-plugin`;service;constructor(e){this.options=e}install(e){this.service=new l(e,this.options),e.registerPlugin(`wss`,this.service)}init(){this.service.init()}destroy(){this.service.destroy()}},l=class{ctx;options;abortController=new AbortController;worker=null;_wsuuid=null;subscribers=/* @__PURE__ */ new Map;constructor(e,t){this.ctx=e,this.options=t}init(){if(!window.Worker){console.warn(`[WssService] Web Workers not supported.`);return}if(!this.options.worker){console.warn(`[WssService] Missing Worker configuration.`);return}let{config:e}=this.ctx,{signal:t}=this.abortController;this.worker=new this.options.worker,this.worker.addEventListener(`message`,e=>{let{type:t,topic:r,data:i}=e.data;switch(t){case n.Ack:i&&this.handleAckMessage(i);break;case n.Error:i&&this.handleErrorMessage(i);break;case n.Auth:i&&this.handleAuthMessage(i);break;case n.Command:i&&this.handleCommandMessage(i);break;case n.Response:i&&console.log(`[WSS-RSP]
2
- `,i);break;case n.Notify:i&&this.handleNotify(i);break;case n.Event:if(r&&i){let e=this.subscribers.get(r);e&&e.forEach(e=>e(i))}}},{signal:t});let r={type:n.Connect,data:{url:this.options.endpoint??`wss://wkrh.info/wss`,app:e.appName,uid:e.appCode,ver:e.version,rel:e.release}};this.worker.postMessage(r)}destroy(){this.abortController.abort(),this.worker?.terminate(),this.worker=null}get wsuuid(){return this._wsuuid??``}post(e){if(!this.worker){console.warn(`[WssService] Worker not initialized`);return}this.worker.postMessage(e)}direct(e,t,n){this.post({type:e,targetId:t,data:n})}publish(e,t){this.post({type:n.Publish,topic:e,data:t})}subscribe(e,t,r){this.subscribers.has(e)||(this.subscribers.set(e,/* @__PURE__ */ new Set),this._wsuuid&&this.post({type:n.Subscribe,topic:e}));let i=this.subscribers.get(e),a=t;i.add(a);let o=!1,s=()=>{if(o)return;o=!0,r&&r.removeEventListener(`abort`,s);let t=this.subscribers.get(e);t&&(t.delete(a),t.size===0&&(this.subscribers.delete(e),this._wsuuid&&this.post({type:n.Unsubscribe,topic:e})))};return r&&(r.aborted?s():r.addEventListener(`abort`,s,{once:!0})),s}handleAckMessage(e){switch(e.status){case r.CONNECTED:this.handleConnected(e.message);break;case r.DISCONNECTED:this.handleDisconnect();break;default:console.log(`[WSS-ACK]`,e.message)}}handleErrorMessage(e){console.log(`[WSS-ERR]`,`${e.status} : ${e.message}`)}handleAuthMessage(e){switch(e.status){case r.AUTH_TOKEN_EXPIRED:this.handleExpired();break;default:console.log(`[WSS-AUTH]`,e.status,e.message)}}handleConnected(e){this._wsuuid=e,this.ctx.events.emit(`wss:connected`),this.tokenAction(`verify`);for(let e of this.subscribers.keys())this.post({type:n.Subscribe,topic:e})}handleDisconnect(){this._wsuuid=null,this.ctx.events.emit(`wss:disconnected`)}tokenAction(e){let{storage:t}=this.ctx.config,r=localStorage.getItem(t.AUTHKEY);r&&this.post({type:n.Auth,data:{action:e,token:r}})}async handleExpired(){if(this.ctx.plugins.auth)try{await this.ctx.plugins.auth.refreshToken(),this.tokenAction(`refresh`)}catch(e){console.warn(`[WssService] Refresh token failed.`,e)}}handleCommandMessage(e){switch(e.action){case`CONRST`:sessionStorage.clear(),window.location.reload();break;case`LOGOUT`:this.ctx.plugins.auth&&this.ctx.plugins.auth.logout();break;default:console.log(`[WSS-CMD]`,`${e.action} : ${e.payload}`)}}handleNotify(e){let t=e.payload,n=t.title??`Hub Notify`,r=t.icon??`https://cdn.jsdelivr.net/gh/wkrdev/assets/img/icon/icon-06.png`,i=t.body??``;Notification.requestPermission().then(e=>{e==`granted`&&new Notification(n,{body:i,icon:r})}).catch(e=>console.error(e))}};const u=()=>({version:s,name:o.split(`/`)[1]});export{i as AUTH_ERROR_CODES,t as AUTH_SUCCESS_CODES,e as CONN_STATUS_CODES,a as DirectMsgType,r as StatusCode,n as WSMsgType,c as WuiWssPlugin,u as info};
1
+ import{a as e,c as t,i as n,n as r,o as i,r as a,s as o,t as s}from"./types-CzCNJdMK.js";import"@wuisdk/plugin-auth";var c=`@wuisdk/plugin-wss`,l=`0.1.17`,u=class{options;name=`wui-wss-plugin`;service;constructor(e){this.options=e}install(e){this.service=new d(e,this.options),e.registerPlugin(`wss`,this.service)}init(){this.service.init()}destroy(){this.service.destroy()}},d=class{ctx;options;abortController=new AbortController;worker=null;_wsuuid=null;subscribers=/* @__PURE__ */ new Map;constructor(e,t){this.ctx=e,this.options=t}init(){if(!window.Worker){console.warn(`[WssService] Web Workers not supported.`);return}if(!this.options.worker){console.warn(`[WssService] Missing Worker configuration.`);return}let{config:e}=this.ctx,{signal:n}=this.abortController;this.worker=new this.options.worker,this.worker.addEventListener(`message`,e=>{let{type:n,topic:r,data:i,senderId:a}=e.data;switch(n){case t.Ack:i&&this.handleMsgAck(i);break;case t.Error:i&&this.handleMsgError(i);break;case t.Auth:i&&this.handleMsgAuth(i);break;case t.Command:i&&this.handleMsgCommand(i);break;case t.Notify:i&&this.handleMsgNotify(i);break;case t.Response:i&&console.log(`[WSS-RSP]
2
+ `,i);break;case t.Event:if(r&&i){let e=this.subscribers.get(r);e&&e.forEach(e=>e(i,a))}}},{signal:n});let r={type:t.Connect,data:{url:this.options.endpoint??`wss://wkrh.info/wss`,app:e.appName,uid:e.appCode,ver:e.version,rel:e.release}};this.worker.postMessage(r)}destroy(){this.abortController.abort(),this.worker?.terminate(),this.worker=null}get wsuuid(){return this._wsuuid??``}post(e){if(!this.worker){console.warn(`[WssService] Worker not initialized`);return}this.worker.postMessage(e)}direct(e,t,n){this.post({type:e,targetId:t,data:n})}publish(e,n){this.post({type:t.Publish,topic:e,data:n})}subscribe(e,n,r){this.subscribers.has(e)||(this.subscribers.set(e,/* @__PURE__ */ new Set),this._wsuuid&&this.post({type:t.Subscribe,topic:e}));let i=this.subscribers.get(e),a=n;i.add(a);let o=!1,s=()=>{if(o)return;o=!0,r&&r.removeEventListener(`abort`,s);let n=this.subscribers.get(e);n&&(n.delete(a),n.size===0&&(this.subscribers.delete(e),this._wsuuid&&this.post({type:t.Unsubscribe,topic:e})))};return r&&(r.aborted?s():r.addEventListener(`abort`,s,{once:!0})),s}handleMsgAck(e){switch(e.status){case n.CONNECTED:this.wsConnected(e.message);break;case n.DISCONNECTED:this.wsDisconnected();break;default:console.log(`[WSS-ACK]`,`${e.status} : ${e.message}`)}}handleMsgError(e){console.log(`[WSS-ERR]`,`${e.status} : ${e.message}`)}handleMsgAuth(t){switch(t.action){case e.expired:this.tokenExpired();break;default:console.log(`[WSS-AUTH]`,t.action)}}handleMsgCommand(e){switch(e.action){case i.CONRST:sessionStorage.clear(),window.location.reload();break;case i.LOGOUT:this.ctx.plugins.auth&&this.ctx.plugins.auth.logout();break;default:console.log(`[WSS-CMD]`,`${e.action} : ${e.payload}`)}}handleMsgNotify(e){let t=e.payload,n=t.title??`Hub Notify`,r=t.icon??`https://cdn.jsdelivr.net/gh/wkrdev/assets/img/icon/icon-06.png`,i=t.body??``;Notification.requestPermission().then(e=>{e===`granted`&&new Notification(n,{body:i,icon:r})}).catch(e=>console.error(e))}wsConnected(e){this._wsuuid=e,this.ctx.events.emit(`wss:connected`),this.tokenAction(`verify`);for(let e of this.subscribers.keys())this.post({type:t.Subscribe,topic:e})}wsDisconnected(){this._wsuuid=null,this.ctx.events.emit(`wss:disconnected`)}tokenAction(e){let{storage:n}=this.ctx.config,r=localStorage.getItem(n.AUTHKEY);r&&this.post({type:t.Auth,data:{action:e,token:r}})}async tokenExpired(){if(this.ctx.plugins.auth)try{await this.ctx.plugins.auth.refreshToken(),this.tokenAction(`refresh`)}catch(e){console.warn(`[WssService] Refresh token failed.`,e)}}};const f=()=>({version:l,name:c.split(`/`)[1]});export{s as AUTH_ERROR_CODES,r as AUTH_SUCCESS_CODES,e as AuthAction,a as CONN_STATUS_CODES,i as DefaultCmd,o as DirectMsgType,n as StatusCode,t as WSMsgType,u as WuiWssPlugin,f as info};
@@ -0,0 +1 @@
1
+ const e={Command:`command`,Response:`response`,Notify:`notify`},t={Subscribe:`subscribe`,Unsubscribe:`unsubscribe`,Publish:`publish`,Event:`event`,Ack:`ack`,Error:`error`,Auth:`auth`,Ping:`ping`,Pong:`pong`,Connect:`connect`,...e},n={verify:`verify`,refresh:`refresh`,expired:`expired`},r={CONRST:`CONRST`,LOGOUT:`LOGOUT`,CMDRUN:`CMDRUN`,GETLOG:`GETLOG`},i={CONNECTED:`CONNECTED`,DISCONNECTED:`DISCONNECTED`},a={AUTH_REQUIRED:`AUTH_REQUIRED`,AUTH_TOKEN_MISSING:`AUTH_TOKEN_MISSING`,AUTH_TOKEN_EXPIRED:`AUTH_TOKEN_EXPIRED`,AUTH_TOKEN_INVALID:`AUTH_TOKEN_INVALID`,AUTH_TOKEN_REVOKED:`AUTH_TOKEN_REVOKED`},o={AUTH_LOGIN_SUCCESS:`AUTH_LOGIN_SUCCESS`,AUTH_LOGOUT_SUCCESS:`AUTH_LOGOUT_SUCCESS`,AUTH_TOKEN_VERIFIED:`AUTH_TOKEN_VERIFIED`,AUTH_TOKEN_REFRESHED:`AUTH_TOKEN_REFRESHED`},s={...i,...a,...o};export{n as a,t as c,s as i,o as n,r as o,i as r,e as s,a as t};
@@ -1 +1 @@
1
- import{n as e,o as t}from"./ws.types-DuEMwpzC.js";let n=null,r,i;self.onmessage=t=>{let{type:r,data:i}=t.data;r===e.Connect?a(i):n?.readyState===WebSocket.OPEN&&n.send(JSON.stringify(t.data))};const a=l=>{let{url:u,app:d,uid:f,ver:p,rel:m}=l;if(!u||!d||!f||!p||!m){console.error(`[HubWorker] Invalid parameters`);return}let h=`${u}?app=${d}&uid=${f}&ver=${p}&rel=${m}`;n&&(n.onopen=null,n.onclose=null,n.onerror=null,n.onmessage=null,n.close()),n=new WebSocket(h),n.onopen=()=>{},n.onclose=()=>{o({type:e.Ack,data:{status:t.DISCONNECTED}}),clearInterval(r),clearTimeout(i),i=self.setTimeout(()=>a(l),c())},n.onerror=e=>{console.error(`[HubWorker] WebSocket Error`,e)},n.onmessage=n=>{if(typeof n.data==`string`)try{let r=JSON.parse(n.data),i=r.data;r.type===e.Ack&&i.status===t.CONNECTED&&s(),o(r)}catch(e){console.error(`[HubWorker] Parse Error:`,e)}}},o=e=>self.postMessage(e),s=()=>{clearInterval(r),r=setInterval(()=>{if(n&&n.readyState===WebSocket.OPEN){let t={type:e.Ping,timestamp:(/* @__PURE__ */ new Date()).getTime()};n.send(JSON.stringify(t))}},5e4)},c=()=>Math.floor(Math.random()*20001)+1e4;
1
+ import{c as e,i as t}from"./types-CzCNJdMK.js";let n=null,r,i;self.onmessage=t=>{let{type:r,data:i}=t.data;r===e.Connect?a(i):n?.readyState===WebSocket.OPEN&&n.send(JSON.stringify(t.data))};const a=l=>{let{url:u,app:d,uid:f,ver:p,rel:m}=l;if(!u||!d||!f||!p||!m){console.error(`[HubWorker] Invalid parameters`);return}let h=`${u}?app=${d}&uid=${f}&ver=${p}&rel=${m}`;n&&(n.onopen=null,n.onclose=null,n.onerror=null,n.onmessage=null,n.close()),n=new WebSocket(h),n.onopen=()=>{},n.onclose=()=>{o({type:e.Ack,data:{status:t.DISCONNECTED}}),self.clearInterval(r),self.clearTimeout(i),i=self.setTimeout(()=>a(l),c())},n.onerror=e=>{console.error(`[HubWorker] WebSocket Error`,e)},n.onmessage=n=>{if(typeof n.data==`string`)try{let r=JSON.parse(n.data),i=r.data;r.type===e.Ack&&i.status===t.CONNECTED&&s(),o(r)}catch(e){console.error(`[HubWorker] Parse Error:`,e)}}},o=e=>self.postMessage(e),s=()=>{self.clearInterval(r),r=self.setInterval(()=>{if(n&&n.readyState===WebSocket.OPEN){let t={type:e.Ping};n.send(JSON.stringify(t))}},5e4)},c=()=>Math.floor(Math.random()*20001)+1e4;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wuisdk/plugin-wss",
3
- "version": "0.1.15",
3
+ "version": "0.1.17",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": {
@@ -1 +0,0 @@
1
- const e={CONNECTED:`CONNECTED`,DISCONNECTED:`DISCONNECTED`},t={AUTH_REQUIRED:`AUTH_REQUIRED`,AUTH_TOKEN_MISSING:`AUTH_TOKEN_MISSING`,AUTH_TOKEN_EXPIRED:`AUTH_TOKEN_EXPIRED`,AUTH_TOKEN_INVALID:`AUTH_TOKEN_INVALID`,AUTH_TOKEN_REVOKED:`AUTH_TOKEN_REVOKED`},n={AUTH_LOGIN_SUCCESS:`AUTH_LOGIN_SUCCESS`,AUTH_LOGOUT_SUCCESS:`AUTH_LOGOUT_SUCCESS`,AUTH_TOKEN_VERIFIED:`AUTH_TOKEN_VERIFIED`,AUTH_TOKEN_REFRESHED:`AUTH_TOKEN_REFRESHED`},r={...e,...t,...n},i={Command:`command`,Response:`response`,Notify:`notify`},a={Subscribe:`subscribe`,Unsubscribe:`unsubscribe`,Publish:`publish`,Event:`event`,Ack:`ack`,Error:`error`,Auth:`auth`,Ping:`ping`,Pong:`pong`,Connect:`connect`,...i};export{e as a,n as i,a as n,r as o,t as r,i as t};