underpost 3.1.3 → 3.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/.env.example +0 -2
  2. package/.github/workflows/ghpkg.ci.yml +4 -4
  3. package/.github/workflows/npmpkg.ci.yml +28 -11
  4. package/.github/workflows/publish.ci.yml +6 -0
  5. package/.github/workflows/pwa-microservices-template-page.cd.yml +4 -5
  6. package/.github/workflows/pwa-microservices-template-test.ci.yml +3 -3
  7. package/.github/workflows/release.cd.yml +13 -8
  8. package/CHANGELOG.md +396 -1
  9. package/CLI-HELP.md +53 -6
  10. package/Dockerfile +4 -2
  11. package/README.md +3 -2
  12. package/bin/build.js +18 -12
  13. package/bin/deploy.js +177 -124
  14. package/bin/file.js +3 -0
  15. package/conf.js +3 -2
  16. package/manifests/cronjobs/dd-cron/dd-cron-backup.yaml +5 -2
  17. package/manifests/cronjobs/dd-cron/dd-cron-dns.yaml +5 -2
  18. package/manifests/deployment/dd-default-development/deployment.yaml +2 -2
  19. package/manifests/deployment/dd-test-development/deployment.yaml +88 -74
  20. package/manifests/deployment/dd-test-development/proxy.yaml +13 -4
  21. package/manifests/deployment/playwright/deployment.yaml +1 -1
  22. package/nodemon.json +1 -1
  23. package/package.json +22 -15
  24. package/scripts/rhel-grpc-setup.sh +56 -0
  25. package/src/api/file/file.ref.json +18 -0
  26. package/src/api/user/user.service.js +8 -7
  27. package/src/cli/cluster.js +7 -7
  28. package/src/cli/db.js +726 -825
  29. package/src/cli/deploy.js +151 -93
  30. package/src/cli/env.js +19 -0
  31. package/src/cli/fs.js +5 -2
  32. package/src/cli/index.js +45 -2
  33. package/src/cli/kubectl.js +211 -0
  34. package/src/cli/release.js +284 -0
  35. package/src/cli/repository.js +434 -75
  36. package/src/cli/run.js +189 -34
  37. package/src/cli/secrets.js +73 -0
  38. package/src/cli/test.js +3 -3
  39. package/src/client/Default.index.js +3 -4
  40. package/src/client/components/core/AppStore.js +69 -0
  41. package/src/client/components/core/CalendarCore.js +2 -2
  42. package/src/client/components/core/DropDown.js +137 -17
  43. package/src/client/components/core/Keyboard.js +2 -2
  44. package/src/client/components/core/LogIn.js +2 -2
  45. package/src/client/components/core/LogOut.js +2 -2
  46. package/src/client/components/core/Modal.js +0 -1
  47. package/src/client/components/core/Panel.js +0 -1
  48. package/src/client/components/core/PanelForm.js +19 -19
  49. package/src/client/components/core/SocketIo.js +82 -29
  50. package/src/client/components/core/SocketIoHandler.js +75 -0
  51. package/src/client/components/core/Stream.js +143 -95
  52. package/src/client/components/core/Webhook.js +40 -7
  53. package/src/client/components/default/AppStoreDefault.js +5 -0
  54. package/src/client/components/default/LogInDefault.js +3 -3
  55. package/src/client/components/default/LogOutDefault.js +2 -2
  56. package/src/client/components/default/MenuDefault.js +5 -5
  57. package/src/client/components/default/SocketIoDefault.js +3 -51
  58. package/src/client/services/core/core.service.js +20 -8
  59. package/src/client/services/user/user.management.js +2 -2
  60. package/src/index.js +24 -1
  61. package/src/runtime/express/Dockerfile +4 -0
  62. package/src/runtime/express/Express.js +18 -1
  63. package/src/runtime/lampp/Dockerfile +13 -2
  64. package/src/runtime/lampp/Lampp.js +27 -4
  65. package/src/runtime/wp/Dockerfile +68 -0
  66. package/src/runtime/wp/Wp.js +639 -0
  67. package/src/server/auth.js +24 -1
  68. package/src/server/backup.js +57 -23
  69. package/src/server/client-build-docs.js +9 -2
  70. package/src/server/client-build.js +31 -31
  71. package/src/server/client-formatted.js +109 -57
  72. package/src/server/cron.js +23 -18
  73. package/src/server/ipfs-client.js +24 -1
  74. package/src/server/peer.js +8 -0
  75. package/src/server/runtime.js +25 -1
  76. package/src/server/start.js +3 -2
  77. package/src/ws/IoInterface.js +1 -10
  78. package/src/ws/IoServer.js +14 -33
  79. package/src/ws/core/channels/core.ws.chat.js +65 -20
  80. package/src/ws/core/channels/core.ws.mailer.js +113 -32
  81. package/src/ws/core/channels/core.ws.stream.js +90 -31
  82. package/src/ws/core/core.ws.connection.js +12 -33
  83. package/src/ws/core/core.ws.emit.js +10 -26
  84. package/src/ws/core/core.ws.server.js +25 -58
  85. package/src/ws/default/channels/default.ws.main.js +53 -12
  86. package/src/ws/default/default.ws.connection.js +26 -13
  87. package/src/ws/default/default.ws.server.js +30 -12
  88. package/src/client/components/default/ElementsDefault.js +0 -38
  89. package/src/ws/core/management/core.ws.chat.js +0 -8
  90. package/src/ws/core/management/core.ws.mailer.js +0 -16
  91. package/src/ws/core/management/core.ws.stream.js +0 -8
  92. package/src/ws/default/management/default.ws.main.js +0 -8
@@ -11,6 +11,7 @@ import * as promClient from 'prom-client';
11
11
  import { loggerFactory } from './logger.js';
12
12
  import { newInstance } from '../client/components/core/CommonJs.js';
13
13
  import { Lampp } from '../runtime/lampp/Lampp.js';
14
+ import { WpService } from '../runtime/wp/Wp.js';
14
15
  import { getInstanceContext, readConfJson } from './conf.js';
15
16
 
16
17
  import ExpressService from '../runtime/express/Express.js';
@@ -71,6 +72,9 @@ const buildRuntime = async () => {
71
72
  valkey,
72
73
  apiBaseHost,
73
74
  useLocalSsl,
75
+ grpc,
76
+ repository,
77
+ wp,
74
78
  } = confServer[host][path];
75
79
 
76
80
  // Calculate context data
@@ -116,6 +120,7 @@ const buildRuntime = async () => {
116
120
  peer,
117
121
  valkey,
118
122
  apiBaseHost,
123
+ grpc,
119
124
  redirectTarget,
120
125
  rootHostPath,
121
126
  confSSR,
@@ -129,7 +134,7 @@ const buildRuntime = async () => {
129
134
 
130
135
  case 'lampp':
131
136
  {
132
- const { disabled } = await Lampp.createApp({
137
+ const { disabled } = Lampp.createApp({
133
138
  port,
134
139
  host,
135
140
  path,
@@ -143,6 +148,25 @@ const buildRuntime = async () => {
143
148
  await Underpost.start.listenPortController(Underpost.start.listenServerFactory(), port, runningData);
144
149
  }
145
150
  break;
151
+
152
+ case 'wp':
153
+ {
154
+ const { disabled } = WpService.createApp({
155
+ port,
156
+ host,
157
+ pathRoute: path,
158
+ repository,
159
+ db,
160
+ wp,
161
+ redirect,
162
+ redirectTarget,
163
+ resetRouter: currentPort === initPort,
164
+ });
165
+ if (disabled) continue;
166
+ await Underpost.start.listenPortController(Underpost.start.listenServerFactory(), port, runningData);
167
+ }
168
+ break;
169
+
146
170
  default:
147
171
  break;
148
172
  }
@@ -9,6 +9,7 @@ import { awaitDeployMonitor } from './conf.js';
9
9
  import { actionInitLog, loggerFactory } from './logger.js';
10
10
  import { shellCd, shellExec } from './process.js';
11
11
  import Underpost from '../index.js';
12
+ import isInsideContainer from 'is-inside-container';
12
13
  const logger = loggerFactory(import.meta);
13
14
 
14
15
  /**
@@ -163,10 +164,9 @@ class UnderpostStartUp {
163
164
  shellExec(`mkdir -p ${buildBasePath}/engine`);
164
165
  shellExec(`cd ${buildBasePath} && sudo cp -a ./${repoName}/. ./engine`);
165
166
  shellExec(`cd ${buildBasePath} && sudo rm -rf ./${repoName}`);
166
- shellExec(`cd ${buildBasePath}/engine && underpost clone ${process.env.GITHUB_USERNAME}/${repoName}-private`);
167
- shellExec(`cd ${buildBasePath}/engine && sudo mv ./${repoName}-private ./engine-private`);
168
167
  }
169
168
  shellCd(`${buildBasePath}/engine`);
169
+ Underpost.repo.privateEngineRepoFactory(deployId);
170
170
  shellExec(options?.underpostQuicklyInstall ? `underpost install` : `npm install`);
171
171
  shellExec(`node bin env ${deployId} ${env}`);
172
172
  if (fs.existsSync('./engine-private/itc-scripts')) {
@@ -197,6 +197,7 @@ class UnderpostStartUp {
197
197
  shellExec(`node bin env ${deployId} ${env}`);
198
198
  shellExec(`npm ${runCmd} ${deployId}`, { async: true });
199
199
  await awaitDeployMonitor(true);
200
+ if (env === 'production' && isInsideContainer()) Underpost.secret.globalSecretClean();
200
201
  Underpost.env.set('container-status', `${deployId}-${env}-running-deployment`);
201
202
  },
202
203
  };
@@ -126,13 +126,4 @@ class IoChannel {
126
126
  }
127
127
  }
128
128
 
129
- /**
130
- * Backward compatibility function to create a new channel instance.
131
- * @memberof SocketIoInterface
132
- * @function IoCreateChannel
133
- * @param {ChannelInterface} IoInterface - The interface object defining the channel's behavior.
134
- * @returns {IoChannel} An instance of the IoChannel class.
135
- */
136
- const IoCreateChannel = (IoInterface) => new IoChannel(IoInterface);
137
-
138
- export { IoChannel, IoCreateChannel };
129
+ export { IoChannel };
@@ -1,7 +1,6 @@
1
1
  /**
2
2
  * Module for creating and managing WebSocket servers.
3
- * @module src/ws/IoServer
4
- * @namespace SocketIoServer
3
+ * @module ws/IoServer
5
4
  */
6
5
 
7
6
  'use strict';
@@ -9,33 +8,27 @@
9
8
  import { Server } from 'socket.io';
10
9
  import { loggerFactory } from '../server/logger.js';
11
10
  import Underpost from '../index.js';
12
- import http from 'http';
13
11
 
14
12
  const logger = loggerFactory(import.meta);
15
13
 
16
14
  /**
17
- * @class IoServerClass
18
- * @alias IoServerClass
19
- * @memberof SocketIoServer
20
- * @classdesc Provides a static factory method to create and configure a Socket.IO server,
21
- * encapsulating WebSocket server initialization logic and CORS configuration.
15
+ * @class IoServer
16
+ * @classdesc Factory for creating and configuring Socket.IO server instances
17
+ * with CORS configuration and HTTP server attachment.
22
18
  */
23
- class IoServerClass {
19
+ class IoServer {
24
20
  /**
25
21
  * Creates a new WebSocket server instance attached to an HTTP server.
26
22
  *
27
23
  * @static
28
- * @param {http.Server} httpServer - The HTTP server instance to attach the WebSocket server to.
29
- * @param {Object} options - Configuration options for the WebSocket server.
30
- * @param {string[]} options.origins - List of allowed origins for Cross-Origin Resource Sharing (CORS).
31
- * @param {string} options.path - The base path for the API. The WebSocket path ('/socket.io') will be appended to this.
32
- * @param {function(import('socket.io').Socket): void} ConnectionHandler - The connection handler function to be executed on a new connection.
33
- * @returns {Object} An object containing the final options and the server instance.
34
- * @returns {import('socket.io').ServerOptions} return.options - The final options object used to create the WebSocket server.
35
- * @returns {import('socket.io').Server} return.ioServer - The created and listening WebSocket server instance.
36
- * @returns {object} return.meta - The module's import meta object (`import.meta`).
24
+ * @param {import('http').Server} httpServer - The HTTP server instance to attach to.
25
+ * @param {Object} options - Configuration options.
26
+ * @param {string[]} options.origins - Allowed CORS origins.
27
+ * @param {string} options.path - Base API path. Socket.IO path is appended automatically.
28
+ * @param {function(import('socket.io').Socket): void} connectionHandler - Handler for new connections.
29
+ * @returns {{ options: import('socket.io').ServerOptions, ioServer: import('socket.io').Server, meta: ImportMeta }}
37
30
  */
38
- static create(httpServer, options = {}, ConnectionHandler = () => {}) {
31
+ static create(httpServer, options = {}, connectionHandler = () => {}) {
39
32
  logger.info('origins', options.origins);
40
33
  const wsOptions = {
41
34
  cors: {
@@ -55,12 +48,11 @@ class IoServerClass {
55
48
  ],
56
49
  credentials: true,
57
50
  },
58
- // Ensure the path ends correctly, appending '/socket.io/'
59
51
  path: options.path !== '/' ? `${options.path}/socket.io/` : '/socket.io/',
60
52
  };
61
53
 
62
54
  const ioServerInstance = Underpost.start.listenServerFactory(() =>
63
- new Server(httpServer, wsOptions).on('connection', ConnectionHandler),
55
+ new Server(httpServer, wsOptions).on('connection', connectionHandler),
64
56
  );
65
57
 
66
58
  logger.info('Socket.IO Server created and listening', { path: wsOptions.path });
@@ -73,15 +65,4 @@ class IoServerClass {
73
65
  }
74
66
  }
75
67
 
76
- /**
77
- * Backward compatibility export for the server creation function.
78
- * @memberof SocketIoServer
79
- * @function IoServer
80
- * @param {http.Server} httpServer - The HTTP server instance.
81
- * @param {Object} options - Configuration options.
82
- * @param {function(import('socket.io').Socket): void} ConnectionHandler - The connection handler function.
83
- * @returns {Object} The server configuration object.
84
- */
85
- const IoServer = IoServerClass.create;
86
-
87
- export { IoServerClass, IoServer };
68
+ export { IoServer };
@@ -1,23 +1,68 @@
1
- import { loggerFactory } from '../../../server/logger.js';
2
- import { IoCreateChannel } from '../../IoInterface.js';
3
- import { CoreWsEmit } from '../core.ws.emit.js';
4
-
5
- const channel = 'chat';
6
- const logger = loggerFactory(import.meta);
7
-
8
- const CoreWsChatController = {
9
- channel,
10
- controller: function (socket, client, payload, wsManagementId) {
11
- for (const socketId of Object.keys(client)) {
12
- if (socketId !== socket.id) {
13
- CoreWsEmit(channel, client[socketId], { id: socket.id, ...payload });
1
+ /**
2
+ * Chat WebSocket channel — broadcasts messages to all connected sockets except the sender.
3
+ * @module ws/core/channels/core.ws.chat
4
+ */
5
+
6
+ import { IoChannel } from '../../IoInterface.js';
7
+ import { CoreWsEmitter } from '../core.ws.emit.js';
8
+
9
+ /**
10
+ * @class CoreWsChatChannel
11
+ * @classdesc Manages the chat WebSocket channel with per-instance state.
12
+ * Broadcasts incoming messages to all other connected sockets.
13
+ */
14
+ class CoreWsChatChannel {
15
+ /** @type {Object.<string, Object>} Per-instance state keyed by wsManagementId. */
16
+ static #state = {};
17
+
18
+ /** @type {IoChannel} */
19
+ static #io = new IoChannel({
20
+ channel: 'chat',
21
+ controller(socket, client, payload, wsManagementId) {
22
+ for (const socketId of Object.keys(client)) {
23
+ if (socketId !== socket.id) {
24
+ CoreWsEmitter.emit('chat', client[socketId], { id: socket.id, ...payload });
25
+ }
14
26
  }
15
- }
16
- },
17
- connection: function (socket, client, wsManagementId) {},
18
- disconnect: function (socket, client, reason, wsManagementId) {},
19
- };
27
+ },
28
+ });
29
+
30
+ /** @returns {Object.<string, import('socket.io').Socket>} Connected sockets map. */
31
+ static get client() {
32
+ return this.#io.client;
33
+ }
34
+
35
+ /** @returns {string} Channel name. */
36
+ static get channel() {
37
+ return this.#io.channel;
38
+ }
39
+
40
+ /**
41
+ * Initializes state for a server instance.
42
+ * @param {string} wsManagementId - Unique server context ID.
43
+ */
44
+ static init(wsManagementId) {
45
+ this.#state[wsManagementId] = {};
46
+ }
47
+
48
+ /**
49
+ * Registers a socket connection.
50
+ * @param {import('socket.io').Socket} socket
51
+ * @param {string} wsManagementId
52
+ */
53
+ static connection(socket, wsManagementId) {
54
+ return this.#io.connection(socket, wsManagementId);
55
+ }
20
56
 
21
- const CoreWsChatChannel = IoCreateChannel(CoreWsChatController);
57
+ /**
58
+ * Handles socket disconnection.
59
+ * @param {import('socket.io').Socket} socket
60
+ * @param {string} reason
61
+ * @param {string} wsManagementId
62
+ */
63
+ static disconnect(socket, reason, wsManagementId) {
64
+ return this.#io.disconnect(socket, reason, wsManagementId);
65
+ }
66
+ }
22
67
 
23
- export { CoreWsChatChannel, CoreWsChatController };
68
+ export { CoreWsChatChannel };
@@ -1,35 +1,116 @@
1
- import { loggerFactory } from '../../../server/logger.js';
2
- import { IoCreateChannel } from '../../IoInterface.js';
3
- import { CoreWsMailerManagement } from '../management/core.ws.mailer.js';
4
-
5
- const channel = 'mailer';
6
- const logger = loggerFactory(import.meta);
7
-
8
- const CoreWsMailerController = {
9
- channel,
10
- controller: function (socket, client, payload, wsManagementId) {
11
- switch (payload.status) {
12
- case 'register-user':
13
- CoreWsMailerManagement.element[wsManagementId][socket.id] = {
14
- model: {
15
- user: payload.user,
16
- },
17
- };
18
- break;
19
- case 'unregister-user':
20
- delete CoreWsMailerManagement.element[wsManagementId][socket.id];
21
- break;
22
-
23
- default:
24
- break;
1
+ /**
2
+ * Mailer WebSocket channel — manages user↔socket bidirectional mapping
3
+ * for targeted real-time pushes (e.g. email confirmation notifications).
4
+ * @module ws/core/channels/core.ws.mailer
5
+ */
6
+
7
+ import { IoChannel } from '../../IoInterface.js';
8
+
9
+ /**
10
+ * @class CoreWsMailerChannel
11
+ * @classdesc Manages the mailer WebSocket channel with O(1) user↔socket lookup.
12
+ * Handles register/unregister messages and cleanup on disconnect.
13
+ */
14
+ class CoreWsMailerChannel {
15
+ /** @type {Object.<string, Object.<string, { model: { user: Object } }>>} Socket data keyed by `[wsManagementId][socketId]`. */
16
+ static #data = {};
17
+
18
+ /** @type {Object.<string, Object.<string, string>>} Reverse index: `[wsManagementId][userId]` → socketId. */
19
+ static #userIndex = {};
20
+
21
+ /** @type {IoChannel} */
22
+ static #io = new IoChannel({
23
+ channel: 'mailer',
24
+ controller(socket, client, payload, wsManagementId) {
25
+ switch (payload.status) {
26
+ case 'register-user':
27
+ CoreWsMailerChannel.setUser(wsManagementId, socket.id, payload.user);
28
+ break;
29
+ case 'unregister-user':
30
+ CoreWsMailerChannel.removeSocket(wsManagementId, socket.id);
31
+ break;
32
+ default:
33
+ break;
34
+ }
35
+ },
36
+ disconnect(socket, client, reason, wsManagementId) {
37
+ CoreWsMailerChannel.removeSocket(wsManagementId, socket.id);
38
+ },
39
+ });
40
+
41
+ /** @returns {Object.<string, import('socket.io').Socket>} Connected sockets map. */
42
+ static get client() {
43
+ return this.#io.client;
44
+ }
45
+
46
+ /** @returns {string} Channel name. */
47
+ static get channel() {
48
+ return this.#io.channel;
49
+ }
50
+
51
+ /**
52
+ * Initializes state for a server instance.
53
+ * @param {string} wsManagementId - Unique server context ID (`${host}${path}`).
54
+ */
55
+ static init(wsManagementId) {
56
+ this.#data[wsManagementId] = {};
57
+ this.#userIndex[wsManagementId] = {};
58
+ }
59
+
60
+ /**
61
+ * Registers a socket connection.
62
+ * @param {import('socket.io').Socket} socket
63
+ * @param {string} wsManagementId
64
+ */
65
+ static connection(socket, wsManagementId) {
66
+ return this.#io.connection(socket, wsManagementId);
67
+ }
68
+
69
+ /**
70
+ * Handles socket disconnection.
71
+ * @param {import('socket.io').Socket} socket
72
+ * @param {string} reason
73
+ * @param {string} wsManagementId
74
+ */
75
+ static disconnect(socket, reason, wsManagementId) {
76
+ return this.#io.disconnect(socket, reason, wsManagementId);
77
+ }
78
+
79
+ /**
80
+ * Registers a user↔socket mapping.
81
+ * @param {string} wsManagementId
82
+ * @param {string} socketId
83
+ * @param {Object} user - User data with `_id` property.
84
+ */
85
+ static setUser(wsManagementId, socketId, user) {
86
+ this.#data[wsManagementId][socketId] = { model: { user } };
87
+ if (user?._id) {
88
+ this.#userIndex[wsManagementId][user._id.toString()] = socketId;
89
+ }
90
+ }
91
+
92
+ /**
93
+ * Removes a socket entry and its reverse user index.
94
+ * @param {string} wsManagementId
95
+ * @param {string} socketId
96
+ */
97
+ static removeSocket(wsManagementId, socketId) {
98
+ const entry = this.#data[wsManagementId]?.[socketId];
99
+ if (entry?.model?.user?._id) {
100
+ delete this.#userIndex[wsManagementId][entry.model.user._id.toString()];
25
101
  }
26
- },
27
- connection: function (socket, client, wsManagementId) {},
28
- disconnect: function (socket, client, reason, wsManagementId) {
29
- delete CoreWsMailerManagement.element[wsManagementId][socket.id];
30
- },
31
- };
102
+ delete this.#data[wsManagementId]?.[socketId];
103
+ }
32
104
 
33
- const CoreWsMailerChannel = IoCreateChannel(CoreWsMailerController);
105
+ /**
106
+ * Finds the socket ID for a user (O(1) reverse index lookup).
107
+ * @param {string} wsManagementId
108
+ * @param {string} userId - The user `_id`.
109
+ * @returns {string|undefined} Socket ID, or `undefined` if not connected.
110
+ */
111
+ static getUserWsId(wsManagementId, userId) {
112
+ return this.#userIndex[wsManagementId]?.[userId];
113
+ }
114
+ }
34
115
 
35
- export { CoreWsMailerChannel, CoreWsMailerController };
116
+ export { CoreWsMailerChannel };
@@ -1,31 +1,90 @@
1
- import { loggerFactory } from '../../../server/logger.js';
2
- import { IoCreateChannel } from '../../IoInterface.js';
3
- import { CoreWsStreamManagement } from '../management/core.ws.stream.js';
4
-
5
- const channel = 'stream';
6
- const logger = loggerFactory(import.meta);
7
-
8
- const CoreWsStreamController = {
9
- channel,
10
- stream: true,
11
- controller: function (socket, client, payload, wsManagementId, args) {
12
- const [roomId, userId] = args;
13
- CoreWsStreamManagement.element[wsManagementId][socket.id] = args;
14
-
15
- socket.join(roomId); // Join the room
16
- socket.broadcast.emit(`${channel}-user-connected`, userId); // Tell everyone else in the room that we joined
17
- },
18
- connection: function (socket, client, wsManagementId) {
19
- CoreWsStreamManagement.element[wsManagementId][socket.id] = [];
20
- },
21
- disconnect: function (socket, client, reason, wsManagementId) {
22
- // Communicate the disconnection
23
- const [roomId, userId] = CoreWsStreamManagement.element[wsManagementId][socket.id];
24
- socket.broadcast.emit(`${channel}-user-disconnected`, userId);
25
- delete CoreWsStreamManagement.element[wsManagementId][socket.id];
26
- },
27
- };
28
-
29
- const CoreWsStreamChannel = IoCreateChannel(CoreWsStreamController);
30
-
31
- export { CoreWsStreamChannel, CoreWsStreamController };
1
+ /**
2
+ * Stream WebSocket channel — manages per-socket room membership and user tracking.
3
+ * @module ws/core/channels/core.ws.stream
4
+ */
5
+
6
+ import { IoChannel } from '../../IoInterface.js';
7
+
8
+ /**
9
+ * @class CoreWsStreamChannel
10
+ * @classdesc Manages the stream WebSocket channel. Each socket can join a room
11
+ * and broadcast connection/disconnection events to other room members.
12
+ */
13
+ class CoreWsStreamChannel {
14
+ /** @type {Object.<string, Object.<string, Array>>} Per-socket room/user args keyed by `[wsManagementId][socketId]`. */
15
+ static #state = {};
16
+
17
+ /** @type {IoChannel} */
18
+ static #io = new IoChannel({
19
+ channel: 'stream',
20
+ stream: true,
21
+ controller(socket, client, payload, wsManagementId, args) {
22
+ const [roomId, userId] = args;
23
+
24
+ // Collect existing users in the room before registering the new one
25
+ const existingUsers = [];
26
+ for (const entry of Object.values(CoreWsStreamChannel.#state[wsManagementId])) {
27
+ if (entry[0] === roomId && entry[1]) existingUsers.push(entry[1]);
28
+ }
29
+
30
+ CoreWsStreamChannel.#state[wsManagementId][socket.id] = args;
31
+ socket.join(roomId);
32
+ socket.to(roomId).emit('stream-user-connected', userId);
33
+
34
+ // Tell the joining user about everyone already in the room
35
+ if (existingUsers.length > 0) socket.emit('stream-existing-users', existingUsers);
36
+ },
37
+ connection(socket, client, wsManagementId) {
38
+ CoreWsStreamChannel.#state[wsManagementId][socket.id] = [];
39
+ },
40
+ disconnect(socket, client, reason, wsManagementId) {
41
+ const entry = CoreWsStreamChannel.#state[wsManagementId]?.[socket.id];
42
+ if (!entry || entry.length === 0) {
43
+ if (CoreWsStreamChannel.#state[wsManagementId]) delete CoreWsStreamChannel.#state[wsManagementId][socket.id];
44
+ return;
45
+ }
46
+ const [roomId, userId] = entry;
47
+ socket.to(roomId).emit('stream-user-disconnected', userId);
48
+ delete CoreWsStreamChannel.#state[wsManagementId][socket.id];
49
+ },
50
+ });
51
+
52
+ /** @returns {Object.<string, import('socket.io').Socket>} Connected sockets map. */
53
+ static get client() {
54
+ return this.#io.client;
55
+ }
56
+
57
+ /** @returns {string} Channel name. */
58
+ static get channel() {
59
+ return this.#io.channel;
60
+ }
61
+
62
+ /**
63
+ * Initializes state for a server instance.
64
+ * @param {string} wsManagementId - Unique server context ID (`${host}${path}`).
65
+ */
66
+ static init(wsManagementId) {
67
+ this.#state[wsManagementId] = {};
68
+ }
69
+
70
+ /**
71
+ * Registers a socket connection.
72
+ * @param {import('socket.io').Socket} socket
73
+ * @param {string} wsManagementId
74
+ */
75
+ static connection(socket, wsManagementId) {
76
+ return this.#io.connection(socket, wsManagementId);
77
+ }
78
+
79
+ /**
80
+ * Handles socket disconnection.
81
+ * @param {import('socket.io').Socket} socket
82
+ * @param {string} reason
83
+ * @param {string} wsManagementId
84
+ */
85
+ static disconnect(socket, reason, wsManagementId) {
86
+ return this.#io.disconnect(socket, reason, wsManagementId);
87
+ }
88
+ }
89
+
90
+ export { CoreWsStreamChannel };
@@ -1,47 +1,36 @@
1
1
  /**
2
- * Module for handling new WebSocket connections and setting up channel listeners.
3
- * @module ws/core.ws.connection
4
- * @namespace CoreWsConnection
2
+ * Core WebSocket connection handler wires sockets to all channels.
3
+ * @module ws/core/core.ws.connection
5
4
  */
6
5
 
7
6
  import { loggerFactory } from '../../server/logger.js';
8
7
  import { CoreWsChatChannel } from './channels/core.ws.chat.js';
9
8
  import { CoreWsMailerChannel } from './channels/core.ws.mailer.js';
10
9
  import { CoreWsStreamChannel } from './channels/core.ws.stream.js';
11
- import { Socket } from 'socket.io'; // Added for JSDoc type hinting
12
10
 
13
11
  const logger = loggerFactory(import.meta);
14
12
 
15
13
  /**
16
- * @class CoreWsConnectionManager
17
- * @alias CoreWsConnectionManager
18
- * @memberof CoreWsConnection
19
- * @classdesc Manages the lifecycle of a new WebSocket connection, setting up listeners for
20
- * all registered channels (Chat, Mailer, Stream) and handling disconnection by delegating to channel handlers.
14
+ * @class CoreWsConnectionHandler
15
+ * @classdesc Subscribes a new socket to all core channels (chat, mailer, stream)
16
+ * and delegates disconnect events to each channel.
21
17
  */
22
- class CoreWsConnectionManager {
18
+ class CoreWsConnectionHandler {
23
19
  /**
24
- * Handles a new WebSocket connection by subscribing it to all active channels
25
- * and setting up the disconnect listener.
26
- *
27
- * @static
28
- * @param {Socket} socket - The Socket.IO socket object representing the client connection.
29
- * @param {string} wsManagementId - Unique identifier for the WebSocket management context.
30
- * @returns {void}
20
+ * Handles a new WebSocket connection.
21
+ * @param {import('socket.io').Socket} socket
22
+ * @param {string} wsManagementId
31
23
  */
32
- static handleConnection(socket, wsManagementId) {
24
+ static handle(socket, wsManagementId) {
33
25
  logger.info(`New connection established. Socket ID: ${socket.id}`);
34
26
 
35
- // Subscribe socket to all channel connection handlers (assuming these channels are IoChannel instances)
36
27
  CoreWsChatChannel.connection(socket, wsManagementId);
37
28
  CoreWsMailerChannel.connection(socket, wsManagementId);
38
29
  CoreWsStreamChannel.connection(socket, wsManagementId);
39
30
 
40
- // Set up the disconnect listener
41
31
  socket.on('disconnect', (reason) => {
42
- logger.info(`Connection disconnected. Socket ID: ${socket.id} due to reason: ${reason}`);
32
+ logger.info(`Connection disconnected. Socket ID: ${socket.id}, reason: ${reason}`);
43
33
 
44
- // Notify all channels of the disconnection
45
34
  CoreWsChatChannel.disconnect(socket, reason, wsManagementId);
46
35
  CoreWsMailerChannel.disconnect(socket, reason, wsManagementId);
47
36
  CoreWsStreamChannel.disconnect(socket, reason, wsManagementId);
@@ -49,14 +38,4 @@ class CoreWsConnectionManager {
49
38
  }
50
39
  }
51
40
 
52
- /**
53
- * Backward compatibility export for the connection handler function.
54
- * @memberof CoreWsConnection
55
- * @function CoreWsConnection
56
- * @param {Socket} socket - The Socket.IO socket object.
57
- * @param {string} wsManagementId - Unique identifier for the WebSocket management context.
58
- * @returns {void}
59
- */
60
- const CoreWsConnection = CoreWsConnectionManager.handleConnection;
61
-
62
- export { CoreWsConnectionManager, CoreWsConnection };
41
+ export { CoreWsConnectionHandler };