@nsshunt/stssocketioutils 1.0.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 nsshunt
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1 @@
1
+ # stssocketioutils
@@ -0,0 +1,302 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __typeError = (msg) => {
3
+ throw TypeError(msg);
4
+ };
5
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
6
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
7
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
8
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
9
+ var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
10
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
11
+ var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
12
+ var _options, _sockets, _agentManager, _SocketIoClientHelper_instances, LogDebugMessage_fn, LogErrorMessage_fn, EstablishSocketConnect_fn, _socketIoServerHelperOptions, _namespace, _SetupStandardEvents, _SetupConnectionMiddleware, _SetupMessageMiddleware;
13
+ import { io } from "socket.io-client";
14
+ import { AgentManager } from "@nsshunt/stsconfig";
15
+ var STSNamespace = /* @__PURE__ */ ((STSNamespace2) => {
16
+ STSNamespace2["STSMonitor"] = "stsinstrumentmanager/stsmonitor";
17
+ STSNamespace2["STSControl"] = "stsinstrumentmanager/stscontrol";
18
+ return STSNamespace2;
19
+ })(STSNamespace || {});
20
+ var STSRoom = /* @__PURE__ */ ((STSRoom2) => {
21
+ STSRoom2["STSInstrumentDataRoom"] = "stsinstrumentdataroom";
22
+ STSRoom2["STSInstrumentDataSubscriptionRoom"] = "stsinstrumentdatasubscriptionroom";
23
+ STSRoom2["STSRunnerRoom"] = "stsrunnerroom";
24
+ STSRoom2["STSNodeRunnerRoom"] = "stsnoderunnerroom";
25
+ return STSRoom2;
26
+ })(STSRoom || {});
27
+ var STSEvent = /* @__PURE__ */ ((STSEvent2) => {
28
+ STSEvent2["STSInstrumentData"] = "stsinstrumentdata";
29
+ STSEvent2["STSSubInstrumentData"] = "stssubinstrumentdata";
30
+ STSEvent2["STSResetInstrumentData"] = "stsresetinstrumentdata";
31
+ STSEvent2["STSStartLoggingInstrumentData"] = "stsStartLoggingInstrumentData";
32
+ STSEvent2["STSStopLoggingInstrumentData"] = "stsStopLoggingInstrumentData";
33
+ STSEvent2["STSStart"] = "stsstart";
34
+ STSEvent2["STSStop"] = "stsstop";
35
+ STSEvent2["STSPause"] = "stspause";
36
+ STSEvent2["STSResume"] = "stsresume";
37
+ STSEvent2["STSTerminate"] = "ststerminate";
38
+ STSEvent2["STSUpdateStaticConfig"] = "stsupdatestaticconfig";
39
+ STSEvent2["STSUpdateDynamicConfig"] = "stsupdatedynamicconfig";
40
+ STSEvent2["STSSendToRoom"] = "sendToRoom";
41
+ STSEvent2["connect"] = "connect";
42
+ return STSEvent2;
43
+ })(STSEvent || {});
44
+ const isNode = Object.prototype.toString.call(typeof process !== "undefined" ? process : 0) === "[object process]";
45
+ class SocketIoClientHelper {
46
+ constructor(options) {
47
+ __privateAdd(this, _SocketIoClientHelper_instances);
48
+ __privateAdd(this, _options);
49
+ __privateAdd(this, _sockets, {});
50
+ __privateAdd(this, _agentManager, null);
51
+ __privateSet(this, _options, options);
52
+ if (isNode) {
53
+ __privateSet(this, _agentManager, new AgentManager({
54
+ agentOptions: __privateGet(this, _options).agentOptions
55
+ }));
56
+ }
57
+ }
58
+ get sockets() {
59
+ return __privateGet(this, _sockets);
60
+ }
61
+ SetupClientSideSocket(name, address, onConnectCallBack, socketEventsCallBack, errorCallBack) {
62
+ this.sockets[name] = {
63
+ name,
64
+ address,
65
+ socket: null,
66
+ errorCallBack
67
+ };
68
+ __privateMethod(this, _SocketIoClientHelper_instances, EstablishSocketConnect_fn).call(this, name, onConnectCallBack, socketEventsCallBack);
69
+ return this.sockets[name].socket;
70
+ }
71
+ GetSocket(name) {
72
+ return this.sockets[name].socket;
73
+ }
74
+ GetSocketDetail(name) {
75
+ return this.sockets[name];
76
+ }
77
+ }
78
+ _options = new WeakMap();
79
+ _sockets = new WeakMap();
80
+ _agentManager = new WeakMap();
81
+ _SocketIoClientHelper_instances = new WeakSet();
82
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
83
+ LogDebugMessage_fn = function(message) {
84
+ if (__privateGet(this, _options).logger) __privateGet(this, _options).logger.debug(message);
85
+ };
86
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
87
+ LogErrorMessage_fn = function(message) {
88
+ if (__privateGet(this, _options).logger) __privateGet(this, _options).logger.error(message);
89
+ };
90
+ EstablishSocketConnect_fn = function(name, onConnectCallBack, socketEventsCallBack) {
91
+ var _a;
92
+ const socketDetail = this.sockets[name];
93
+ if (socketDetail.socket !== null) {
94
+ if (socketDetail.socket.connected === true) {
95
+ socketDetail.socket.disconnect();
96
+ }
97
+ socketDetail.socket = null;
98
+ if (isNode) {
99
+ setTimeout(() => __privateMethod(this, _SocketIoClientHelper_instances, EstablishSocketConnect_fn).call(this, name, onConnectCallBack, socketEventsCallBack), 100).unref();
100
+ } else {
101
+ setTimeout(() => __privateMethod(this, _SocketIoClientHelper_instances, EstablishSocketConnect_fn).call(this, name, onConnectCallBack, socketEventsCallBack), 100);
102
+ }
103
+ return;
104
+ }
105
+ let socketOptions;
106
+ if (isNode) {
107
+ socketOptions = {
108
+ transports: ["websocket"],
109
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
110
+ agent: (_a = __privateGet(this, _agentManager)) == null ? void 0 : _a.GetAgent(socketDetail.address)
111
+ };
112
+ } else {
113
+ socketOptions = {
114
+ transports: ["websocket"]
115
+ };
116
+ }
117
+ socketDetail.socket = io(socketDetail.address, socketOptions);
118
+ socketDetail.socket.on("connect", () => {
119
+ if (socketDetail.socket) {
120
+ __privateMethod(this, _SocketIoClientHelper_instances, LogDebugMessage_fn).call(this, `Socket: [${socketDetail.socket.id}]: connected`);
121
+ if (onConnectCallBack) {
122
+ setTimeout(() => {
123
+ onConnectCallBack(socketDetail.socket);
124
+ }, 0);
125
+ }
126
+ if (socketEventsCallBack) {
127
+ socketEventsCallBack(socketDetail.socket);
128
+ }
129
+ } else {
130
+ const errorMessage = "Could not get socket object from socket.io";
131
+ __privateMethod(this, _SocketIoClientHelper_instances, LogErrorMessage_fn).call(this, errorMessage);
132
+ socketDetail.errorCallBack(new Error(errorMessage));
133
+ }
134
+ });
135
+ socketDetail.socket.on("disconnect", (reason) => {
136
+ __privateMethod(this, _SocketIoClientHelper_instances, LogDebugMessage_fn).call(this, "socket disconnect: " + reason);
137
+ switch (reason) {
138
+ case "io server disconnect":
139
+ {
140
+ __privateMethod(this, _SocketIoClientHelper_instances, LogDebugMessage_fn).call(this, "The server disconnected using disconnectSockets, i.e. normal safe shutdown from explicit disconnection by the server.");
141
+ __privateMethod(this, _SocketIoClientHelper_instances, LogDebugMessage_fn).call(this, "The connection will be re-established when the server becomes available.");
142
+ const socketDetail2 = this.sockets[name];
143
+ socketDetail2.socket = null;
144
+ if (isNode) {
145
+ setTimeout(() => __privateMethod(this, _SocketIoClientHelper_instances, EstablishSocketConnect_fn).call(this, name, onConnectCallBack, socketEventsCallBack), 100).unref();
146
+ } else {
147
+ setTimeout(() => __privateMethod(this, _SocketIoClientHelper_instances, EstablishSocketConnect_fn).call(this, name, onConnectCallBack, socketEventsCallBack), 100);
148
+ }
149
+ }
150
+ break;
151
+ case "io client disconnect":
152
+ __privateMethod(this, _SocketIoClientHelper_instances, LogDebugMessage_fn).call(this, "The client disconnected using disconnectSockets, i.e. normal safe disconnection from explicit disconnection by the client.");
153
+ __privateMethod(this, _SocketIoClientHelper_instances, LogDebugMessage_fn).call(this, "The connection will not be re-established automatically.");
154
+ break;
155
+ case "transport close":
156
+ case "ping timeout":
157
+ case "transport error":
158
+ {
159
+ __privateMethod(this, _SocketIoClientHelper_instances, LogDebugMessage_fn).call(this, `Server unexpectedly disconnected. Reason: [${reason}]`);
160
+ __privateMethod(this, _SocketIoClientHelper_instances, LogDebugMessage_fn).call(this, "The connection will be re-established when the server becomes available.");
161
+ const socketDetail2 = this.sockets[name];
162
+ if (socketDetail2.socket) {
163
+ socketDetail2.socket.disconnect();
164
+ }
165
+ socketDetail2.socket = null;
166
+ if (isNode) {
167
+ setTimeout(() => __privateMethod(this, _SocketIoClientHelper_instances, EstablishSocketConnect_fn).call(this, name, onConnectCallBack, socketEventsCallBack), 100).unref();
168
+ } else {
169
+ setTimeout(() => __privateMethod(this, _SocketIoClientHelper_instances, EstablishSocketConnect_fn).call(this, name, onConnectCallBack, socketEventsCallBack), 100);
170
+ }
171
+ }
172
+ break;
173
+ }
174
+ });
175
+ };
176
+ class SocketIoServerHelper {
177
+ constructor(options) {
178
+ __privateAdd(this, _socketIoServerHelperOptions);
179
+ __privateAdd(this, _namespace, {});
180
+ __publicField(this, "LeaveRoom", (namespace, socket, room) => {
181
+ this.LogMessage(namespace, `${namespace.socketionamespace.name}: Leaving room [${room}]`);
182
+ socket.leave(room);
183
+ });
184
+ __publicField(this, "JoinRoom", (namespace, socket, room) => {
185
+ this.LogMessage(namespace, `${namespace.socketionamespace.name}: Socket joining room [${room}], ID: [${socket.id}]`);
186
+ socket.join(room);
187
+ });
188
+ __privateAdd(this, _SetupStandardEvents, (namespace, socket) => {
189
+ socket.on("disconnect", (reason) => {
190
+ this.LogMessage(namespace, `${namespace.socketionamespace.name}: socket disconnect, ID: [${socket.id}] [${reason}]`);
191
+ });
192
+ socket.on("disconnecting", (reason) => {
193
+ this.LogMessage(namespace, `${namespace.socketionamespace.name}: socket disconnecting, ID: [${socket.id}] [${reason}]`);
194
+ });
195
+ socket.on("error", (error) => {
196
+ this.LogMessage(namespace, `${namespace.socketionamespace.name}: socket error, ID: [${socket.id}] [${error}]`);
197
+ });
198
+ socket.on("__STSdisconnect", (reason) => {
199
+ this.LogMessage(namespace, `${namespace.socketionamespace.name}: __STSdisconnect: socket disconnect, ID: [${socket.id}] [${reason}]`);
200
+ });
201
+ socket.on("__STSdisconnecting", (reason, callBackResult) => {
202
+ this.LogMessage(namespace, `${namespace.socketionamespace.name}: __STSdisconnecting: socket disconnecting, ID: [${socket.id}] [${reason}]`);
203
+ callBackResult("__STSdisconnecting accepted by server.");
204
+ });
205
+ socket.on("__STSjoinRoom", (rooms) => {
206
+ rooms.forEach((room) => {
207
+ this.JoinRoom(namespace, socket, room);
208
+ });
209
+ });
210
+ socket.on("__STSleaveRoom", (rooms) => {
211
+ rooms.forEach((room) => {
212
+ this.LeaveRoom(namespace, socket, room);
213
+ });
214
+ });
215
+ socket.on("__STSsendToRoom", (rooms, payload) => {
216
+ rooms.forEach((room) => {
217
+ this.LogMessage(namespace, `${namespace.socketionamespace.name}:socket.on:sendToRoom: __STSsendToRoom: Sending to room [${room}], ID: [${socket.id}]`);
218
+ namespace.socketionamespace.to(room).emit(payload.command, payload);
219
+ });
220
+ });
221
+ });
222
+ // Use this middleward to check every incomming connection
223
+ __privateAdd(this, _SetupConnectionMiddleware, (nameSpace) => {
224
+ nameSpace.socketionamespace.use((socket, next) => {
225
+ {
226
+ next();
227
+ }
228
+ });
229
+ });
230
+ // Use this middleware to check very packet being received
231
+ __privateAdd(this, _SetupMessageMiddleware, (socket) => {
232
+ socket.use(([event, ...args], next) => {
233
+ next();
234
+ });
235
+ });
236
+ __publicField(this, "SetupNamespace", (io2, namespace, rooms, autoJoinRooms, socketConnectCallBack, socketEventsCallBack) => {
237
+ __privateGet(this, _namespace)[namespace] = {
238
+ namespace,
239
+ pid: process.pid,
240
+ socketionamespace: io2.of(`/${namespace}/`)
241
+ };
242
+ __privateGet(this, _SetupConnectionMiddleware).call(this, __privateGet(this, _namespace)[namespace]);
243
+ __privateGet(this, _namespace)[namespace].socketionamespace.on("connection", (socket) => {
244
+ this.LogMessage(__privateGet(this, _namespace)[namespace], `${namespace}: Socket connected, ID: [${socket.id}]`);
245
+ this.LogMessage(__privateGet(this, _namespace)[namespace], `${namespace}: Authentication Handshake: [${JSON.stringify(socket.handshake.auth)}]`);
246
+ __privateGet(this, _SetupMessageMiddleware).call(this, socket);
247
+ if (autoJoinRooms) {
248
+ rooms.map((room) => {
249
+ this.JoinRoom(__privateGet(this, _namespace)[namespace], socket, room);
250
+ });
251
+ }
252
+ __privateGet(this, _SetupStandardEvents).call(this, __privateGet(this, _namespace)[namespace], socket);
253
+ if (socketConnectCallBack) {
254
+ setTimeout(() => {
255
+ socketConnectCallBack(socket);
256
+ }, 0);
257
+ }
258
+ if (socketEventsCallBack) {
259
+ socketEventsCallBack(socket);
260
+ }
261
+ });
262
+ return __privateGet(this, _namespace)[namespace].socketionamespace;
263
+ });
264
+ __publicField(this, "GetSTSSocketIONamespace", (namespace) => {
265
+ return __privateGet(this, _namespace)[namespace];
266
+ });
267
+ __publicField(this, "GetSTSSocketIONamespaces", () => {
268
+ return __privateGet(this, _namespace);
269
+ });
270
+ __publicField(this, "CloseAdaptors", async () => {
271
+ for (const [, namespace] of Object.entries(__privateGet(this, _namespace))) {
272
+ await namespace.socketionamespace.adapter.close();
273
+ }
274
+ });
275
+ __publicField(this, "DisconnectSockets", () => {
276
+ for (const [, namespace] of Object.entries(__privateGet(this, _namespace))) {
277
+ namespace.socketionamespace.disconnectSockets();
278
+ }
279
+ __privateSet(this, _namespace, {});
280
+ });
281
+ __privateSet(this, _socketIoServerHelperOptions, options);
282
+ }
283
+ LogMessage(namespace, message) {
284
+ __privateGet(this, _socketIoServerHelperOptions).logger.debug(`${namespace.namespace}: ${message}`);
285
+ }
286
+ SetupEvent(event, eventCb) {
287
+ return this;
288
+ }
289
+ }
290
+ _socketIoServerHelperOptions = new WeakMap();
291
+ _namespace = new WeakMap();
292
+ _SetupStandardEvents = new WeakMap();
293
+ _SetupConnectionMiddleware = new WeakMap();
294
+ _SetupMessageMiddleware = new WeakMap();
295
+ export {
296
+ STSEvent,
297
+ STSNamespace,
298
+ STSRoom,
299
+ SocketIoClientHelper,
300
+ SocketIoServerHelper
301
+ };
302
+ //# sourceMappingURL=stssocketioutils.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stssocketioutils.mjs","sources":["../src/commonTypes.ts","../node_modules/detect-node/index.esm.js","../src/socketIoClientHelper.ts","../src/socketIoServerHelper.ts"],"sourcesContent":["/* eslint @typescript-eslint/no-explicit-any: 0, @typescript-eslint/no-unused-vars: 0 */ // --> OFF\nimport { Server, Socket, Namespace } from \"socket.io\";\nimport { ISTSLogger } from '@nsshunt/stsutils'\n\nexport interface STSDefaultClientToServerEvents {\n /**\n * Join the room(s) specified for this client.\n * @param room The room(s) to join for this client.\n * @returns \n */\n\t__STSjoinRoom: (room: string[]) => void;\n\n /**\n * Remove this client from the specified room(s).\n * @param room The room(s) to remove the client from within the server.\n * @returns \n */\n\t__STSleaveRoom: (room: string[]) => void;\n\n /**\n * Alerts the server that this client has flagged to disconnect. Allows server to perform clean-up if required. The server must call-back with the result of the disconnecting event.\n * @param reason Reason for the disconnecting event.\n * @param callback The server must call-back with the result of the disconnecting event.\n * @returns \n */\n\t__STSdisconnecting: (reason: string, callback: (data: string) => void) => void;\n\n /**\n * Alerts the server to disconnect this client.\n * @param reason Reason for the disconnect event.\n * @returns \n */\n\t__STSdisconnect: (reason: string) => void; // server and client event\n\n /**\n * Send a payload of data to 1 or more rooms registered on the server.\n * @param rooms Room array for broadcasting.\n * @param payload The data to be sent to every client within each of the rooms provided. The command within the payload must be a valid STSServerToClientEvents event. This includes any\n * interface that extends STSServerToClientEvents.\n * @returns \n */\n \n\t__STSsendToRoom: (rooms: string[], payload: { command: string, payload: any }) => void;\n}\n\nexport interface STSDefaultServerToClientEvents {\n /**\n * The server may emit an unsolicited disconnect event to flag that all clients should disconnect. Most likely becuase the server may be shutting down.\n * @param reason Reason why the server is emitting this disconnect event.\n * @returns \n */\n\t__STSdisconnect: (reason: string) => void;\n}\n\nexport interface ISocketIoServerHelperOptions {\n logger: ISTSLogger\n}\n\nexport type ServerEventCb = (socket: any, data: any) => void\n\nexport interface ServerSocketEvent {\n\tserverEventName: string,\n\tserverEventCb: ServerEventCb\n}\n\nexport enum STSNamespace {\n\tSTSMonitor = 'stsinstrumentmanager/stsmonitor',\n\tSTSControl = 'stsinstrumentmanager/stscontrol'\n}\n\nexport enum STSRoom {\n\t// STSMonitor rooms\n\tSTSInstrumentDataRoom = 'stsinstrumentdataroom', // This room is for all instrument data messages\n\tSTSInstrumentDataSubscriptionRoom = 'stsinstrumentdatasubscriptionroom', // This room is only for subscribed instrument data messages\n\n\t// STSControl rooms\n\tSTSRunnerRoom = 'stsrunnerroom',\n\tSTSNodeRunnerRoom = 'stsnoderunnerroom'\n}\n\nexport enum STSEvent {\n\t// STSInstrumentData\n\tSTSInstrumentData = 'stsinstrumentdata',\n\tSTSSubInstrumentData = 'stssubinstrumentdata', // sub-scribed instrument data. This only outputs the nodes that have been subscribed by the client(s).\n\tSTSResetInstrumentData = 'stsresetinstrumentdata',\n\n\tSTSStartLoggingInstrumentData = 'stsStartLoggingInstrumentData',\n\tSTSStopLoggingInstrumentData = 'stsStopLoggingInstrumentData',\n\n\t// STSRunner events\n\tSTSStart = 'stsstart', // Start a test run with options as payload.\n\tSTSStop = 'stsstop', // Stop test run(s).\n\tSTSPause = 'stspause', // Pause test run(s).\n\tSTSResume = 'stsresume', // Resume test run(s).\n\tSTSTerminate = 'ststerminate', // Terminate runner instances and exit applications.\n\t// This may also be uysed to force trigger self healing (i.e. auto re-start) when\n\t// running within a container orchestrator such as K8, K3 or Docker Swarm.\n\tSTSUpdateStaticConfig = 'stsupdatestaticconfig', // Update base configuration. Options as payload.\n\tSTSUpdateDynamicConfig = 'stsupdatedynamicconfig', // Update running configuration. This is used\n\t// to control the runnning behaviour of test(s) in-flight. Options as payload.\n\n\tSTSSendToRoom = 'sendToRoom',\n\n\t// Standard socket events\n\tconnect = 'connect'\n}\n\n// https://socket.io/docs/v4/typescript/\n\nexport interface InterServerEvents {\n\tping: () => void;\n}\n\nexport interface STSSocketIONamespace {\n\tnamespace: string\n\tpid: number\n\tsocketionamespace: Namespace<STSDefaultClientToServerEvents, STSDefaultServerToClientEvents, InterServerEvents>\n}\n\nexport type STSSocketIONamespaces = Record<string, STSSocketIONamespace>;\n\nexport type STSServerSocket = Socket<STSDefaultClientToServerEvents, STSDefaultServerToClientEvents, InterServerEvents>\nexport type STSClientSocket = Socket<STSDefaultServerToClientEvents, STSDefaultClientToServerEvents, InterServerEvents>\n\nexport interface ISocketIoServerHelper<ClientToServerEvents extends STSDefaultClientToServerEvents, ServerToClientEvents extends STSDefaultServerToClientEvents>\n{\n LogMessage: (namespace: STSSocketIONamespace, message: string) => void\n LeaveRoom: (namespace: STSSocketIONamespace, socket: STSServerSocket, room: STSRoom) => void\n JoinRoom: (namespace: STSSocketIONamespace, socket: STSServerSocket, room: STSRoom) => void\n SetupNamespace: (io: Server, namespace: STSNamespace, rooms: string[], autoJoinRooms: boolean, \n /* serverSocketEvents: ServerSocketEvent[], */\n socketConnectCallBack: ((socket: Socket<ClientToServerEvents, ServerToClientEvents, InterServerEvents>) => void) | null,\n socketEventsCallBack: ((socket: Socket<ClientToServerEvents, ServerToClientEvents, InterServerEvents>) => void) | null\n ) => Namespace<ClientToServerEvents, ServerToClientEvents, InterServerEvents>\n GetSTSSocketIONamespace: (namespace: any) => STSSocketIONamespace\n GetSTSSocketIONamespaces: () => STSSocketIONamespaces\n DisconnectSockets: () => void\n CloseAdaptors: () => Promise<void>\n SetupEvent(event: ClientToServerEvents, eventCb: ServerEventCb): ISocketIoServerHelper<ClientToServerEvents, ServerToClientEvents>\n}\n","// Only Node.JS has a process variable that is of [[Class]] process\nexport default Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]';\n","import { io, SocketOptions, ManagerOptions, Socket } from 'socket.io-client'\n\nimport isNode from 'detect-node';\n\nimport { ISTSLogger } from '@nsshunt/stsutils'\n\nimport { STSDefaultClientToServerEvents, STSDefaultServerToClientEvents } from './commonTypes'\nimport { AgentManager } from '@nsshunt/stsconfig';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type EventCb = (socket: any, data: any) => void\n\n/*\nSocket.io - Reserved events\nOn each side, the following events are reserved and should not be used as event names by your application:\nconnect\nconnect_error\ndisconnect\ndisconnecting\nnewListener\nremoveListener\n*/\n\n/*\nexport interface EventsMap { // From the socket.io library - was not declared as external\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [event: string]: any;\n}\n*/\n\nexport interface ISocketDetail {\n\tname: string,\n\taddress: string,\n \n\tsocket: Socket | null\n errorCallBack: (error: Error) => void\n}\n\nexport interface ISocketIoClientHelperOptions\n{\n url?: string\n agentOptions?: {\n\t\tkeepAlive: boolean,\n\t\tmaxSockets: number\n\t\tmaxTotalSockets: number,\n\t\tmaxFreeSockets: number,\n\t\ttimeout: number,\n\t\trejectUnauthorized: boolean // Allows self signed certs in non production mode(s)\n\t}\n logger?: ISTSLogger\n}\n\nexport class SocketIoClientHelper<ServerToClientEvents extends STSDefaultServerToClientEvents, ClientToServerEvents extends STSDefaultClientToServerEvents>\n{\n #options: ISocketIoClientHelperOptions\n #sockets: Record<string, ISocketDetail> = { }\n #agentManager: AgentManager | null = null;\n\n constructor(options: ISocketIoClientHelperOptions) {\n this.#options = options;\n if (isNode) {\n this.#agentManager = new AgentManager({\n agentOptions: this.#options.agentOptions\n });\n }\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n #LogDebugMessage(message: any): void {\n if (this.#options.logger) this.#options.logger.debug(message);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n #LogErrorMessage(message: any): void {\n if (this.#options.logger) this.#options.logger.error(message);\n }\n\n get sockets(): Record<string, ISocketDetail> {\n return this.#sockets;\n }\n \n SetupClientSideSocket(name: string, address: string, \n onConnectCallBack: ((socket: Socket<ServerToClientEvents, ClientToServerEvents>) => void) | null,\n socketEventsCallBack: ((socket: Socket<ServerToClientEvents, ClientToServerEvents>) => void) | null,\n errorCallBack: ((error: Error) => void)\n ): Socket<ServerToClientEvents, ClientToServerEvents> {\n this.sockets[name] = {\n name,\n address,\n socket: null,\n errorCallBack\n }\n this.#EstablishSocketConnect(name, onConnectCallBack, socketEventsCallBack);\n return this.sockets[name].socket as Socket<ServerToClientEvents, ClientToServerEvents>\n }\n\n GetSocket(name: string): Socket<ServerToClientEvents, ClientToServerEvents> {\n return this.sockets[name].socket as Socket<ServerToClientEvents, ClientToServerEvents>\n }\n\n GetSocketDetail(name: string): ISocketDetail {\n return this.sockets[name];\n }\n\n #EstablishSocketConnect(name: string, onConnectCallBack: ((socket: Socket<ServerToClientEvents, ClientToServerEvents>) => void) | null,\n socketEventsCallBack: ((socket: Socket<ServerToClientEvents, ClientToServerEvents>) => void) | null): void\n {\n const socketDetail: ISocketDetail = this.sockets[name];\n\n if (socketDetail.socket !== null) {\n // We already have a socket object (may or may not be connected)\n if (socketDetail.socket.connected === true) {\n socketDetail.socket.disconnect();\n }\n socketDetail.socket = null;\n if (isNode) {\n setTimeout(() => this.#EstablishSocketConnect(name, onConnectCallBack, socketEventsCallBack), 100).unref(); //@@ config\n } else {\n setTimeout(() => this.#EstablishSocketConnect(name, onConnectCallBack, socketEventsCallBack), 100); //@@ config\n }\n return;\n }\n\n let socketOptions: Partial<SocketOptions & ManagerOptions>;\n if (isNode) {\n // https://socket.io/docs/v4/client-options/#reconnection\n // https://github.com/socketio/engine.io-client#methods\n socketOptions = {\n transports: [\"websocket\" ],\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n agent: this.#agentManager?.GetAgent(socketDetail.address) as any\n }\n // This also works for self signed certs\n //rejectUnauthorized: goptions.isProduction // Allows self signed certs in non production mode(s)\n\n //reconnection: true\n //auth: {\n //\ttoken: \"abcd\"\n //}\n //,path: '/zzz'\n } else {\n socketOptions = {\n transports: [\"websocket\" ]\n }\n }\n socketDetail.socket = io(socketDetail.address, socketOptions) as Socket<ServerToClientEvents, ClientToServerEvents>\n\n socketDetail.socket.on(\"connect\", () => {\n if (socketDetail.socket) {\n this.#LogDebugMessage(`Socket: [${socketDetail.socket.id}]: connected`);\n\n if (onConnectCallBack) {\n setTimeout(() => {\n onConnectCallBack(socketDetail.socket as Socket<ServerToClientEvents, ClientToServerEvents>);\n }, 0);\n }\n\n if (socketEventsCallBack) {\n socketEventsCallBack(socketDetail.socket);\n }\n\n } else {\n const errorMessage: string = 'Could not get socket object from socket.io';\n this.#LogErrorMessage(errorMessage);\n socketDetail.errorCallBack(new Error(errorMessage));\n }\n })\n\n // https://socket.io/docs/v4/client-socket-instance/#disconnect\n socketDetail.socket.on(\"disconnect\", (reason: string) =>\n {\n this.#LogDebugMessage('socket disconnect: ' + reason);\n switch (reason) {\n case 'io server disconnect' : {\n // The server disconnect using disconnectSockets (i.e. normal safe shutdown)\n this.#LogDebugMessage('The server disconnected using disconnectSockets, i.e. normal safe shutdown from explicit disconnection by the server.');\n this.#LogDebugMessage('The connection will be re-established when the server becomes available.');\n const socketDetail: ISocketDetail = this.sockets[name];\n socketDetail.socket = null;\n if (isNode) {\n setTimeout(() => this.#EstablishSocketConnect(name, onConnectCallBack, socketEventsCallBack), 100).unref(); //@@ config\n } else {\n setTimeout(() => this.#EstablishSocketConnect(name, onConnectCallBack, socketEventsCallBack), 100); //@@ config\n }\n }\n break;\n case 'io client disconnect' :\n this.#LogDebugMessage('The client disconnected using disconnectSockets, i.e. normal safe disconnection from explicit disconnection by the client.');\n this.#LogDebugMessage('The connection will not be re-established automatically.');\n // Do nothing\n break;\n case 'transport close' :\n case 'ping timeout' :\n case 'transport error' : {\n this.#LogDebugMessage(`Server unexpectedly disconnected. Reason: [${reason}]`);\n this.#LogDebugMessage('The connection will be re-established when the server becomes available.');\n const socketDetail: ISocketDetail = this.sockets[name];\n if (socketDetail.socket) {\n socketDetail.socket.disconnect();\n }\n socketDetail.socket = null;\n if (isNode) {\n setTimeout(() => this.#EstablishSocketConnect(name, onConnectCallBack, socketEventsCallBack), 100).unref(); //@@ config\n } else {\n setTimeout(() => this.#EstablishSocketConnect(name, onConnectCallBack, socketEventsCallBack), 100); //@@ config\n }\n }\n break;\n }\n });\n }\n}\n","/* eslint @typescript-eslint/no-explicit-any: 0, @typescript-eslint/no-unused-vars: 0 */ // --> OFF\nimport { JSONObject } from '@nsshunt/stsutils'\n\nimport { Server, Namespace, Socket } from \"socket.io\";\n\nimport { STSDefaultClientToServerEvents, STSDefaultServerToClientEvents, STSServerSocket, ISocketIoServerHelper,\n ISocketIoServerHelperOptions, STSSocketIONamespace, STSSocketIONamespaces, STSNamespace,\n InterServerEvents, ServerEventCb } from './commonTypes'\n\nexport class SocketIoServerHelper<ClientToServerEvents extends STSDefaultClientToServerEvents, ServerToClientEvents extends STSDefaultServerToClientEvents> implements ISocketIoServerHelper<ClientToServerEvents, ServerToClientEvents>\n{\n #socketIoServerHelperOptions: ISocketIoServerHelperOptions\n #namespace: STSSocketIONamespaces = { };\n\n constructor(options: ISocketIoServerHelperOptions) { // IProcessBase\n this.#socketIoServerHelperOptions = options;\n }\n\n LogMessage(namespace: STSSocketIONamespace, message: any) {\n this.#socketIoServerHelperOptions.logger.debug(`${namespace.namespace}: ${message}`);\n }\n\n LeaveRoom = (namespace: STSSocketIONamespace, socket: Socket<ClientToServerEvents, ServerToClientEvents>, room: string): void => {\n this.LogMessage(namespace, `${namespace.socketionamespace.name}: Leaving room [${room}]`);\n socket.leave(room);\n };\n\n JoinRoom = (namespace: STSSocketIONamespace, socket: Socket<ClientToServerEvents, ServerToClientEvents>, room: string): void => {\n this.LogMessage(namespace, `${namespace.socketionamespace.name}: Socket joining room [${room}], ID: [${socket.id}]`);\n socket.join(room);\n };\n\n #SetupStandardEvents = (namespace: STSSocketIONamespace, socket: Socket<STSDefaultClientToServerEvents, STSDefaultServerToClientEvents>): void => {\n socket.on('disconnect', (reason: string) => {\n this.LogMessage(namespace, `${namespace.socketionamespace.name}: socket disconnect, ID: [${socket.id}] [${reason}]`);\n });\n\n socket.on('disconnecting', (reason: string) => {\n this.LogMessage(namespace, `${namespace.socketionamespace.name}: socket disconnecting, ID: [${socket.id}] [${reason}]`);\n });\n\n socket.on('error', (error: Error) => {\n this.LogMessage(namespace, `${namespace.socketionamespace.name}: socket error, ID: [${socket.id}] [${error}]`);\n });\n\n socket.on(\"__STSdisconnect\", (reason: string) => {\n this.LogMessage(namespace, `${namespace.socketionamespace.name}: __STSdisconnect: socket disconnect, ID: [${socket.id}] [${reason}]`);\n });\n\n socket.on(\"__STSdisconnecting\", (reason, callBackResult) => {\n this.LogMessage(namespace, `${namespace.socketionamespace.name}: __STSdisconnecting: socket disconnecting, ID: [${socket.id}] [${reason}]`);\n callBackResult(\"__STSdisconnecting accepted by server.\");\n });\n\n socket.on('__STSjoinRoom', (rooms: string[]): void => { //@@ names\n rooms.forEach((room) => {\n this.JoinRoom(namespace, socket, room)\n });\n });\n\n socket.on('__STSleaveRoom', (rooms: string[]): void => { //@@ names\n rooms.forEach((room) => {\n this.LeaveRoom(namespace, socket, room);\n });\n });\n\n socket.on('__STSsendToRoom', (rooms: string[], payload: { command: string, payload: JSONObject }): void => {\n rooms.forEach((room) => {\n this.LogMessage(namespace, `${namespace.socketionamespace.name}:socket.on:sendToRoom: __STSsendToRoom: Sending to room [${room}], ID: [${socket.id}]`);\n \n namespace.socketionamespace.to(room).emit(payload.command as any, payload);\n });\n });\n }\n\n // Use this middleward to check every incomming connection\n #SetupConnectionMiddleware = (nameSpace: STSSocketIONamespace) => {\n nameSpace.socketionamespace.use((socket, next) => {\n //if (isValid(socket.request)) {\n const a=5; // for lint purposes\n if (a === 5) {\n next();\n } else {\n next(new Error(\"invalid\"));\n }\n });\n }\n\n // Use this middleware to check very packet being received\n #SetupMessageMiddleware = (socket: STSServerSocket) => {\n socket.use(([event, ...args], next) => {\n /*\n if (isUnauthorized(event)) {\n return next(new Error(\"unauthorized event\"));\n }\n */\n next();\n });\n }\n \n SetupNamespace = (io: Server, namespace: STSNamespace, rooms: string[], autoJoinRooms: boolean, /* serverSocketEvents: ServerSocketEvent[], */\n socketConnectCallBack: ((socket: Socket<ClientToServerEvents, ServerToClientEvents, InterServerEvents>) => void) | null,\n socketEventsCallBack: ((socket: Socket<ClientToServerEvents, ServerToClientEvents, InterServerEvents>) => void) | null\n ): Namespace<ClientToServerEvents, ServerToClientEvents, InterServerEvents> => {\n // Create STS Command Centre Client namespace\n this.#namespace[namespace] = {\n namespace: namespace,\n pid: process.pid,\n socketionamespace: io.of(`/${namespace}/`)\n }\n\n this.#SetupConnectionMiddleware(this.#namespace[namespace]);\n\n this.#namespace[namespace].socketionamespace.on(\"connection\", socket => {\n this.LogMessage(this.#namespace[namespace], `${namespace}: Socket connected, ID: [${socket.id}]`);\n this.LogMessage(this.#namespace[namespace], `${namespace}: Authentication Handshake: [${JSON.stringify(socket.handshake.auth)}]`);\n\n this.#SetupMessageMiddleware(socket);\n\n if (autoJoinRooms) {\n rooms.map((room) => {\n this.JoinRoom(this.#namespace[namespace], socket, room);\n });\n }\n\n this.#SetupStandardEvents(this.#namespace[namespace], socket);\n\n if (socketConnectCallBack) {\n setTimeout(() => {\n socketConnectCallBack(socket);\n }, 0);\n }\n\n if (socketEventsCallBack) {\n socketEventsCallBack(socket);\n }\n });\n\n return this.#namespace[namespace].socketionamespace as Namespace<ClientToServerEvents, ServerToClientEvents, InterServerEvents>;\n }\n\n GetSTSSocketIONamespace = (namespace: string): STSSocketIONamespace => {\n return this.#namespace[namespace];\n }\n\n GetSTSSocketIONamespaces = (): STSSocketIONamespaces => {\n return this.#namespace;\n }\n\n CloseAdaptors = async (): Promise<void> => {\n for (const [, namespace] of Object.entries(this.#namespace)) {\n await namespace.socketionamespace.adapter.close();\n }\n }\n\n DisconnectSockets = (): void => {\n for (const [, namespace] of Object.entries(this.#namespace)) {\n namespace.socketionamespace.disconnectSockets();\n }\n this.#namespace = { };\n }\n\n SetupEvent(event: ClientToServerEvents, eventCb: ServerEventCb): ISocketIoServerHelper<ClientToServerEvents, ServerToClientEvents> {\n return this as any;\n }\n}\n"],"names":["STSNamespace","STSRoom","STSEvent","socketDetail","io"],"mappings":";;;;;;;;;;;;;;AAiEY,IAAA,iCAAAA,kBAAL;AACNA,gBAAA,YAAa,IAAA;AACbA,gBAAA,YAAa,IAAA;AAFFA,SAAAA;AAAA,GAAA,gBAAA,CAAA,CAAA;AAKA,IAAA,4BAAAC,aAAL;AAENA,WAAA,uBAAwB,IAAA;AACxBA,WAAA,mCAAoC,IAAA;AAGpCA,WAAA,eAAgB,IAAA;AAChBA,WAAA,mBAAoB,IAAA;AAPTA,SAAAA;AAAA,GAAA,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;AACT,gBAAA,IAAI,CAAC,SAAS;AAChB,iBAAK,SAAS,mBAAK,YAAW,SAAS,GAAG,QAAQ,IAAI;AAAA,UAAA,CACzD;AAAA,QAAA;AAGL,2BAAK,sBAAL,WAA0B,mBAAK,YAAW,SAAS,GAAG;AAEtD,YAAI,uBAAuB;AACvB,qBAAW,MAAM;AACb,kCAAsB,MAAM;AAAA,aAC7B,CAAC;AAAA,QAAA;AAGR,YAAI,sBAAsB;AACtB,+BAAqB,MAAM;AAAA,QAAA;AAAA,MAC/B,CACH;AAEM,aAAA,mBAAK,YAAW,SAAS,EAAE;AAAA,IACtC;AAEA,mDAA0B,CAAC,cAA4C;AAC5D,aAAA,mBAAK,YAAW,SAAS;AAAA,IACpC;AAEA,oDAA2B,MAA6B;AACpD,aAAO,mBAAK;AAAA,IAChB;AAEA,yCAAgB,YAA2B;AAC5B,iBAAA,CAAG,EAAA,SAAS,KAAK,OAAO,QAAQ,mBAAK,WAAU,GAAG;AACnD,cAAA,UAAU,kBAAkB,QAAQ,MAAM;AAAA,MAAA;AAAA,IAExD;AAEA,6CAAoB,MAAY;AACjB,iBAAA,CAAG,EAAA,SAAS,KAAK,OAAO,QAAQ,mBAAK,WAAU,GAAG;AACzD,kBAAU,kBAAkB,kBAAkB;AAAA,MAAA;AAElD,yBAAK,YAAa,CAAE;AAAA,IACxB;AAjJI,uBAAK,8BAA+B;AAAA,EAAA;AAAA,EAGxC,WAAW,WAAiC,SAAc;AACjD,uBAAA,8BAA6B,OAAO,MAAM,GAAG,UAAU,SAAS,KAAK,OAAO,EAAE;AAAA,EAAA;AAAA,EA+IvF,WAAW,OAA6B,SAA2F;AACxH,WAAA;AAAA,EAAA;AAEf;AA1JI;AACA;AAoBA;AA4CA;AAaA;","x_google_ignoreList":[1]}
@@ -0,0 +1,304 @@
1
+ (function(global, factory) {
2
+ typeof exports === "object" && typeof module !== "undefined" ? factory(exports, require("socket.io-client"), require("@nsshunt/stsconfig")) : typeof define === "function" && define.amd ? define(["exports", "socket.io-client", "@nsshunt/stsconfig"], factory) : (global = typeof globalThis !== "undefined" ? globalThis : global || self, factory(global["@nsshunt/stssocketioutils"] = {}, global.socket["io-client"], global.stsconfig));
3
+ })(this, function(exports2, socket_ioClient, stsconfig) {
4
+ "use strict";var __defProp = Object.defineProperty;
5
+ var __typeError = (msg) => {
6
+ throw TypeError(msg);
7
+ };
8
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
9
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
10
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
11
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
12
+ var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
13
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
14
+ var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
15
+
16
+ var _options, _sockets, _agentManager, _SocketIoClientHelper_instances, LogDebugMessage_fn, LogErrorMessage_fn, EstablishSocketConnect_fn, _socketIoServerHelperOptions, _namespace, _SetupStandardEvents, _SetupConnectionMiddleware, _SetupMessageMiddleware;
17
+ var STSNamespace = /* @__PURE__ */ ((STSNamespace2) => {
18
+ STSNamespace2["STSMonitor"] = "stsinstrumentmanager/stsmonitor";
19
+ STSNamespace2["STSControl"] = "stsinstrumentmanager/stscontrol";
20
+ return STSNamespace2;
21
+ })(STSNamespace || {});
22
+ var STSRoom = /* @__PURE__ */ ((STSRoom2) => {
23
+ STSRoom2["STSInstrumentDataRoom"] = "stsinstrumentdataroom";
24
+ STSRoom2["STSInstrumentDataSubscriptionRoom"] = "stsinstrumentdatasubscriptionroom";
25
+ STSRoom2["STSRunnerRoom"] = "stsrunnerroom";
26
+ STSRoom2["STSNodeRunnerRoom"] = "stsnoderunnerroom";
27
+ return STSRoom2;
28
+ })(STSRoom || {});
29
+ var STSEvent = /* @__PURE__ */ ((STSEvent2) => {
30
+ STSEvent2["STSInstrumentData"] = "stsinstrumentdata";
31
+ STSEvent2["STSSubInstrumentData"] = "stssubinstrumentdata";
32
+ STSEvent2["STSResetInstrumentData"] = "stsresetinstrumentdata";
33
+ STSEvent2["STSStartLoggingInstrumentData"] = "stsStartLoggingInstrumentData";
34
+ STSEvent2["STSStopLoggingInstrumentData"] = "stsStopLoggingInstrumentData";
35
+ STSEvent2["STSStart"] = "stsstart";
36
+ STSEvent2["STSStop"] = "stsstop";
37
+ STSEvent2["STSPause"] = "stspause";
38
+ STSEvent2["STSResume"] = "stsresume";
39
+ STSEvent2["STSTerminate"] = "ststerminate";
40
+ STSEvent2["STSUpdateStaticConfig"] = "stsupdatestaticconfig";
41
+ STSEvent2["STSUpdateDynamicConfig"] = "stsupdatedynamicconfig";
42
+ STSEvent2["STSSendToRoom"] = "sendToRoom";
43
+ STSEvent2["connect"] = "connect";
44
+ return STSEvent2;
45
+ })(STSEvent || {});
46
+ const isNode = Object.prototype.toString.call(typeof process !== "undefined" ? process : 0) === "[object process]";
47
+ class SocketIoClientHelper {
48
+ constructor(options) {
49
+ __privateAdd(this, _SocketIoClientHelper_instances);
50
+ __privateAdd(this, _options);
51
+ __privateAdd(this, _sockets, {});
52
+ __privateAdd(this, _agentManager, null);
53
+ __privateSet(this, _options, options);
54
+ if (isNode) {
55
+ __privateSet(this, _agentManager, new stsconfig.AgentManager({
56
+ agentOptions: __privateGet(this, _options).agentOptions
57
+ }));
58
+ }
59
+ }
60
+ get sockets() {
61
+ return __privateGet(this, _sockets);
62
+ }
63
+ SetupClientSideSocket(name, address, onConnectCallBack, socketEventsCallBack, errorCallBack) {
64
+ this.sockets[name] = {
65
+ name,
66
+ address,
67
+ socket: null,
68
+ errorCallBack
69
+ };
70
+ __privateMethod(this, _SocketIoClientHelper_instances, EstablishSocketConnect_fn).call(this, name, onConnectCallBack, socketEventsCallBack);
71
+ return this.sockets[name].socket;
72
+ }
73
+ GetSocket(name) {
74
+ return this.sockets[name].socket;
75
+ }
76
+ GetSocketDetail(name) {
77
+ return this.sockets[name];
78
+ }
79
+ }
80
+ _options = new WeakMap();
81
+ _sockets = new WeakMap();
82
+ _agentManager = new WeakMap();
83
+ _SocketIoClientHelper_instances = new WeakSet();
84
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
85
+ LogDebugMessage_fn = function(message) {
86
+ if (__privateGet(this, _options).logger) __privateGet(this, _options).logger.debug(message);
87
+ };
88
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
89
+ LogErrorMessage_fn = function(message) {
90
+ if (__privateGet(this, _options).logger) __privateGet(this, _options).logger.error(message);
91
+ };
92
+ EstablishSocketConnect_fn = function(name, onConnectCallBack, socketEventsCallBack) {
93
+ var _a;
94
+ const socketDetail = this.sockets[name];
95
+ if (socketDetail.socket !== null) {
96
+ if (socketDetail.socket.connected === true) {
97
+ socketDetail.socket.disconnect();
98
+ }
99
+ socketDetail.socket = null;
100
+ if (isNode) {
101
+ setTimeout(() => __privateMethod(this, _SocketIoClientHelper_instances, EstablishSocketConnect_fn).call(this, name, onConnectCallBack, socketEventsCallBack), 100).unref();
102
+ } else {
103
+ setTimeout(() => __privateMethod(this, _SocketIoClientHelper_instances, EstablishSocketConnect_fn).call(this, name, onConnectCallBack, socketEventsCallBack), 100);
104
+ }
105
+ return;
106
+ }
107
+ let socketOptions;
108
+ if (isNode) {
109
+ socketOptions = {
110
+ transports: ["websocket"],
111
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
112
+ agent: (_a = __privateGet(this, _agentManager)) == null ? void 0 : _a.GetAgent(socketDetail.address)
113
+ };
114
+ } else {
115
+ socketOptions = {
116
+ transports: ["websocket"]
117
+ };
118
+ }
119
+ socketDetail.socket = socket_ioClient.io(socketDetail.address, socketOptions);
120
+ socketDetail.socket.on("connect", () => {
121
+ if (socketDetail.socket) {
122
+ __privateMethod(this, _SocketIoClientHelper_instances, LogDebugMessage_fn).call(this, `Socket: [${socketDetail.socket.id}]: connected`);
123
+ if (onConnectCallBack) {
124
+ setTimeout(() => {
125
+ onConnectCallBack(socketDetail.socket);
126
+ }, 0);
127
+ }
128
+ if (socketEventsCallBack) {
129
+ socketEventsCallBack(socketDetail.socket);
130
+ }
131
+ } else {
132
+ const errorMessage = "Could not get socket object from socket.io";
133
+ __privateMethod(this, _SocketIoClientHelper_instances, LogErrorMessage_fn).call(this, errorMessage);
134
+ socketDetail.errorCallBack(new Error(errorMessage));
135
+ }
136
+ });
137
+ socketDetail.socket.on("disconnect", (reason) => {
138
+ __privateMethod(this, _SocketIoClientHelper_instances, LogDebugMessage_fn).call(this, "socket disconnect: " + reason);
139
+ switch (reason) {
140
+ case "io server disconnect":
141
+ {
142
+ __privateMethod(this, _SocketIoClientHelper_instances, LogDebugMessage_fn).call(this, "The server disconnected using disconnectSockets, i.e. normal safe shutdown from explicit disconnection by the server.");
143
+ __privateMethod(this, _SocketIoClientHelper_instances, LogDebugMessage_fn).call(this, "The connection will be re-established when the server becomes available.");
144
+ const socketDetail2 = this.sockets[name];
145
+ socketDetail2.socket = null;
146
+ if (isNode) {
147
+ setTimeout(() => __privateMethod(this, _SocketIoClientHelper_instances, EstablishSocketConnect_fn).call(this, name, onConnectCallBack, socketEventsCallBack), 100).unref();
148
+ } else {
149
+ setTimeout(() => __privateMethod(this, _SocketIoClientHelper_instances, EstablishSocketConnect_fn).call(this, name, onConnectCallBack, socketEventsCallBack), 100);
150
+ }
151
+ }
152
+ break;
153
+ case "io client disconnect":
154
+ __privateMethod(this, _SocketIoClientHelper_instances, LogDebugMessage_fn).call(this, "The client disconnected using disconnectSockets, i.e. normal safe disconnection from explicit disconnection by the client.");
155
+ __privateMethod(this, _SocketIoClientHelper_instances, LogDebugMessage_fn).call(this, "The connection will not be re-established automatically.");
156
+ break;
157
+ case "transport close":
158
+ case "ping timeout":
159
+ case "transport error":
160
+ {
161
+ __privateMethod(this, _SocketIoClientHelper_instances, LogDebugMessage_fn).call(this, `Server unexpectedly disconnected. Reason: [${reason}]`);
162
+ __privateMethod(this, _SocketIoClientHelper_instances, LogDebugMessage_fn).call(this, "The connection will be re-established when the server becomes available.");
163
+ const socketDetail2 = this.sockets[name];
164
+ if (socketDetail2.socket) {
165
+ socketDetail2.socket.disconnect();
166
+ }
167
+ socketDetail2.socket = null;
168
+ if (isNode) {
169
+ setTimeout(() => __privateMethod(this, _SocketIoClientHelper_instances, EstablishSocketConnect_fn).call(this, name, onConnectCallBack, socketEventsCallBack), 100).unref();
170
+ } else {
171
+ setTimeout(() => __privateMethod(this, _SocketIoClientHelper_instances, EstablishSocketConnect_fn).call(this, name, onConnectCallBack, socketEventsCallBack), 100);
172
+ }
173
+ }
174
+ break;
175
+ }
176
+ });
177
+ };
178
+ class SocketIoServerHelper {
179
+ constructor(options) {
180
+ __privateAdd(this, _socketIoServerHelperOptions);
181
+ __privateAdd(this, _namespace, {});
182
+ __publicField(this, "LeaveRoom", (namespace, socket, room) => {
183
+ this.LogMessage(namespace, `${namespace.socketionamespace.name}: Leaving room [${room}]`);
184
+ socket.leave(room);
185
+ });
186
+ __publicField(this, "JoinRoom", (namespace, socket, room) => {
187
+ this.LogMessage(namespace, `${namespace.socketionamespace.name}: Socket joining room [${room}], ID: [${socket.id}]`);
188
+ socket.join(room);
189
+ });
190
+ __privateAdd(this, _SetupStandardEvents, (namespace, socket) => {
191
+ socket.on("disconnect", (reason) => {
192
+ this.LogMessage(namespace, `${namespace.socketionamespace.name}: socket disconnect, ID: [${socket.id}] [${reason}]`);
193
+ });
194
+ socket.on("disconnecting", (reason) => {
195
+ this.LogMessage(namespace, `${namespace.socketionamespace.name}: socket disconnecting, ID: [${socket.id}] [${reason}]`);
196
+ });
197
+ socket.on("error", (error) => {
198
+ this.LogMessage(namespace, `${namespace.socketionamespace.name}: socket error, ID: [${socket.id}] [${error}]`);
199
+ });
200
+ socket.on("__STSdisconnect", (reason) => {
201
+ this.LogMessage(namespace, `${namespace.socketionamespace.name}: __STSdisconnect: socket disconnect, ID: [${socket.id}] [${reason}]`);
202
+ });
203
+ socket.on("__STSdisconnecting", (reason, callBackResult) => {
204
+ this.LogMessage(namespace, `${namespace.socketionamespace.name}: __STSdisconnecting: socket disconnecting, ID: [${socket.id}] [${reason}]`);
205
+ callBackResult("__STSdisconnecting accepted by server.");
206
+ });
207
+ socket.on("__STSjoinRoom", (rooms) => {
208
+ rooms.forEach((room) => {
209
+ this.JoinRoom(namespace, socket, room);
210
+ });
211
+ });
212
+ socket.on("__STSleaveRoom", (rooms) => {
213
+ rooms.forEach((room) => {
214
+ this.LeaveRoom(namespace, socket, room);
215
+ });
216
+ });
217
+ socket.on("__STSsendToRoom", (rooms, payload) => {
218
+ rooms.forEach((room) => {
219
+ this.LogMessage(namespace, `${namespace.socketionamespace.name}:socket.on:sendToRoom: __STSsendToRoom: Sending to room [${room}], ID: [${socket.id}]`);
220
+ namespace.socketionamespace.to(room).emit(payload.command, payload);
221
+ });
222
+ });
223
+ });
224
+ // Use this middleward to check every incomming connection
225
+ __privateAdd(this, _SetupConnectionMiddleware, (nameSpace) => {
226
+ nameSpace.socketionamespace.use((socket, next) => {
227
+ {
228
+ next();
229
+ }
230
+ });
231
+ });
232
+ // Use this middleware to check very packet being received
233
+ __privateAdd(this, _SetupMessageMiddleware, (socket) => {
234
+ socket.use(([event, ...args], next) => {
235
+ next();
236
+ });
237
+ });
238
+ __publicField(this, "SetupNamespace", (io, namespace, rooms, autoJoinRooms, socketConnectCallBack, socketEventsCallBack) => {
239
+ __privateGet(this, _namespace)[namespace] = {
240
+ namespace,
241
+ pid: process.pid,
242
+ socketionamespace: io.of(`/${namespace}/`)
243
+ };
244
+ __privateGet(this, _SetupConnectionMiddleware).call(this, __privateGet(this, _namespace)[namespace]);
245
+ __privateGet(this, _namespace)[namespace].socketionamespace.on("connection", (socket) => {
246
+ this.LogMessage(__privateGet(this, _namespace)[namespace], `${namespace}: Socket connected, ID: [${socket.id}]`);
247
+ this.LogMessage(__privateGet(this, _namespace)[namespace], `${namespace}: Authentication Handshake: [${JSON.stringify(socket.handshake.auth)}]`);
248
+ __privateGet(this, _SetupMessageMiddleware).call(this, socket);
249
+ if (autoJoinRooms) {
250
+ rooms.map((room) => {
251
+ this.JoinRoom(__privateGet(this, _namespace)[namespace], socket, room);
252
+ });
253
+ }
254
+ __privateGet(this, _SetupStandardEvents).call(this, __privateGet(this, _namespace)[namespace], socket);
255
+ if (socketConnectCallBack) {
256
+ setTimeout(() => {
257
+ socketConnectCallBack(socket);
258
+ }, 0);
259
+ }
260
+ if (socketEventsCallBack) {
261
+ socketEventsCallBack(socket);
262
+ }
263
+ });
264
+ return __privateGet(this, _namespace)[namespace].socketionamespace;
265
+ });
266
+ __publicField(this, "GetSTSSocketIONamespace", (namespace) => {
267
+ return __privateGet(this, _namespace)[namespace];
268
+ });
269
+ __publicField(this, "GetSTSSocketIONamespaces", () => {
270
+ return __privateGet(this, _namespace);
271
+ });
272
+ __publicField(this, "CloseAdaptors", async () => {
273
+ for (const [, namespace] of Object.entries(__privateGet(this, _namespace))) {
274
+ await namespace.socketionamespace.adapter.close();
275
+ }
276
+ });
277
+ __publicField(this, "DisconnectSockets", () => {
278
+ for (const [, namespace] of Object.entries(__privateGet(this, _namespace))) {
279
+ namespace.socketionamespace.disconnectSockets();
280
+ }
281
+ __privateSet(this, _namespace, {});
282
+ });
283
+ __privateSet(this, _socketIoServerHelperOptions, options);
284
+ }
285
+ LogMessage(namespace, message) {
286
+ __privateGet(this, _socketIoServerHelperOptions).logger.debug(`${namespace.namespace}: ${message}`);
287
+ }
288
+ SetupEvent(event, eventCb) {
289
+ return this;
290
+ }
291
+ }
292
+ _socketIoServerHelperOptions = new WeakMap();
293
+ _namespace = new WeakMap();
294
+ _SetupStandardEvents = new WeakMap();
295
+ _SetupConnectionMiddleware = new WeakMap();
296
+ _SetupMessageMiddleware = new WeakMap();
297
+ exports2.STSEvent = STSEvent;
298
+ exports2.STSNamespace = STSNamespace;
299
+ exports2.STSRoom = STSRoom;
300
+ exports2.SocketIoClientHelper = SocketIoClientHelper;
301
+ exports2.SocketIoServerHelper = SocketIoServerHelper;
302
+ Object.defineProperty(exports2, Symbol.toStringTag, { value: "Module" });
303
+ });
304
+ //# sourceMappingURL=stssocketioutils.umd.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stssocketioutils.umd.js","sources":["../src/commonTypes.ts","../node_modules/detect-node/index.esm.js","../src/socketIoClientHelper.ts","../src/socketIoServerHelper.ts"],"sourcesContent":["/* eslint @typescript-eslint/no-explicit-any: 0, @typescript-eslint/no-unused-vars: 0 */ // --> OFF\nimport { Server, Socket, Namespace } from \"socket.io\";\nimport { ISTSLogger } from '@nsshunt/stsutils'\n\nexport interface STSDefaultClientToServerEvents {\n /**\n * Join the room(s) specified for this client.\n * @param room The room(s) to join for this client.\n * @returns \n */\n\t__STSjoinRoom: (room: string[]) => void;\n\n /**\n * Remove this client from the specified room(s).\n * @param room The room(s) to remove the client from within the server.\n * @returns \n */\n\t__STSleaveRoom: (room: string[]) => void;\n\n /**\n * Alerts the server that this client has flagged to disconnect. Allows server to perform clean-up if required. The server must call-back with the result of the disconnecting event.\n * @param reason Reason for the disconnecting event.\n * @param callback The server must call-back with the result of the disconnecting event.\n * @returns \n */\n\t__STSdisconnecting: (reason: string, callback: (data: string) => void) => void;\n\n /**\n * Alerts the server to disconnect this client.\n * @param reason Reason for the disconnect event.\n * @returns \n */\n\t__STSdisconnect: (reason: string) => void; // server and client event\n\n /**\n * Send a payload of data to 1 or more rooms registered on the server.\n * @param rooms Room array for broadcasting.\n * @param payload The data to be sent to every client within each of the rooms provided. The command within the payload must be a valid STSServerToClientEvents event. This includes any\n * interface that extends STSServerToClientEvents.\n * @returns \n */\n \n\t__STSsendToRoom: (rooms: string[], payload: { command: string, payload: any }) => void;\n}\n\nexport interface STSDefaultServerToClientEvents {\n /**\n * The server may emit an unsolicited disconnect event to flag that all clients should disconnect. Most likely becuase the server may be shutting down.\n * @param reason Reason why the server is emitting this disconnect event.\n * @returns \n */\n\t__STSdisconnect: (reason: string) => void;\n}\n\nexport interface ISocketIoServerHelperOptions {\n logger: ISTSLogger\n}\n\nexport type ServerEventCb = (socket: any, data: any) => void\n\nexport interface ServerSocketEvent {\n\tserverEventName: string,\n\tserverEventCb: ServerEventCb\n}\n\nexport enum STSNamespace {\n\tSTSMonitor = 'stsinstrumentmanager/stsmonitor',\n\tSTSControl = 'stsinstrumentmanager/stscontrol'\n}\n\nexport enum STSRoom {\n\t// STSMonitor rooms\n\tSTSInstrumentDataRoom = 'stsinstrumentdataroom', // This room is for all instrument data messages\n\tSTSInstrumentDataSubscriptionRoom = 'stsinstrumentdatasubscriptionroom', // This room is only for subscribed instrument data messages\n\n\t// STSControl rooms\n\tSTSRunnerRoom = 'stsrunnerroom',\n\tSTSNodeRunnerRoom = 'stsnoderunnerroom'\n}\n\nexport enum STSEvent {\n\t// STSInstrumentData\n\tSTSInstrumentData = 'stsinstrumentdata',\n\tSTSSubInstrumentData = 'stssubinstrumentdata', // sub-scribed instrument data. This only outputs the nodes that have been subscribed by the client(s).\n\tSTSResetInstrumentData = 'stsresetinstrumentdata',\n\n\tSTSStartLoggingInstrumentData = 'stsStartLoggingInstrumentData',\n\tSTSStopLoggingInstrumentData = 'stsStopLoggingInstrumentData',\n\n\t// STSRunner events\n\tSTSStart = 'stsstart', // Start a test run with options as payload.\n\tSTSStop = 'stsstop', // Stop test run(s).\n\tSTSPause = 'stspause', // Pause test run(s).\n\tSTSResume = 'stsresume', // Resume test run(s).\n\tSTSTerminate = 'ststerminate', // Terminate runner instances and exit applications.\n\t// This may also be uysed to force trigger self healing (i.e. auto re-start) when\n\t// running within a container orchestrator such as K8, K3 or Docker Swarm.\n\tSTSUpdateStaticConfig = 'stsupdatestaticconfig', // Update base configuration. Options as payload.\n\tSTSUpdateDynamicConfig = 'stsupdatedynamicconfig', // Update running configuration. This is used\n\t// to control the runnning behaviour of test(s) in-flight. Options as payload.\n\n\tSTSSendToRoom = 'sendToRoom',\n\n\t// Standard socket events\n\tconnect = 'connect'\n}\n\n// https://socket.io/docs/v4/typescript/\n\nexport interface InterServerEvents {\n\tping: () => void;\n}\n\nexport interface STSSocketIONamespace {\n\tnamespace: string\n\tpid: number\n\tsocketionamespace: Namespace<STSDefaultClientToServerEvents, STSDefaultServerToClientEvents, InterServerEvents>\n}\n\nexport type STSSocketIONamespaces = Record<string, STSSocketIONamespace>;\n\nexport type STSServerSocket = Socket<STSDefaultClientToServerEvents, STSDefaultServerToClientEvents, InterServerEvents>\nexport type STSClientSocket = Socket<STSDefaultServerToClientEvents, STSDefaultClientToServerEvents, InterServerEvents>\n\nexport interface ISocketIoServerHelper<ClientToServerEvents extends STSDefaultClientToServerEvents, ServerToClientEvents extends STSDefaultServerToClientEvents>\n{\n LogMessage: (namespace: STSSocketIONamespace, message: string) => void\n LeaveRoom: (namespace: STSSocketIONamespace, socket: STSServerSocket, room: STSRoom) => void\n JoinRoom: (namespace: STSSocketIONamespace, socket: STSServerSocket, room: STSRoom) => void\n SetupNamespace: (io: Server, namespace: STSNamespace, rooms: string[], autoJoinRooms: boolean, \n /* serverSocketEvents: ServerSocketEvent[], */\n socketConnectCallBack: ((socket: Socket<ClientToServerEvents, ServerToClientEvents, InterServerEvents>) => void) | null,\n socketEventsCallBack: ((socket: Socket<ClientToServerEvents, ServerToClientEvents, InterServerEvents>) => void) | null\n ) => Namespace<ClientToServerEvents, ServerToClientEvents, InterServerEvents>\n GetSTSSocketIONamespace: (namespace: any) => STSSocketIONamespace\n GetSTSSocketIONamespaces: () => STSSocketIONamespaces\n DisconnectSockets: () => void\n CloseAdaptors: () => Promise<void>\n SetupEvent(event: ClientToServerEvents, eventCb: ServerEventCb): ISocketIoServerHelper<ClientToServerEvents, ServerToClientEvents>\n}\n","// Only Node.JS has a process variable that is of [[Class]] process\nexport default Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]';\n","import { io, SocketOptions, ManagerOptions, Socket } from 'socket.io-client'\n\nimport isNode from 'detect-node';\n\nimport { ISTSLogger } from '@nsshunt/stsutils'\n\nimport { STSDefaultClientToServerEvents, STSDefaultServerToClientEvents } from './commonTypes'\nimport { AgentManager } from '@nsshunt/stsconfig';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type EventCb = (socket: any, data: any) => void\n\n/*\nSocket.io - Reserved events\nOn each side, the following events are reserved and should not be used as event names by your application:\nconnect\nconnect_error\ndisconnect\ndisconnecting\nnewListener\nremoveListener\n*/\n\n/*\nexport interface EventsMap { // From the socket.io library - was not declared as external\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [event: string]: any;\n}\n*/\n\nexport interface ISocketDetail {\n\tname: string,\n\taddress: string,\n \n\tsocket: Socket | null\n errorCallBack: (error: Error) => void\n}\n\nexport interface ISocketIoClientHelperOptions\n{\n url?: string\n agentOptions?: {\n\t\tkeepAlive: boolean,\n\t\tmaxSockets: number\n\t\tmaxTotalSockets: number,\n\t\tmaxFreeSockets: number,\n\t\ttimeout: number,\n\t\trejectUnauthorized: boolean // Allows self signed certs in non production mode(s)\n\t}\n logger?: ISTSLogger\n}\n\nexport class SocketIoClientHelper<ServerToClientEvents extends STSDefaultServerToClientEvents, ClientToServerEvents extends STSDefaultClientToServerEvents>\n{\n #options: ISocketIoClientHelperOptions\n #sockets: Record<string, ISocketDetail> = { }\n #agentManager: AgentManager | null = null;\n\n constructor(options: ISocketIoClientHelperOptions) {\n this.#options = options;\n if (isNode) {\n this.#agentManager = new AgentManager({\n agentOptions: this.#options.agentOptions\n });\n }\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n #LogDebugMessage(message: any): void {\n if (this.#options.logger) this.#options.logger.debug(message);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n #LogErrorMessage(message: any): void {\n if (this.#options.logger) this.#options.logger.error(message);\n }\n\n get sockets(): Record<string, ISocketDetail> {\n return this.#sockets;\n }\n \n SetupClientSideSocket(name: string, address: string, \n onConnectCallBack: ((socket: Socket<ServerToClientEvents, ClientToServerEvents>) => void) | null,\n socketEventsCallBack: ((socket: Socket<ServerToClientEvents, ClientToServerEvents>) => void) | null,\n errorCallBack: ((error: Error) => void)\n ): Socket<ServerToClientEvents, ClientToServerEvents> {\n this.sockets[name] = {\n name,\n address,\n socket: null,\n errorCallBack\n }\n this.#EstablishSocketConnect(name, onConnectCallBack, socketEventsCallBack);\n return this.sockets[name].socket as Socket<ServerToClientEvents, ClientToServerEvents>\n }\n\n GetSocket(name: string): Socket<ServerToClientEvents, ClientToServerEvents> {\n return this.sockets[name].socket as Socket<ServerToClientEvents, ClientToServerEvents>\n }\n\n GetSocketDetail(name: string): ISocketDetail {\n return this.sockets[name];\n }\n\n #EstablishSocketConnect(name: string, onConnectCallBack: ((socket: Socket<ServerToClientEvents, ClientToServerEvents>) => void) | null,\n socketEventsCallBack: ((socket: Socket<ServerToClientEvents, ClientToServerEvents>) => void) | null): void\n {\n const socketDetail: ISocketDetail = this.sockets[name];\n\n if (socketDetail.socket !== null) {\n // We already have a socket object (may or may not be connected)\n if (socketDetail.socket.connected === true) {\n socketDetail.socket.disconnect();\n }\n socketDetail.socket = null;\n if (isNode) {\n setTimeout(() => this.#EstablishSocketConnect(name, onConnectCallBack, socketEventsCallBack), 100).unref(); //@@ config\n } else {\n setTimeout(() => this.#EstablishSocketConnect(name, onConnectCallBack, socketEventsCallBack), 100); //@@ config\n }\n return;\n }\n\n let socketOptions: Partial<SocketOptions & ManagerOptions>;\n if (isNode) {\n // https://socket.io/docs/v4/client-options/#reconnection\n // https://github.com/socketio/engine.io-client#methods\n socketOptions = {\n transports: [\"websocket\" ],\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n agent: this.#agentManager?.GetAgent(socketDetail.address) as any\n }\n // This also works for self signed certs\n //rejectUnauthorized: goptions.isProduction // Allows self signed certs in non production mode(s)\n\n //reconnection: true\n //auth: {\n //\ttoken: \"abcd\"\n //}\n //,path: '/zzz'\n } else {\n socketOptions = {\n transports: [\"websocket\" ]\n }\n }\n socketDetail.socket = io(socketDetail.address, socketOptions) as Socket<ServerToClientEvents, ClientToServerEvents>\n\n socketDetail.socket.on(\"connect\", () => {\n if (socketDetail.socket) {\n this.#LogDebugMessage(`Socket: [${socketDetail.socket.id}]: connected`);\n\n if (onConnectCallBack) {\n setTimeout(() => {\n onConnectCallBack(socketDetail.socket as Socket<ServerToClientEvents, ClientToServerEvents>);\n }, 0);\n }\n\n if (socketEventsCallBack) {\n socketEventsCallBack(socketDetail.socket);\n }\n\n } else {\n const errorMessage: string = 'Could not get socket object from socket.io';\n this.#LogErrorMessage(errorMessage);\n socketDetail.errorCallBack(new Error(errorMessage));\n }\n })\n\n // https://socket.io/docs/v4/client-socket-instance/#disconnect\n socketDetail.socket.on(\"disconnect\", (reason: string) =>\n {\n this.#LogDebugMessage('socket disconnect: ' + reason);\n switch (reason) {\n case 'io server disconnect' : {\n // The server disconnect using disconnectSockets (i.e. normal safe shutdown)\n this.#LogDebugMessage('The server disconnected using disconnectSockets, i.e. normal safe shutdown from explicit disconnection by the server.');\n this.#LogDebugMessage('The connection will be re-established when the server becomes available.');\n const socketDetail: ISocketDetail = this.sockets[name];\n socketDetail.socket = null;\n if (isNode) {\n setTimeout(() => this.#EstablishSocketConnect(name, onConnectCallBack, socketEventsCallBack), 100).unref(); //@@ config\n } else {\n setTimeout(() => this.#EstablishSocketConnect(name, onConnectCallBack, socketEventsCallBack), 100); //@@ config\n }\n }\n break;\n case 'io client disconnect' :\n this.#LogDebugMessage('The client disconnected using disconnectSockets, i.e. normal safe disconnection from explicit disconnection by the client.');\n this.#LogDebugMessage('The connection will not be re-established automatically.');\n // Do nothing\n break;\n case 'transport close' :\n case 'ping timeout' :\n case 'transport error' : {\n this.#LogDebugMessage(`Server unexpectedly disconnected. Reason: [${reason}]`);\n this.#LogDebugMessage('The connection will be re-established when the server becomes available.');\n const socketDetail: ISocketDetail = this.sockets[name];\n if (socketDetail.socket) {\n socketDetail.socket.disconnect();\n }\n socketDetail.socket = null;\n if (isNode) {\n setTimeout(() => this.#EstablishSocketConnect(name, onConnectCallBack, socketEventsCallBack), 100).unref(); //@@ config\n } else {\n setTimeout(() => this.#EstablishSocketConnect(name, onConnectCallBack, socketEventsCallBack), 100); //@@ config\n }\n }\n break;\n }\n });\n }\n}\n","/* eslint @typescript-eslint/no-explicit-any: 0, @typescript-eslint/no-unused-vars: 0 */ // --> OFF\nimport { JSONObject } from '@nsshunt/stsutils'\n\nimport { Server, Namespace, Socket } from \"socket.io\";\n\nimport { STSDefaultClientToServerEvents, STSDefaultServerToClientEvents, STSServerSocket, ISocketIoServerHelper,\n ISocketIoServerHelperOptions, STSSocketIONamespace, STSSocketIONamespaces, STSNamespace,\n InterServerEvents, ServerEventCb } from './commonTypes'\n\nexport class SocketIoServerHelper<ClientToServerEvents extends STSDefaultClientToServerEvents, ServerToClientEvents extends STSDefaultServerToClientEvents> implements ISocketIoServerHelper<ClientToServerEvents, ServerToClientEvents>\n{\n #socketIoServerHelperOptions: ISocketIoServerHelperOptions\n #namespace: STSSocketIONamespaces = { };\n\n constructor(options: ISocketIoServerHelperOptions) { // IProcessBase\n this.#socketIoServerHelperOptions = options;\n }\n\n LogMessage(namespace: STSSocketIONamespace, message: any) {\n this.#socketIoServerHelperOptions.logger.debug(`${namespace.namespace}: ${message}`);\n }\n\n LeaveRoom = (namespace: STSSocketIONamespace, socket: Socket<ClientToServerEvents, ServerToClientEvents>, room: string): void => {\n this.LogMessage(namespace, `${namespace.socketionamespace.name}: Leaving room [${room}]`);\n socket.leave(room);\n };\n\n JoinRoom = (namespace: STSSocketIONamespace, socket: Socket<ClientToServerEvents, ServerToClientEvents>, room: string): void => {\n this.LogMessage(namespace, `${namespace.socketionamespace.name}: Socket joining room [${room}], ID: [${socket.id}]`);\n socket.join(room);\n };\n\n #SetupStandardEvents = (namespace: STSSocketIONamespace, socket: Socket<STSDefaultClientToServerEvents, STSDefaultServerToClientEvents>): void => {\n socket.on('disconnect', (reason: string) => {\n this.LogMessage(namespace, `${namespace.socketionamespace.name}: socket disconnect, ID: [${socket.id}] [${reason}]`);\n });\n\n socket.on('disconnecting', (reason: string) => {\n this.LogMessage(namespace, `${namespace.socketionamespace.name}: socket disconnecting, ID: [${socket.id}] [${reason}]`);\n });\n\n socket.on('error', (error: Error) => {\n this.LogMessage(namespace, `${namespace.socketionamespace.name}: socket error, ID: [${socket.id}] [${error}]`);\n });\n\n socket.on(\"__STSdisconnect\", (reason: string) => {\n this.LogMessage(namespace, `${namespace.socketionamespace.name}: __STSdisconnect: socket disconnect, ID: [${socket.id}] [${reason}]`);\n });\n\n socket.on(\"__STSdisconnecting\", (reason, callBackResult) => {\n this.LogMessage(namespace, `${namespace.socketionamespace.name}: __STSdisconnecting: socket disconnecting, ID: [${socket.id}] [${reason}]`);\n callBackResult(\"__STSdisconnecting accepted by server.\");\n });\n\n socket.on('__STSjoinRoom', (rooms: string[]): void => { //@@ names\n rooms.forEach((room) => {\n this.JoinRoom(namespace, socket, room)\n });\n });\n\n socket.on('__STSleaveRoom', (rooms: string[]): void => { //@@ names\n rooms.forEach((room) => {\n this.LeaveRoom(namespace, socket, room);\n });\n });\n\n socket.on('__STSsendToRoom', (rooms: string[], payload: { command: string, payload: JSONObject }): void => {\n rooms.forEach((room) => {\n this.LogMessage(namespace, `${namespace.socketionamespace.name}:socket.on:sendToRoom: __STSsendToRoom: Sending to room [${room}], ID: [${socket.id}]`);\n \n namespace.socketionamespace.to(room).emit(payload.command as any, payload);\n });\n });\n }\n\n // Use this middleward to check every incomming connection\n #SetupConnectionMiddleware = (nameSpace: STSSocketIONamespace) => {\n nameSpace.socketionamespace.use((socket, next) => {\n //if (isValid(socket.request)) {\n const a=5; // for lint purposes\n if (a === 5) {\n next();\n } else {\n next(new Error(\"invalid\"));\n }\n });\n }\n\n // Use this middleware to check very packet being received\n #SetupMessageMiddleware = (socket: STSServerSocket) => {\n socket.use(([event, ...args], next) => {\n /*\n if (isUnauthorized(event)) {\n return next(new Error(\"unauthorized event\"));\n }\n */\n next();\n });\n }\n \n SetupNamespace = (io: Server, namespace: STSNamespace, rooms: string[], autoJoinRooms: boolean, /* serverSocketEvents: ServerSocketEvent[], */\n socketConnectCallBack: ((socket: Socket<ClientToServerEvents, ServerToClientEvents, InterServerEvents>) => void) | null,\n socketEventsCallBack: ((socket: Socket<ClientToServerEvents, ServerToClientEvents, InterServerEvents>) => void) | null\n ): Namespace<ClientToServerEvents, ServerToClientEvents, InterServerEvents> => {\n // Create STS Command Centre Client namespace\n this.#namespace[namespace] = {\n namespace: namespace,\n pid: process.pid,\n socketionamespace: io.of(`/${namespace}/`)\n }\n\n this.#SetupConnectionMiddleware(this.#namespace[namespace]);\n\n this.#namespace[namespace].socketionamespace.on(\"connection\", socket => {\n this.LogMessage(this.#namespace[namespace], `${namespace}: Socket connected, ID: [${socket.id}]`);\n this.LogMessage(this.#namespace[namespace], `${namespace}: Authentication Handshake: [${JSON.stringify(socket.handshake.auth)}]`);\n\n this.#SetupMessageMiddleware(socket);\n\n if (autoJoinRooms) {\n rooms.map((room) => {\n this.JoinRoom(this.#namespace[namespace], socket, room);\n });\n }\n\n this.#SetupStandardEvents(this.#namespace[namespace], socket);\n\n if (socketConnectCallBack) {\n setTimeout(() => {\n socketConnectCallBack(socket);\n }, 0);\n }\n\n if (socketEventsCallBack) {\n socketEventsCallBack(socket);\n }\n });\n\n return this.#namespace[namespace].socketionamespace as Namespace<ClientToServerEvents, ServerToClientEvents, InterServerEvents>;\n }\n\n GetSTSSocketIONamespace = (namespace: string): STSSocketIONamespace => {\n return this.#namespace[namespace];\n }\n\n GetSTSSocketIONamespaces = (): STSSocketIONamespaces => {\n return this.#namespace;\n }\n\n CloseAdaptors = async (): Promise<void> => {\n for (const [, namespace] of Object.entries(this.#namespace)) {\n await namespace.socketionamespace.adapter.close();\n }\n }\n\n DisconnectSockets = (): void => {\n for (const [, namespace] of Object.entries(this.#namespace)) {\n namespace.socketionamespace.disconnectSockets();\n }\n this.#namespace = { };\n }\n\n SetupEvent(event: ClientToServerEvents, eventCb: ServerEventCb): ISocketIoServerHelper<ClientToServerEvents, ServerToClientEvents> {\n return this as any;\n }\n}\n"],"names":["STSNamespace","STSRoom","STSEvent","AgentManager","io","socketDetail"],"mappings":";;;;;;;;;;;;;;;;AAiEY,MAAA,iCAAAA,kBAAL;AACNA,kBAAA,YAAa,IAAA;AACbA,kBAAA,YAAa,IAAA;AAFFA,WAAAA;AAAAA,EAAA,GAAA,gBAAA,CAAA,CAAA;AAKA,MAAA,4BAAAC,aAAL;AAENA,aAAA,uBAAwB,IAAA;AACxBA,aAAA,mCAAoC,IAAA;AAGpCA,aAAA,eAAgB,IAAA;AAChBA,aAAA,mBAAoB,IAAA;AAPTA,WAAAA;AAAAA,EAAA,GAAA,WAAA,CAAA,CAAA;AAUA,MAAA,6BAAAC,cAAL;AAENA,cAAA,mBAAoB,IAAA;AACpBA,cAAA,sBAAuB,IAAA;AACvBA,cAAA,wBAAyB,IAAA;AAEzBA,cAAA,+BAAgC,IAAA;AAChCA,cAAA,8BAA+B,IAAA;AAG/BA,cAAA,UAAW,IAAA;AACXA,cAAA,SAAU,IAAA;AACVA,cAAA,UAAW,IAAA;AACXA,cAAA,WAAY,IAAA;AACZA,cAAA,cAAe,IAAA;AAGfA,cAAA,uBAAwB,IAAA;AACxBA,cAAA,wBAAyB,IAAA;AAGzBA,cAAA,eAAgB,IAAA;AAGhBA,cAAA,SAAU,IAAA;AAxBCA,WAAAA;AAAAA,EAAA,GAAA,YAAA,CAAA,CAAA;AC/EZ,QAAA,SAAe,OAAO,UAAU,SAAS,KAAK,OAAO,YAAY,cAAc,UAAU,CAAC,MAAM;AAAA,ECmDzF,MAAM,qBACb;AAAA,IAKI,YAAY,SAAuC;AANhD;AAEH;AACA,mCAA0C,CAAE;AAC5C,wCAAqC;AAG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mBAAK,WAAU,GAAG;AACnD,gBAAA,UAAU,kBAAkB,QAAQ,MAAM;AAAA,QAAA;AAAA,MAExD;AAEA,+CAAoB,MAAY;AACjB,mBAAA,CAAG,EAAA,SAAS,KAAK,OAAO,QAAQ,mBAAK,WAAU,GAAG;AACzD,oBAAU,kBAAkB,kBAAkB;AAAA,QAAA;AAElD,2BAAK,YAAa,CAAE;AAAA,MACxB;AAjJI,yBAAK,8BAA+B;AAAA,IAAA;AAAA,IAGxC,WAAW,WAAiC,SAAc;AACjD,yBAAA,8BAA6B,OAAO,MAAM,GAAG,UAAU,SAAS,KAAK,OAAO,EAAE;AAAA,IAAA;AAAA,IA+IvF,WAAW,OAA6B,SAA2F;AACxH,aAAA;AAAA,IAAA;AAAA,EAEf;AA1JI;AACA;AAoBA;AA4CA;AAaA;;;;;;;;","x_google_ignoreList":[1]}
package/package.json ADDED
@@ -0,0 +1,73 @@
1
+ {
2
+ "name": "@nsshunt/stssocketioutils",
3
+ "version": "1.0.1",
4
+ "description": "STS Socket.IO Utils",
5
+ "main": "./dist/stssocketioutils.umd.js",
6
+ "module": "./dist/stssocketioutils.mjs",
7
+ "type": "commonjs",
8
+ "types": "./types/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "import": "./dist/stssocketioutils.mjs",
12
+ "require": "./dist/stssocketioutils.umd.js"
13
+ }
14
+ },
15
+ "files": [
16
+ "dist",
17
+ "types",
18
+ "LICENSE",
19
+ "README.md"
20
+ ],
21
+ "scripts": {
22
+ "lint": "eslint .",
23
+ "lintex": "eslint . --fix",
24
+ "test": "DEBUG=testcontainers:containers vitest run --reporter verbose --pool forks",
25
+ "test2": "jest --detectOpenHandles --no-cache",
26
+ "testwatch": "jest --watchAll --detectOpenHandles --no-cache",
27
+ "build": "tsc && vite build",
28
+ "build2": "tsc"
29
+ },
30
+ "repository": {
31
+ "type": "git",
32
+ "url": "git+https://github.com/nsshunt/stssocketioutils.git"
33
+ },
34
+ "author": "STS",
35
+ "license": "MIT",
36
+ "bugs": {
37
+ "url": "https://github.com/nsshunt/stssocketioutils/issues"
38
+ },
39
+ "homepage": "https://github.com/nsshunt/stssocketioutils#readme",
40
+ "devDependencies": {
41
+ "@babel/preset-env": "^7.26.0",
42
+ "@babel/preset-typescript": "^7.26.0",
43
+ "@eslint/eslintrc": "^3.1.0",
44
+ "@eslint/js": "^9.14.0",
45
+ "@tsconfig/node20": "^20.1.4",
46
+ "@types/detect-node": "^2.0.2",
47
+ "@types/uuid": "^10.0.0",
48
+ "@typescript-eslint/eslint-plugin": "^8.13.0",
49
+ "@typescript-eslint/parser": "^8.13.0",
50
+ "eslint": "^9.14.0",
51
+ "globals": "^15.12.0",
52
+ "jest": "^29.7.0",
53
+ "testcontainers": "^10.14.0",
54
+ "typescript": "^5.6.3",
55
+ "vite": "^5.4.10",
56
+ "vitest": "^2.1.4"
57
+ },
58
+ "dependencies": {
59
+ "@nsshunt/stsconfig": "^1.25.167",
60
+ "@nsshunt/stsutils": "^1.16.91",
61
+ "@socket.io/cluster-adapter": "^0.2.2",
62
+ "@socket.io/redis-adapter": "^8.3.0",
63
+ "@socket.io/redis-streams-adapter": "^0.2.2",
64
+ "chalk": "^4.1.2",
65
+ "detect-node": "^2.1.0",
66
+ "ioredis": "^5.4.1",
67
+ "redis": "^4.7.0",
68
+ "socket.io": "^4.8.1",
69
+ "socket.io-client": "^4.8.1",
70
+ "uuid": "^10.0.0",
71
+ "winston": "^3.16.0"
72
+ }
73
+ }
@@ -0,0 +1,105 @@
1
+ import { Server, Socket, Namespace } from "socket.io";
2
+ import { ISTSLogger } from '@nsshunt/stsutils';
3
+ export interface STSDefaultClientToServerEvents {
4
+ /**
5
+ * Join the room(s) specified for this client.
6
+ * @param room The room(s) to join for this client.
7
+ * @returns
8
+ */
9
+ __STSjoinRoom: (room: string[]) => void;
10
+ /**
11
+ * Remove this client from the specified room(s).
12
+ * @param room The room(s) to remove the client from within the server.
13
+ * @returns
14
+ */
15
+ __STSleaveRoom: (room: string[]) => void;
16
+ /**
17
+ * Alerts the server that this client has flagged to disconnect. Allows server to perform clean-up if required. The server must call-back with the result of the disconnecting event.
18
+ * @param reason Reason for the disconnecting event.
19
+ * @param callback The server must call-back with the result of the disconnecting event.
20
+ * @returns
21
+ */
22
+ __STSdisconnecting: (reason: string, callback: (data: string) => void) => void;
23
+ /**
24
+ * Alerts the server to disconnect this client.
25
+ * @param reason Reason for the disconnect event.
26
+ * @returns
27
+ */
28
+ __STSdisconnect: (reason: string) => void;
29
+ /**
30
+ * Send a payload of data to 1 or more rooms registered on the server.
31
+ * @param rooms Room array for broadcasting.
32
+ * @param payload The data to be sent to every client within each of the rooms provided. The command within the payload must be a valid STSServerToClientEvents event. This includes any
33
+ * interface that extends STSServerToClientEvents.
34
+ * @returns
35
+ */
36
+ __STSsendToRoom: (rooms: string[], payload: {
37
+ command: string;
38
+ payload: any;
39
+ }) => void;
40
+ }
41
+ export interface STSDefaultServerToClientEvents {
42
+ /**
43
+ * The server may emit an unsolicited disconnect event to flag that all clients should disconnect. Most likely becuase the server may be shutting down.
44
+ * @param reason Reason why the server is emitting this disconnect event.
45
+ * @returns
46
+ */
47
+ __STSdisconnect: (reason: string) => void;
48
+ }
49
+ export interface ISocketIoServerHelperOptions {
50
+ logger: ISTSLogger;
51
+ }
52
+ export type ServerEventCb = (socket: any, data: any) => void;
53
+ export interface ServerSocketEvent {
54
+ serverEventName: string;
55
+ serverEventCb: ServerEventCb;
56
+ }
57
+ export declare enum STSNamespace {
58
+ STSMonitor = "stsinstrumentmanager/stsmonitor",
59
+ STSControl = "stsinstrumentmanager/stscontrol"
60
+ }
61
+ export declare enum STSRoom {
62
+ STSInstrumentDataRoom = "stsinstrumentdataroom",// This room is for all instrument data messages
63
+ STSInstrumentDataSubscriptionRoom = "stsinstrumentdatasubscriptionroom",// This room is only for subscribed instrument data messages
64
+ STSRunnerRoom = "stsrunnerroom",
65
+ STSNodeRunnerRoom = "stsnoderunnerroom"
66
+ }
67
+ export declare enum STSEvent {
68
+ STSInstrumentData = "stsinstrumentdata",
69
+ STSSubInstrumentData = "stssubinstrumentdata",// sub-scribed instrument data. This only outputs the nodes that have been subscribed by the client(s).
70
+ STSResetInstrumentData = "stsresetinstrumentdata",
71
+ STSStartLoggingInstrumentData = "stsStartLoggingInstrumentData",
72
+ STSStopLoggingInstrumentData = "stsStopLoggingInstrumentData",
73
+ STSStart = "stsstart",// Start a test run with options as payload.
74
+ STSStop = "stsstop",// Stop test run(s).
75
+ STSPause = "stspause",// Pause test run(s).
76
+ STSResume = "stsresume",// Resume test run(s).
77
+ STSTerminate = "ststerminate",// Terminate runner instances and exit applications.
78
+ STSUpdateStaticConfig = "stsupdatestaticconfig",// Update base configuration. Options as payload.
79
+ STSUpdateDynamicConfig = "stsupdatedynamicconfig",// Update running configuration. This is used
80
+ STSSendToRoom = "sendToRoom",
81
+ connect = "connect"
82
+ }
83
+ export interface InterServerEvents {
84
+ ping: () => void;
85
+ }
86
+ export interface STSSocketIONamespace {
87
+ namespace: string;
88
+ pid: number;
89
+ socketionamespace: Namespace<STSDefaultClientToServerEvents, STSDefaultServerToClientEvents, InterServerEvents>;
90
+ }
91
+ export type STSSocketIONamespaces = Record<string, STSSocketIONamespace>;
92
+ export type STSServerSocket = Socket<STSDefaultClientToServerEvents, STSDefaultServerToClientEvents, InterServerEvents>;
93
+ export type STSClientSocket = Socket<STSDefaultServerToClientEvents, STSDefaultClientToServerEvents, InterServerEvents>;
94
+ export interface ISocketIoServerHelper<ClientToServerEvents extends STSDefaultClientToServerEvents, ServerToClientEvents extends STSDefaultServerToClientEvents> {
95
+ LogMessage: (namespace: STSSocketIONamespace, message: string) => void;
96
+ LeaveRoom: (namespace: STSSocketIONamespace, socket: STSServerSocket, room: STSRoom) => void;
97
+ JoinRoom: (namespace: STSSocketIONamespace, socket: STSServerSocket, room: STSRoom) => void;
98
+ SetupNamespace: (io: Server, namespace: STSNamespace, rooms: string[], autoJoinRooms: boolean, socketConnectCallBack: ((socket: Socket<ClientToServerEvents, ServerToClientEvents, InterServerEvents>) => void) | null, socketEventsCallBack: ((socket: Socket<ClientToServerEvents, ServerToClientEvents, InterServerEvents>) => void) | null) => Namespace<ClientToServerEvents, ServerToClientEvents, InterServerEvents>;
99
+ GetSTSSocketIONamespace: (namespace: any) => STSSocketIONamespace;
100
+ GetSTSSocketIONamespaces: () => STSSocketIONamespaces;
101
+ DisconnectSockets: () => void;
102
+ CloseAdaptors: () => Promise<void>;
103
+ SetupEvent(event: ClientToServerEvents, eventCb: ServerEventCb): ISocketIoServerHelper<ClientToServerEvents, ServerToClientEvents>;
104
+ }
105
+ //# sourceMappingURL=commonTypes.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"commonTypes.d.ts","sourceRoot":"","sources":["../src/commonTypes.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AACtD,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAA;AAE9C,MAAM,WAAW,8BAA8B;IAC3C;;;;OAIG;IACN,aAAa,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,IAAI,CAAC;IAErC;;;;OAIG;IACN,cAAc,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,IAAI,CAAC;IAEtC;;;;;OAKG;IACN,kBAAkB,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,KAAK,IAAI,CAAC;IAE5E;;;;OAIG;IACN,eAAe,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,IAAI,CAAC;IAEvC;;;;;;OAMG;IAEN,eAAe,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,EAAE,OAAO,EAAE;QAAE,OAAO,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,GAAG,CAAA;KAAE,KAAK,IAAI,CAAC;CACvF;AAED,MAAM,WAAW,8BAA8B;IAC3C;;;;OAIG;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;IAC7B,aAAa,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAA;IAClC,UAAU,CAAC,KAAK,EAAE,oBAAoB,EAAE,OAAO,EAAE,aAAa,GAAG,qBAAqB,CAAC,oBAAoB,EAAE,oBAAoB,CAAC,CAAA;CACrI"}
@@ -0,0 +1,4 @@
1
+ export * from './commonTypes';
2
+ export * from './socketIoClientHelper';
3
+ export * from './socketIoServerHelper';
4
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,eAAe,CAAC;AAC9B,cAAc,wBAAwB,CAAC;AACvC,cAAc,wBAAwB,CAAC"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=index.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.test.d.ts","sourceRoot":"","sources":["../src/index.test.ts"],"names":[],"mappings":""}
@@ -0,0 +1,31 @@
1
+ import { Socket } from 'socket.io-client';
2
+ import { ISTSLogger } from '@nsshunt/stsutils';
3
+ import { STSDefaultClientToServerEvents, STSDefaultServerToClientEvents } from './commonTypes';
4
+ export type EventCb = (socket: any, data: any) => void;
5
+ export interface ISocketDetail {
6
+ name: string;
7
+ address: string;
8
+ socket: Socket | null;
9
+ errorCallBack: (error: Error) => void;
10
+ }
11
+ export interface ISocketIoClientHelperOptions {
12
+ url?: string;
13
+ agentOptions?: {
14
+ keepAlive: boolean;
15
+ maxSockets: number;
16
+ maxTotalSockets: number;
17
+ maxFreeSockets: number;
18
+ timeout: number;
19
+ rejectUnauthorized: boolean;
20
+ };
21
+ logger?: ISTSLogger;
22
+ }
23
+ export declare class SocketIoClientHelper<ServerToClientEvents extends STSDefaultServerToClientEvents, ClientToServerEvents extends STSDefaultClientToServerEvents> {
24
+ #private;
25
+ constructor(options: ISocketIoClientHelperOptions);
26
+ get sockets(): Record<string, ISocketDetail>;
27
+ SetupClientSideSocket(name: string, address: string, onConnectCallBack: ((socket: Socket<ServerToClientEvents, ClientToServerEvents>) => void) | null, socketEventsCallBack: ((socket: Socket<ServerToClientEvents, ClientToServerEvents>) => void) | null, errorCallBack: ((error: Error) => void)): Socket<ServerToClientEvents, ClientToServerEvents>;
28
+ GetSocket(name: string): Socket<ServerToClientEvents, ClientToServerEvents>;
29
+ GetSocketDetail(name: string): ISocketDetail;
30
+ }
31
+ //# sourceMappingURL=socketIoClientHelper.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"socketIoClientHelper.d.ts","sourceRoot":"","sources":["../src/socketIoClientHelper.ts"],"names":[],"mappings":"AAAA,OAAO,EAAqC,MAAM,EAAE,MAAM,kBAAkB,CAAA;AAI5E,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAA;AAE9C,OAAO,EAAE,8BAA8B,EAAE,8BAA8B,EAAE,MAAM,eAAe,CAAA;AAI9F,MAAM,MAAM,OAAO,GAAG,CAAC,MAAM,EAAE,GAAG,EAAE,IAAI,EAAE,GAAG,KAAK,IAAI,CAAA;AAoBtD,MAAM,WAAW,aAAa;IAC7B,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;IAEhB,MAAM,EAAE,MAAM,GAAG,IAAI,CAAA;IAClB,aAAa,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAA;CACxC;AAED,MAAM,WAAW,4BAA4B;IAEzC,GAAG,CAAC,EAAE,MAAM,CAAA;IACZ,YAAY,CAAC,EAAE;QACjB,SAAS,EAAE,OAAO,CAAC;QACnB,UAAU,EAAE,MAAM,CAAA;QAClB,eAAe,EAAE,MAAM,CAAC;QACxB,cAAc,EAAE,MAAM,CAAC;QACvB,OAAO,EAAE,MAAM,CAAC;QAChB,kBAAkB,EAAE,OAAO,CAAA;KAC3B,CAAA;IACE,MAAM,CAAC,EAAE,UAAU,CAAA;CACtB;AAED,qBAAa,oBAAoB,CAAC,oBAAoB,SAAS,8BAA8B,EAAE,oBAAoB,SAAS,8BAA8B;;gBAM1I,OAAO,EAAE,4BAA4B;IAmBjD,IAAI,OAAO,IAAI,MAAM,CAAC,MAAM,EAAE,aAAa,CAAC,CAE3C;IAED,qBAAqB,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAC/C,iBAAiB,EAAE,CAAC,CAAC,MAAM,EAAE,MAAM,CAAC,oBAAoB,EAAE,oBAAoB,CAAC,KAAK,IAAI,CAAC,GAAG,IAAI,EAChG,oBAAoB,EAAE,CAAC,CAAC,MAAM,EAAE,MAAM,CAAC,oBAAoB,EAAE,oBAAoB,CAAC,KAAK,IAAI,CAAC,GAAG,IAAI,EACnG,aAAa,EAAE,CAAC,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC,GACxC,MAAM,CAAC,oBAAoB,EAAE,oBAAoB,CAAC;IAWrD,SAAS,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAAC,oBAAoB,EAAE,oBAAoB,CAAC;IAI3E,eAAe,CAAC,IAAI,EAAE,MAAM,GAAG,aAAa;CA+G/C"}
@@ -0,0 +1,16 @@
1
+ import { Server, Namespace, Socket } from "socket.io";
2
+ import { STSDefaultClientToServerEvents, STSDefaultServerToClientEvents, ISocketIoServerHelper, ISocketIoServerHelperOptions, STSSocketIONamespace, STSSocketIONamespaces, STSNamespace, InterServerEvents, ServerEventCb } from './commonTypes';
3
+ export declare class SocketIoServerHelper<ClientToServerEvents extends STSDefaultClientToServerEvents, ServerToClientEvents extends STSDefaultServerToClientEvents> implements ISocketIoServerHelper<ClientToServerEvents, ServerToClientEvents> {
4
+ #private;
5
+ constructor(options: ISocketIoServerHelperOptions);
6
+ LogMessage(namespace: STSSocketIONamespace, message: any): void;
7
+ LeaveRoom: (namespace: STSSocketIONamespace, socket: Socket<ClientToServerEvents, ServerToClientEvents>, room: string) => void;
8
+ JoinRoom: (namespace: STSSocketIONamespace, socket: Socket<ClientToServerEvents, ServerToClientEvents>, room: string) => void;
9
+ SetupNamespace: (io: Server, namespace: STSNamespace, rooms: string[], autoJoinRooms: boolean, socketConnectCallBack: ((socket: Socket<ClientToServerEvents, ServerToClientEvents, InterServerEvents>) => void) | null, socketEventsCallBack: ((socket: Socket<ClientToServerEvents, ServerToClientEvents, InterServerEvents>) => void) | null) => Namespace<ClientToServerEvents, ServerToClientEvents, InterServerEvents>;
10
+ GetSTSSocketIONamespace: (namespace: string) => STSSocketIONamespace;
11
+ GetSTSSocketIONamespaces: () => STSSocketIONamespaces;
12
+ CloseAdaptors: () => Promise<void>;
13
+ DisconnectSockets: () => void;
14
+ SetupEvent(event: ClientToServerEvents, eventCb: ServerEventCb): ISocketIoServerHelper<ClientToServerEvents, ServerToClientEvents>;
15
+ }
16
+ //# sourceMappingURL=socketIoServerHelper.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"socketIoServerHelper.d.ts","sourceRoot":"","sources":["../src/socketIoServerHelper.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AAEtD,OAAO,EAAE,8BAA8B,EAAE,8BAA8B,EAAmB,qBAAqB,EAC3G,4BAA4B,EAAE,oBAAoB,EAAE,qBAAqB,EAAE,YAAY,EACvF,iBAAiB,EAAE,aAAa,EAAE,MAAM,eAAe,CAAA;AAE3D,qBAAa,oBAAoB,CAAC,oBAAoB,SAAS,8BAA8B,EAAE,oBAAoB,SAAS,8BAA8B,CAAE,YAAW,qBAAqB,CAAC,oBAAoB,EAAE,oBAAoB,CAAC;;gBAKxN,OAAO,EAAE,4BAA4B;IAIjD,UAAU,CAAC,SAAS,EAAE,oBAAoB,EAAE,OAAO,EAAE,GAAG;IAIxD,SAAS,cAAe,oBAAoB,UAAU,MAAM,CAAC,oBAAoB,EAAE,oBAAoB,CAAC,QAAQ,MAAM,KAAG,IAAI,CAG3H;IAEF,QAAQ,cAAe,oBAAoB,UAAU,MAAM,CAAC,oBAAo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