@seip/bluebird-js 0.0.1 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/.env_example +53 -53
  2. package/AGENTS.md +426 -403
  3. package/LICENSE +1 -1
  4. package/README.md +292 -285
  5. package/app/routes/api.js +50 -50
  6. package/app/routes/web.js +55 -53
  7. package/app/views/about.js +63 -0
  8. package/app/views/dashboard.js +147 -0
  9. package/app/views/index.js +80 -0
  10. package/app/views/layouts/main/view.js +81 -0
  11. package/app/views/legal/terms.html +19 -0
  12. package/app/views/login.js +80 -0
  13. package/core/app.d.ts +18 -18
  14. package/core/app.js +684 -644
  15. package/core/auth.d.ts +13 -13
  16. package/core/auth.js +326 -326
  17. package/core/cache.d.ts +17 -17
  18. package/core/cache.js +475 -475
  19. package/core/cli/doctor.js +287 -287
  20. package/core/cli/ecosystem.js +162 -162
  21. package/core/cli/init.js +779 -779
  22. package/core/cli/migrate.js +541 -541
  23. package/core/cli/model.js +66 -66
  24. package/core/cli/nginx.js +199 -199
  25. package/core/cli/route.js +120 -120
  26. package/core/cli/view.js +55 -36
  27. package/core/config.d.ts +3 -3
  28. package/core/config.js +111 -111
  29. package/core/csrf.d.ts +3 -3
  30. package/core/csrf.js +114 -114
  31. package/core/database.d.ts +15 -15
  32. package/core/database.js +636 -636
  33. package/core/debug.d.ts +3 -3
  34. package/core/debug.js +249 -249
  35. package/core/hash.d.ts +3 -3
  36. package/core/hash.js +194 -194
  37. package/core/html.d.ts +42 -0
  38. package/core/html.js +217 -0
  39. package/core/index.d.ts +1176 -1071
  40. package/core/logger.d.ts +3 -3
  41. package/core/logger.js +127 -124
  42. package/core/middleware.d.ts +3 -3
  43. package/core/middleware.js +28 -28
  44. package/core/model.d.ts +19 -19
  45. package/core/model.js +600 -600
  46. package/core/queue.d.ts +13 -13
  47. package/core/queue.js +172 -172
  48. package/core/ratelimit.d.ts +3 -3
  49. package/core/ratelimit.js +145 -145
  50. package/core/redis.d.ts +21 -21
  51. package/core/redis.js +230 -230
  52. package/core/render-cache.js +212 -0
  53. package/core/render.d.ts +3 -3
  54. package/core/render.js +199 -555
  55. package/core/router.d.ts +3 -3
  56. package/core/router.js +171 -171
  57. package/core/seo.d.ts +3 -3
  58. package/core/seo.js +106 -106
  59. package/core/swagger.d.ts +3 -3
  60. package/core/swagger.js +60 -60
  61. package/core/upload.d.ts +13 -13
  62. package/core/upload.js +102 -102
  63. package/core/util/colors.js +82 -82
  64. package/core/validate.d.ts +15 -15
  65. package/core/validate.js +364 -364
  66. package/core/view-loader.js +162 -0
  67. package/core/vite.d.ts +3 -3
  68. package/core/vite.js +145 -145
  69. package/core/ws.d.ts +13 -13
  70. package/core/ws.js +245 -245
  71. package/index.js +18 -18
  72. package/jsconfig.json +15 -15
  73. package/package.json +85 -86
  74. package/production.md +273 -273
  75. package/public/css/bluebird.min.css +1 -1
  76. package/public/js/bluebird-client.js +1780 -1662
  77. package/public/js/bluebird.min.js +1072 -1072
  78. package/app/views/about.html +0 -161
  79. package/app/views/dashboard.html +0 -140
  80. package/app/views/index.html +0 -150
  81. package/app/views/login.html +0 -144
package/core/ws.js CHANGED
@@ -1,245 +1,245 @@
1
- import { randomUUID } from "node:crypto";
2
- import { getRedisClient } from "./cache.js";
3
- import Auth from "./auth.js";
4
-
5
- let WebSocketServer = null;
6
- let WebSocket = null;
7
-
8
- try {
9
- const wsModule = await import("ws");
10
- WebSocketServer = wsModule.WebSocketServer || wsModule.default?.WebSocketServer;
11
- WebSocket = wsModule.WebSocket || wsModule.default?.WebSocket;
12
- } catch {}
13
-
14
- /**
15
- * High-performance WebSocketManager providing real-time channels, room management,
16
- * heartbeat ping/pong, Auth token verification, and Redis Pub/Sub multi-process cluster scaling.
17
- */
18
- class WebSocketManager {
19
- /**
20
- * Initializes the WebSocket manager attached to an HTTP server.
21
- * @param {import('http').Server} server - Express HTTP server instance.
22
- * @param {Object} [options={}] - Configuration options.
23
- * @param {string} [options.path="/ws"] - WebSocket endpoint route.
24
- * @param {boolean} [options.auth=false] - Require valid Auth JWT token on connection.
25
- * @param {number} [options.maxPayload=1048576] - Maximum payload size in bytes (default 1MB).
26
- */
27
- constructor(server, options = {}) {
28
- if (!WebSocketServer || !WebSocket) {
29
- throw new Error(
30
- "[WS ERROR] 'ws' package is not installed. Install it with: npm install ws or npx blue-bird add ws",
31
- );
32
- }
33
-
34
- this.server = server;
35
- this.path = options.path || "/ws";
36
- this.requireAuth = options.auth ?? false;
37
- this.maxPayload = options.maxPayload || 1024 * 1024;
38
- this.instanceId = randomUUID();
39
- this.rooms = new Map();
40
- this.clients = new Set();
41
- this.connectionHandler = null;
42
- this.redisPublisher = null;
43
- this.redisSubscriber = null;
44
-
45
- this.wss = new WebSocketServer({
46
- noServer: true,
47
- maxPayload: this.maxPayload,
48
- });
49
-
50
- this._setupUpgrade();
51
- this._setupHeartbeat();
52
- this._setupRedisPubSub();
53
- }
54
-
55
- /**
56
- * Attaches the HTTP Upgrade listener to the Express HTTP server instance.
57
- * @private
58
- */
59
- _setupUpgrade() {
60
- this.server.on("upgrade", async (request, socket, head) => {
61
- try {
62
- const urlObj = new URL(request.url, `http://${request.headers.host || "localhost"}`);
63
- if (urlObj.pathname !== this.path) {
64
- return;
65
- }
66
-
67
- if (this.requireAuth) {
68
- const cookieHeader = request.headers.cookie || "";
69
- const cookies = {};
70
- cookieHeader.split(";").forEach((c) => {
71
- const parts = c.trim().split("=");
72
- if (parts[0]) cookies[parts[0]] = decodeURIComponent(parts[1] || "");
73
- });
74
-
75
- const token = cookies.auth || urlObj.searchParams.get("token") || request.headers.authorization?.split(" ")[1];
76
- const user = token ? Auth.verifyToken(token) : null;
77
-
78
- if (!user) {
79
- socket.write("HTTP/1.1 401 Unauthorized\r\n\r\n");
80
- socket.destroy();
81
- return;
82
- }
83
- request.user = user;
84
- }
85
-
86
- this.wss.handleUpgrade(request, socket, head, (ws) => {
87
- this.wss.emit("connection", ws, request);
88
- });
89
- } catch (err) {
90
- socket.destroy();
91
- }
92
- });
93
-
94
- this.wss.on("connection", (ws, req) => {
95
- ws.isAlive = true;
96
- ws.user = req.user || null;
97
- ws.rooms = new Set();
98
- this.clients.add(ws);
99
-
100
- ws.on("pong", () => {
101
- ws.isAlive = true;
102
- });
103
-
104
- ws.on("close", () => {
105
- this.clients.delete(ws);
106
- ws.rooms.forEach((room) => this.leave(room, ws));
107
- });
108
-
109
- ws.on("error", () => {
110
- this.clients.delete(ws);
111
- });
112
-
113
- ws.join = (room) => this.join(room, ws);
114
- ws.leave = (room) => this.leave(room, ws);
115
- ws.sendJSON = (data) => {
116
- if (ws.readyState === WebSocket.OPEN) {
117
- ws.send(JSON.stringify(data));
118
- }
119
- };
120
-
121
- if (this.connectionHandler) {
122
- this.connectionHandler(ws, req);
123
- }
124
- });
125
- }
126
-
127
- /**
128
- * Registers a connection callback handler.
129
- * @param {Function} handler - Callback function: (ws, req) => {}
130
- */
131
- onConnection(handler) {
132
- this.connectionHandler = handler;
133
- }
134
-
135
- /**
136
- * Subscribes a WebSocket connection to a room.
137
- * @param {string} room - Room identifier.
138
- * @param {WebSocket} ws - Target WebSocket instance.
139
- */
140
- join(room, ws) {
141
- if (!this.rooms.has(room)) {
142
- this.rooms.set(room, new Set());
143
- }
144
- this.rooms.get(room).add(ws);
145
- ws.rooms.add(room);
146
- }
147
-
148
- /**
149
- * Unsubscribes a WebSocket connection from a room.
150
- * @param {string} room - Room identifier.
151
- * @param {WebSocket} ws - Target WebSocket instance.
152
- */
153
- leave(room, ws) {
154
- if (this.rooms.has(room)) {
155
- this.rooms.get(room).delete(ws);
156
- if (this.rooms.get(room).size === 0) {
157
- this.rooms.delete(room);
158
- }
159
- }
160
- ws.rooms.delete(room);
161
- }
162
-
163
- /**
164
- * Broadcasts a JSON payload or string to all connected clients (or specific room).
165
- * Automatically synchronizes across cluster workers via Redis Pub/Sub without duplicate delivery.
166
- * @param {any} data - Data to send.
167
- * @param {string} [room=null] - Optional target room.
168
- */
169
- broadcast(data, room = null) {
170
- const payload = typeof data === "string" ? data : JSON.stringify(data);
171
-
172
- this._sendLocal(payload, room);
173
-
174
- if (this.redisPublisher && this.redisPublisher.isOpen) {
175
- this.redisPublisher
176
- .publish(
177
- "bluebird:ws:broadcast",
178
- JSON.stringify({ instanceId: this.instanceId, room, payload })
179
- )
180
- .catch(() => {});
181
- }
182
- }
183
-
184
- /**
185
- * Transmits payload to local WebSocket connections.
186
- * @private
187
- */
188
- _sendLocal(payload, room = null) {
189
- const targetSockets = room && this.rooms.has(room) ? this.rooms.get(room) : this.clients;
190
- targetSockets.forEach((client) => {
191
- if (client.readyState === WebSocket.OPEN) {
192
- client.send(payload);
193
- }
194
- });
195
- }
196
-
197
- /**
198
- * Sets up 30s ping/pong heartbeat to clear dead TCP sockets.
199
- * @private
200
- */
201
- _setupHeartbeat() {
202
- this.heartbeatInterval = setInterval(() => {
203
- this.clients.forEach((ws) => {
204
- if (ws.isAlive === false) {
205
- this.clients.delete(ws);
206
- return ws.terminate();
207
- }
208
- ws.isAlive = false;
209
- ws.ping();
210
- });
211
- }, 30000);
212
- this.heartbeatInterval.unref();
213
- }
214
-
215
- /**
216
- * Initializes Redis Pub/Sub channels for multi-process cluster synchronization.
217
- * @private
218
- */
219
- async _setupRedisPubSub() {
220
- try {
221
- const redisClient = getRedisClient();
222
- if (!redisClient) return;
223
-
224
- this.redisPublisher = redisClient.duplicate();
225
- this.redisSubscriber = redisClient.duplicate();
226
-
227
- this.redisPublisher.on("error", () => {});
228
- this.redisSubscriber.on("error", () => {});
229
-
230
- await this.redisPublisher.connect();
231
- await this.redisSubscriber.connect();
232
-
233
- await this.redisSubscriber.subscribe("bluebird:ws:broadcast", (message) => {
234
- try {
235
- const messageData = JSON.parse(message);
236
- if (messageData.instanceId === this.instanceId) return;
237
- this._sendLocal(messageData.payload, messageData.room);
238
- } catch {}
239
- });
240
- } catch {}
241
- }
242
- }
243
-
244
- export { WebSocketManager };
245
- export default WebSocketManager;
1
+ import { randomUUID } from "node:crypto";
2
+ import { getRedisClient } from "./cache.js";
3
+ import Auth from "./auth.js";
4
+
5
+ let WebSocketServer = null;
6
+ let WebSocket = null;
7
+
8
+ try {
9
+ const wsModule = await import("ws");
10
+ WebSocketServer = wsModule.WebSocketServer || wsModule.default?.WebSocketServer;
11
+ WebSocket = wsModule.WebSocket || wsModule.default?.WebSocket;
12
+ } catch {}
13
+
14
+ /**
15
+ * High-performance WebSocketManager providing real-time channels, room management,
16
+ * heartbeat ping/pong, Auth token verification, and Redis Pub/Sub multi-process cluster scaling.
17
+ */
18
+ class WebSocketManager {
19
+ /**
20
+ * Initializes the WebSocket manager attached to an HTTP server.
21
+ * @param {import('http').Server} server - Express HTTP server instance.
22
+ * @param {Object} [options={}] - Configuration options.
23
+ * @param {string} [options.path="/ws"] - WebSocket endpoint route.
24
+ * @param {boolean} [options.auth=false] - Require valid Auth JWT token on connection.
25
+ * @param {number} [options.maxPayload=1048576] - Maximum payload size in bytes (default 1MB).
26
+ */
27
+ constructor(server, options = {}) {
28
+ if (!WebSocketServer || !WebSocket) {
29
+ throw new Error(
30
+ "[WS ERROR] 'ws' package is not installed. Install it with: npm install ws or npx blue-bird add ws",
31
+ );
32
+ }
33
+
34
+ this.server = server;
35
+ this.path = options.path || "/ws";
36
+ this.requireAuth = options.auth ?? false;
37
+ this.maxPayload = options.maxPayload || 1024 * 1024;
38
+ this.instanceId = randomUUID();
39
+ this.rooms = new Map();
40
+ this.clients = new Set();
41
+ this.connectionHandler = null;
42
+ this.redisPublisher = null;
43
+ this.redisSubscriber = null;
44
+
45
+ this.wss = new WebSocketServer({
46
+ noServer: true,
47
+ maxPayload: this.maxPayload,
48
+ });
49
+
50
+ this._setupUpgrade();
51
+ this._setupHeartbeat();
52
+ this._setupRedisPubSub();
53
+ }
54
+
55
+ /**
56
+ * Attaches the HTTP Upgrade listener to the Express HTTP server instance.
57
+ * @private
58
+ */
59
+ _setupUpgrade() {
60
+ this.server.on("upgrade", async (request, socket, head) => {
61
+ try {
62
+ const urlObj = new URL(request.url, `http://${request.headers.host || "localhost"}`);
63
+ if (urlObj.pathname !== this.path) {
64
+ return;
65
+ }
66
+
67
+ if (this.requireAuth) {
68
+ const cookieHeader = request.headers.cookie || "";
69
+ const cookies = {};
70
+ cookieHeader.split(";").forEach((c) => {
71
+ const parts = c.trim().split("=");
72
+ if (parts[0]) cookies[parts[0]] = decodeURIComponent(parts[1] || "");
73
+ });
74
+
75
+ const token = cookies.auth || urlObj.searchParams.get("token") || request.headers.authorization?.split(" ")[1];
76
+ const user = token ? Auth.verifyToken(token) : null;
77
+
78
+ if (!user) {
79
+ socket.write("HTTP/1.1 401 Unauthorized\r\n\r\n");
80
+ socket.destroy();
81
+ return;
82
+ }
83
+ request.user = user;
84
+ }
85
+
86
+ this.wss.handleUpgrade(request, socket, head, (ws) => {
87
+ this.wss.emit("connection", ws, request);
88
+ });
89
+ } catch (err) {
90
+ socket.destroy();
91
+ }
92
+ });
93
+
94
+ this.wss.on("connection", (ws, req) => {
95
+ ws.isAlive = true;
96
+ ws.user = req.user || null;
97
+ ws.rooms = new Set();
98
+ this.clients.add(ws);
99
+
100
+ ws.on("pong", () => {
101
+ ws.isAlive = true;
102
+ });
103
+
104
+ ws.on("close", () => {
105
+ this.clients.delete(ws);
106
+ ws.rooms.forEach((room) => this.leave(room, ws));
107
+ });
108
+
109
+ ws.on("error", () => {
110
+ this.clients.delete(ws);
111
+ });
112
+
113
+ ws.join = (room) => this.join(room, ws);
114
+ ws.leave = (room) => this.leave(room, ws);
115
+ ws.sendJSON = (data) => {
116
+ if (ws.readyState === WebSocket.OPEN) {
117
+ ws.send(JSON.stringify(data));
118
+ }
119
+ };
120
+
121
+ if (this.connectionHandler) {
122
+ this.connectionHandler(ws, req);
123
+ }
124
+ });
125
+ }
126
+
127
+ /**
128
+ * Registers a connection callback handler.
129
+ * @param {Function} handler - Callback function: (ws, req) => {}
130
+ */
131
+ onConnection(handler) {
132
+ this.connectionHandler = handler;
133
+ }
134
+
135
+ /**
136
+ * Subscribes a WebSocket connection to a room.
137
+ * @param {string} room - Room identifier.
138
+ * @param {WebSocket} ws - Target WebSocket instance.
139
+ */
140
+ join(room, ws) {
141
+ if (!this.rooms.has(room)) {
142
+ this.rooms.set(room, new Set());
143
+ }
144
+ this.rooms.get(room).add(ws);
145
+ ws.rooms.add(room);
146
+ }
147
+
148
+ /**
149
+ * Unsubscribes a WebSocket connection from a room.
150
+ * @param {string} room - Room identifier.
151
+ * @param {WebSocket} ws - Target WebSocket instance.
152
+ */
153
+ leave(room, ws) {
154
+ if (this.rooms.has(room)) {
155
+ this.rooms.get(room).delete(ws);
156
+ if (this.rooms.get(room).size === 0) {
157
+ this.rooms.delete(room);
158
+ }
159
+ }
160
+ ws.rooms.delete(room);
161
+ }
162
+
163
+ /**
164
+ * Broadcasts a JSON payload or string to all connected clients (or specific room).
165
+ * Automatically synchronizes across cluster workers via Redis Pub/Sub without duplicate delivery.
166
+ * @param {any} data - Data to send.
167
+ * @param {string} [room=null] - Optional target room.
168
+ */
169
+ broadcast(data, room = null) {
170
+ const payload = typeof data === "string" ? data : JSON.stringify(data);
171
+
172
+ this._sendLocal(payload, room);
173
+
174
+ if (this.redisPublisher && this.redisPublisher.isOpen) {
175
+ this.redisPublisher
176
+ .publish(
177
+ "bluebird:ws:broadcast",
178
+ JSON.stringify({ instanceId: this.instanceId, room, payload })
179
+ )
180
+ .catch(() => {});
181
+ }
182
+ }
183
+
184
+ /**
185
+ * Transmits payload to local WebSocket connections.
186
+ * @private
187
+ */
188
+ _sendLocal(payload, room = null) {
189
+ const targetSockets = room && this.rooms.has(room) ? this.rooms.get(room) : this.clients;
190
+ targetSockets.forEach((client) => {
191
+ if (client.readyState === WebSocket.OPEN) {
192
+ client.send(payload);
193
+ }
194
+ });
195
+ }
196
+
197
+ /**
198
+ * Sets up 30s ping/pong heartbeat to clear dead TCP sockets.
199
+ * @private
200
+ */
201
+ _setupHeartbeat() {
202
+ this.heartbeatInterval = setInterval(() => {
203
+ this.clients.forEach((ws) => {
204
+ if (ws.isAlive === false) {
205
+ this.clients.delete(ws);
206
+ return ws.terminate();
207
+ }
208
+ ws.isAlive = false;
209
+ ws.ping();
210
+ });
211
+ }, 30000);
212
+ this.heartbeatInterval.unref();
213
+ }
214
+
215
+ /**
216
+ * Initializes Redis Pub/Sub channels for multi-process cluster synchronization.
217
+ * @private
218
+ */
219
+ async _setupRedisPubSub() {
220
+ try {
221
+ const redisClient = getRedisClient();
222
+ if (!redisClient) return;
223
+
224
+ this.redisPublisher = redisClient.duplicate();
225
+ this.redisSubscriber = redisClient.duplicate();
226
+
227
+ this.redisPublisher.on("error", () => {});
228
+ this.redisSubscriber.on("error", () => {});
229
+
230
+ await this.redisPublisher.connect();
231
+ await this.redisSubscriber.connect();
232
+
233
+ await this.redisSubscriber.subscribe("bluebird:ws:broadcast", (message) => {
234
+ try {
235
+ const messageData = JSON.parse(message);
236
+ if (messageData.instanceId === this.instanceId) return;
237
+ this._sendLocal(messageData.payload, messageData.room);
238
+ } catch {}
239
+ });
240
+ } catch {}
241
+ }
242
+ }
243
+
244
+ export { WebSocketManager };
245
+ export default WebSocketManager;
package/index.js CHANGED
@@ -1,18 +1,18 @@
1
- import App from "@seip/bluebird-js/core/app.js";
2
- import routerApi from "./app/routes/api.js";
3
- import routerWeb from "./app/routes/web.js";
4
-
5
- /**
6
- * Main entry point for the Blue Bird application.
7
- * Initializes the App instance with routes, configuration, and starts the server.
8
- */
9
- const app = new App({
10
- routes: [routerWeb, routerApi],
11
- cors: {},
12
- middlewares: [],
13
- host: "http://localhost",
14
- port: process.env.PORT || 3000,
15
- logger: false,
16
- });
17
-
18
- app.run();
1
+ import App from "@seip/bluebird-js/core/app.js";
2
+ import routerApi from "./app/routes/api.js";
3
+ import routerWeb from "./app/routes/web.js";
4
+
5
+ /**
6
+ * Main entry point for the Blue Bird application.
7
+ * Initializes the App instance with routes, configuration, and starts the server.
8
+ */
9
+ const app = new App({
10
+ routes: [routerWeb, routerApi],
11
+ cors: {},
12
+ middlewares: [],
13
+ host: "http://localhost",
14
+ port: process.env.PORT || 3000,
15
+ logger: false,
16
+ });
17
+
18
+ app.run();
package/jsconfig.json CHANGED
@@ -1,15 +1,15 @@
1
- {
2
- "compilerOptions": {
3
- "target": "ES2022",
4
- "module": "NodeNext",
5
- "moduleResolution": "NodeNext",
6
- "checkJs": false,
7
- "allowJs": true
8
- },
9
- "include": [
10
- "public/**/*",
11
- "app/**/*",
12
- "core/**/*",
13
- "test/**/*"
14
- ]
15
- }
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2022",
4
+ "module": "NodeNext",
5
+ "moduleResolution": "NodeNext",
6
+ "checkJs": false,
7
+ "allowJs": true
8
+ },
9
+ "include": [
10
+ "public/**/*",
11
+ "app/**/*",
12
+ "core/**/*",
13
+ "test/**/*"
14
+ ]
15
+ }