@dnotifier-realtime/dnotifier 1.0.0 → 1.0.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.
- package/README.md +50 -1
- package/package.json +3 -2
- package/src/dnotifier.js +249 -52
- package/src/transport/websocketTransport.js +106 -21
- package/src/utils/buffer.js +6 -0
package/README.md
CHANGED
|
@@ -20,4 +20,53 @@
|
|
|
20
20
|
## 📦 Installation
|
|
21
21
|
|
|
22
22
|
```bash
|
|
23
|
-
npm
|
|
23
|
+
npm i @dnotifier-realtime/dnotifier
|
|
24
|
+
|
|
25
|
+
import { DNotifier } from "@dnotifier-realtime/dnotifier";
|
|
26
|
+
|
|
27
|
+
const notifier = new DNotifier({
|
|
28
|
+
appId: "YOUR-APP-ID",
|
|
29
|
+
secret: "YOUR-APP-SECRET",
|
|
30
|
+
transport: "ws", // or "http"
|
|
31
|
+
userId: "YOUR-UNIQUE-USERID",
|
|
32
|
+
onConnected: () => {
|
|
33
|
+
console.log("✅ Connected successfully.");
|
|
34
|
+
},
|
|
35
|
+
onMessage: (data) => {
|
|
36
|
+
console.log("📩 Incoming message:");
|
|
37
|
+
console.log("Metadata:", data.metadata);
|
|
38
|
+
console.log("Message:", data.payload.toJSON());
|
|
39
|
+
console.log("Message:", data.payload.toString());
|
|
40
|
+
console.log("Message:", data.payload.raw());
|
|
41
|
+
}
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
await notifier.connect();
|
|
45
|
+
|
|
46
|
+
// Send single message
|
|
47
|
+
notifier.send({
|
|
48
|
+
senderId: "YOUR-UNIQUE-USERID",
|
|
49
|
+
receiverId: "RECEIVER-UNIQUE-USERID",
|
|
50
|
+
code: 200,
|
|
51
|
+
data: {
|
|
52
|
+
text: "Hello from DNotifier SDK 🚀"
|
|
53
|
+
}
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
// Broadcast message
|
|
57
|
+
notifier.send({
|
|
58
|
+
senderId: "YOUR-UNIQUE-USERID",
|
|
59
|
+
receiverIds: ["user_2", "user_3"],
|
|
60
|
+
code: 200,
|
|
61
|
+
data: "Broadcast test message"
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
// Send Binary Data (files, images , media)
|
|
65
|
+
const buffer = Buffer.from("Hello Binary");
|
|
66
|
+
|
|
67
|
+
notifier.sendBinary({
|
|
68
|
+
senderId: "YOUR-UNIQUE-USERID",
|
|
69
|
+
receiverIds: ["user_1"],
|
|
70
|
+
buffer
|
|
71
|
+
});
|
|
72
|
+
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dnotifier-realtime/dnotifier",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.2",
|
|
4
4
|
"description": "Real-time notification & messaging SDK",
|
|
5
5
|
"main": "src/dnotifier.js",
|
|
6
6
|
"type": "module",
|
|
@@ -24,7 +24,8 @@
|
|
|
24
24
|
},
|
|
25
25
|
"devDependencies": {},
|
|
26
26
|
"scripts": {
|
|
27
|
-
"test": "echo \"Error: no test specified\" && exit 1"
|
|
27
|
+
"test": "echo \"Error: no test specified\" && exit 1",
|
|
28
|
+
"start" : "node index.js"
|
|
28
29
|
},
|
|
29
30
|
"homepage": "https://dnotifier.com"
|
|
30
31
|
}
|
package/src/dnotifier.js
CHANGED
|
@@ -1,21 +1,194 @@
|
|
|
1
|
+
// import { HttpTransport } from "./transport/httpTransport.js";
|
|
2
|
+
// import { WebsocketTransport } from "./transport/websocketTransport.js";
|
|
3
|
+
// import { prefixId } from "./utils/id.js";
|
|
4
|
+
// import { framePacket, decodePacket } from "./utils/frame.js";
|
|
5
|
+
// import {Payload} from './utils/payload.js'
|
|
6
|
+
// // import { decodePacket } from "./utils/decode.js";
|
|
7
|
+
|
|
8
|
+
// export class DNotifier {
|
|
9
|
+
// /**
|
|
10
|
+
// * @param {Object} options
|
|
11
|
+
// * @param {string} options.appId
|
|
12
|
+
// * @param {string} options.secret
|
|
13
|
+
// * @param {string} options.transport - "ws" or "http"
|
|
14
|
+
// * @param {string} options.userId
|
|
15
|
+
// * @param {function} options.onConnected - callback when handshake is done
|
|
16
|
+
// * @param {function} options.onMessage - callback for all subsequent messages
|
|
17
|
+
// * @param {function} options.onDisconnected - callback when disconnection happens
|
|
18
|
+
// *
|
|
19
|
+
// */
|
|
20
|
+
// constructor({ appId, secret, transport, userId, onConnected, onMessage, onDisconnected }) {
|
|
21
|
+
// if (!appId || !secret || !transport || !userId) {
|
|
22
|
+
// throw new Error("appId, secret, transport, and userId are required");
|
|
23
|
+
// }
|
|
24
|
+
|
|
25
|
+
// this.appId = appId;
|
|
26
|
+
// this.secret = secret;
|
|
27
|
+
// this.userId = userId;
|
|
28
|
+
// this.url = "ws://127.0.0.1:7072";
|
|
29
|
+
|
|
30
|
+
// this.onConnectedCallback = onConnected || (() => {});
|
|
31
|
+
// this.onMessageCallback = onMessage || (() => {});
|
|
32
|
+
// this.onDisconnectedCallback = onDisconnected || (() => {});
|
|
33
|
+
|
|
34
|
+
// this.isConnected = false;
|
|
35
|
+
|
|
36
|
+
// this.transport =
|
|
37
|
+
// transport === "ws" ? new WebsocketTransport() : new HttpTransport();
|
|
38
|
+
// }
|
|
39
|
+
|
|
40
|
+
// async connect() {
|
|
41
|
+
// // Step 1: Authenticate with Auth server
|
|
42
|
+
// const authServer = new HttpTransport({
|
|
43
|
+
// url: "https://link.dchatter.com/api/v1/sdk/auth",
|
|
44
|
+
// });
|
|
45
|
+
|
|
46
|
+
// const res = await authServer.send({
|
|
47
|
+
// appId: this.appId,
|
|
48
|
+
// appSecret: this.secret,
|
|
49
|
+
// userID: this.userId,
|
|
50
|
+
// });
|
|
51
|
+
|
|
52
|
+
// if (res._responseCode !== 200) {
|
|
53
|
+
// throw new Error("Authentication Failed.");
|
|
54
|
+
// }
|
|
55
|
+
// this.authToken = res._responseData;
|
|
56
|
+
|
|
57
|
+
// // Step 2: Connect WebSocket
|
|
58
|
+
// await this.transport.connect(this.url);
|
|
59
|
+
|
|
60
|
+
// // Step 3: Send handshake packet
|
|
61
|
+
// const metadata = {
|
|
62
|
+
// type: "text",
|
|
63
|
+
// code: 101, // handshake
|
|
64
|
+
// appId: this.appId,
|
|
65
|
+
// sender: prefixId(this.appId, this.userId),
|
|
66
|
+
// timestamp: Date.now(),
|
|
67
|
+
// };
|
|
68
|
+
// const payloadBuffer = Buffer.from(JSON.stringify({ token : this.authToken+ "123" }), "utf8");
|
|
69
|
+
// const frame = framePacket(metadata, payloadBuffer);
|
|
70
|
+
|
|
71
|
+
// this.transport.sendBinary(frame);
|
|
72
|
+
|
|
73
|
+
// // Step 4: Listen for all incoming messages
|
|
74
|
+
// let handshakeProcessed = false;
|
|
75
|
+
|
|
76
|
+
// // Flag to ignore handshake response
|
|
77
|
+
// let handshakeDone = false;
|
|
78
|
+
|
|
79
|
+
// this.transport.on("message", (chunk) => {
|
|
80
|
+
// try {
|
|
81
|
+
|
|
82
|
+
// const metadata = chunk.metadata
|
|
83
|
+
// const data = chunk.data;
|
|
84
|
+
|
|
85
|
+
// // Handle handshake response internally
|
|
86
|
+
// if (!handshakeProcessed && metadata.packet.code === '102' && metadata.packet.sender.includes(prefixId(this.appId, this.userId))) {
|
|
87
|
+
// handshakeProcessed = true;
|
|
88
|
+
// this.isConnected = true;
|
|
89
|
+
// handshakeDone = true;
|
|
90
|
+
// this.onConnectedCallback(); // notify developer
|
|
91
|
+
|
|
92
|
+
// return; // do NOT forward handshake packet
|
|
93
|
+
// }
|
|
94
|
+
// // Forward all other messages to developer
|
|
95
|
+
// if (handshakeDone && this.onMessageCallback) {
|
|
96
|
+
// this.onMessageCallback({
|
|
97
|
+
// metadata : {
|
|
98
|
+
// sender : metadata.packet.sender,
|
|
99
|
+
// timestamp : metadata.packet.timestamp,
|
|
100
|
+
// },
|
|
101
|
+
// payload: new Payload(data)
|
|
102
|
+
// });
|
|
103
|
+
|
|
104
|
+
// }
|
|
105
|
+
// } catch (err) {
|
|
106
|
+
// console.error("Error decoding packet:", err);
|
|
107
|
+
// }
|
|
108
|
+
// });
|
|
109
|
+
|
|
110
|
+
// this.transport.on("close", ({ code, reason }) => {
|
|
111
|
+
// if (this.isConnected) {
|
|
112
|
+
// this.isConnected = false;
|
|
113
|
+
|
|
114
|
+
// this.onDisconnectedCallback({
|
|
115
|
+
// code,
|
|
116
|
+
// reason: reason?.toString?.() || "Disconnected"
|
|
117
|
+
// });
|
|
118
|
+
// }
|
|
119
|
+
// });
|
|
120
|
+
|
|
121
|
+
// this.transport.on("error", (err) => {
|
|
122
|
+
// this.isConnected = false;
|
|
123
|
+
|
|
124
|
+
// this.onDisconnectedCallback({
|
|
125
|
+
// code,
|
|
126
|
+
// reason: reason?.toString?.() || "Disconnected"
|
|
127
|
+
// });
|
|
128
|
+
// });
|
|
129
|
+
|
|
130
|
+
// }
|
|
131
|
+
|
|
132
|
+
// send({ senderId, receiverId, receiverIds, data }) {
|
|
133
|
+
// if (!senderId) throw new Error("senderId required");
|
|
134
|
+
// if (!receiverId && !receiverIds)
|
|
135
|
+
// throw new Error("receiverId or receiverIds required");
|
|
136
|
+
|
|
137
|
+
// const receivers = receiverIds ?? [receiverId];
|
|
138
|
+
|
|
139
|
+
// const metadata = {
|
|
140
|
+
// type: "text",
|
|
141
|
+
// code: 200, // message
|
|
142
|
+
// appId: this.appId,
|
|
143
|
+
// sender: prefixId(this.appId, senderId),
|
|
144
|
+
// receivers: receivers.map((id) => prefixId(this.appId, id)),
|
|
145
|
+
// timestamp: Date.now(),
|
|
146
|
+
// };
|
|
147
|
+
|
|
148
|
+
// const payloadBuffer = Buffer.from(JSON.stringify(data), "utf8");
|
|
149
|
+
// const frame = framePacket(metadata, payloadBuffer);
|
|
150
|
+
|
|
151
|
+
// this.transport.sendBinary(frame);
|
|
152
|
+
// }
|
|
153
|
+
|
|
154
|
+
// sendBinary({ senderId, receiverIds, buffer, type = "binary" }) {
|
|
155
|
+
// if (!senderId) throw new Error("senderId required");
|
|
156
|
+
// if (!buffer) throw new Error("buffer is required");
|
|
157
|
+
|
|
158
|
+
// const metadata = {
|
|
159
|
+
// type,
|
|
160
|
+
// code: 202, // binary stream
|
|
161
|
+
// appId: this.appId,
|
|
162
|
+
// sender: prefixId(this.appId, senderId),
|
|
163
|
+
// receivers: receiverIds.map((id) => prefixId(this.appId, id)),
|
|
164
|
+
// timestamp: Date.now(),
|
|
165
|
+
// };
|
|
166
|
+
|
|
167
|
+
// const frame = framePacket(metadata, buffer);
|
|
168
|
+
|
|
169
|
+
// this.transport.sendBinary(frame);
|
|
170
|
+
// }
|
|
171
|
+
// }
|
|
172
|
+
|
|
173
|
+
|
|
1
174
|
import { HttpTransport } from "./transport/httpTransport.js";
|
|
2
175
|
import { WebsocketTransport } from "./transport/websocketTransport.js";
|
|
3
176
|
import { prefixId } from "./utils/id.js";
|
|
4
|
-
import { framePacket
|
|
5
|
-
import {Payload} from
|
|
6
|
-
|
|
177
|
+
import { framePacket } from "./utils/frame.js";
|
|
178
|
+
import { Payload } from "./utils/payload.js";
|
|
179
|
+
import { toUint8 } from "./utils/buffer.js";
|
|
7
180
|
|
|
8
181
|
export class DNotifier {
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
182
|
+
constructor({
|
|
183
|
+
appId,
|
|
184
|
+
secret,
|
|
185
|
+
transport,
|
|
186
|
+
userId,
|
|
187
|
+
onConnected,
|
|
188
|
+
onMessage,
|
|
189
|
+
onDisconnected,
|
|
190
|
+
WebSocketImpl, // 👈 OPTIONAL injection
|
|
191
|
+
}) {
|
|
19
192
|
if (!appId || !secret || !transport || !userId) {
|
|
20
193
|
throw new Error("appId, secret, transport, and userId are required");
|
|
21
194
|
}
|
|
@@ -23,19 +196,22 @@ export class DNotifier {
|
|
|
23
196
|
this.appId = appId;
|
|
24
197
|
this.secret = secret;
|
|
25
198
|
this.userId = userId;
|
|
26
|
-
this.url = "ws://
|
|
199
|
+
this.url = "ws://127.0.0.1:7072";
|
|
27
200
|
|
|
28
201
|
this.onConnectedCallback = onConnected || (() => {});
|
|
29
202
|
this.onMessageCallback = onMessage || (() => {});
|
|
203
|
+
this.onDisconnectedCallback = onDisconnected || (() => {});
|
|
30
204
|
|
|
31
205
|
this.isConnected = false;
|
|
32
206
|
|
|
33
207
|
this.transport =
|
|
34
|
-
transport === "ws"
|
|
208
|
+
transport === "ws"
|
|
209
|
+
? new WebsocketTransport(WebSocketImpl)
|
|
210
|
+
: new HttpTransport();
|
|
35
211
|
}
|
|
36
212
|
|
|
37
213
|
async connect() {
|
|
38
|
-
// Step 1: Authenticate
|
|
214
|
+
// Step 1: Authenticate
|
|
39
215
|
const authServer = new HttpTransport({
|
|
40
216
|
url: "https://link.dchatter.com/api/v1/sdk/auth",
|
|
41
217
|
});
|
|
@@ -49,60 +225,78 @@ export class DNotifier {
|
|
|
49
225
|
if (res._responseCode !== 200) {
|
|
50
226
|
throw new Error("Authentication Failed.");
|
|
51
227
|
}
|
|
228
|
+
|
|
52
229
|
this.authToken = res._responseData;
|
|
53
230
|
|
|
54
|
-
// Step 2:
|
|
231
|
+
// Step 2: WebSocket connect
|
|
55
232
|
await this.transport.connect(this.url);
|
|
56
233
|
|
|
57
|
-
// Step 3:
|
|
234
|
+
// Step 3: Handshake
|
|
58
235
|
const metadata = {
|
|
59
236
|
type: "text",
|
|
60
|
-
code: 101,
|
|
237
|
+
code: 101,
|
|
61
238
|
appId: this.appId,
|
|
62
239
|
sender: prefixId(this.appId, this.userId),
|
|
63
240
|
timestamp: Date.now(),
|
|
64
241
|
};
|
|
65
|
-
const payloadBuffer = Buffer.from("handshake", "utf8");
|
|
66
|
-
const frame = framePacket(metadata, payloadBuffer);
|
|
67
242
|
|
|
68
|
-
|
|
243
|
+
const payloadBuffer = toUint8(
|
|
244
|
+
JSON.stringify({ token: this.authToken })
|
|
245
|
+
);
|
|
69
246
|
|
|
70
|
-
|
|
71
|
-
|
|
247
|
+
const frame = framePacket(metadata, payloadBuffer);
|
|
248
|
+
this.transport.sendBinary(frame);
|
|
72
249
|
|
|
73
|
-
// Flag to ignore handshake response
|
|
74
250
|
let handshakeDone = false;
|
|
75
251
|
|
|
76
252
|
this.transport.on("message", (chunk) => {
|
|
77
253
|
try {
|
|
254
|
+
const { metadata, data } = chunk;
|
|
78
255
|
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
256
|
+
if (
|
|
257
|
+
!handshakeDone &&
|
|
258
|
+
metadata.packet.code === "102" &&
|
|
259
|
+
metadata.packet.sender.includes(
|
|
260
|
+
prefixId(this.appId, this.userId)
|
|
261
|
+
)
|
|
262
|
+
) {
|
|
86
263
|
handshakeDone = true;
|
|
87
|
-
this.
|
|
88
|
-
|
|
89
|
-
return;
|
|
264
|
+
this.isConnected = true;
|
|
265
|
+
this.onConnectedCallback();
|
|
266
|
+
return;
|
|
90
267
|
}
|
|
91
|
-
|
|
92
|
-
if (handshakeDone
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
268
|
+
|
|
269
|
+
if (handshakeDone) {
|
|
270
|
+
this.onMessageCallback({
|
|
271
|
+
metadata: {
|
|
272
|
+
sender: metadata.packet.sender,
|
|
273
|
+
timestamp: metadata.packet.timestamp,
|
|
274
|
+
},
|
|
275
|
+
payload: new Payload(data),
|
|
276
|
+
});
|
|
101
277
|
}
|
|
102
278
|
} catch (err) {
|
|
103
|
-
console.error("
|
|
279
|
+
console.error("Packet error:", err);
|
|
104
280
|
}
|
|
105
281
|
});
|
|
282
|
+
|
|
283
|
+
this.transport.on("close", ({ code, reason }) => {
|
|
284
|
+
if (this.isConnected) {
|
|
285
|
+
this.isConnected = false;
|
|
286
|
+
this.onDisconnectedCallback({
|
|
287
|
+
code,
|
|
288
|
+
reason: reason || "Disconnected",
|
|
289
|
+
});
|
|
290
|
+
}
|
|
291
|
+
});
|
|
292
|
+
|
|
293
|
+
this.transport.on("error", (err) => {
|
|
294
|
+
this.isConnected = false;
|
|
295
|
+
this.onDisconnectedCallback({
|
|
296
|
+
code: 500,
|
|
297
|
+
reason: err?.message || "Transport error",
|
|
298
|
+
});
|
|
299
|
+
});
|
|
106
300
|
}
|
|
107
301
|
|
|
108
302
|
send({ senderId, receiverId, receiverIds, data }) {
|
|
@@ -114,14 +308,16 @@ export class DNotifier {
|
|
|
114
308
|
|
|
115
309
|
const metadata = {
|
|
116
310
|
type: "text",
|
|
117
|
-
code: 200,
|
|
311
|
+
code: 200,
|
|
118
312
|
appId: this.appId,
|
|
119
313
|
sender: prefixId(this.appId, senderId),
|
|
120
|
-
receivers: receivers.map((id) =>
|
|
314
|
+
receivers: receivers.map((id) =>
|
|
315
|
+
prefixId(this.appId, id)
|
|
316
|
+
),
|
|
121
317
|
timestamp: Date.now(),
|
|
122
318
|
};
|
|
123
319
|
|
|
124
|
-
const payloadBuffer =
|
|
320
|
+
const payloadBuffer = toUint8(JSON.stringify(data));
|
|
125
321
|
const frame = framePacket(metadata, payloadBuffer);
|
|
126
322
|
|
|
127
323
|
this.transport.sendBinary(frame);
|
|
@@ -133,15 +329,16 @@ export class DNotifier {
|
|
|
133
329
|
|
|
134
330
|
const metadata = {
|
|
135
331
|
type,
|
|
136
|
-
code: 202,
|
|
332
|
+
code: 202,
|
|
137
333
|
appId: this.appId,
|
|
138
334
|
sender: prefixId(this.appId, senderId),
|
|
139
|
-
receivers: receiverIds.map((id) =>
|
|
335
|
+
receivers: receiverIds.map((id) =>
|
|
336
|
+
prefixId(this.appId, id)
|
|
337
|
+
),
|
|
140
338
|
timestamp: Date.now(),
|
|
141
339
|
};
|
|
142
340
|
|
|
143
341
|
const frame = framePacket(metadata, buffer);
|
|
144
|
-
|
|
145
342
|
this.transport.sendBinary(frame);
|
|
146
343
|
}
|
|
147
344
|
}
|
|
@@ -1,57 +1,142 @@
|
|
|
1
|
-
import WebSocket from "ws";
|
|
1
|
+
// import WebSocket from "ws";
|
|
2
|
+
// import EventEmitter from "events";
|
|
3
|
+
// import { decodePacket } from "../utils/frame.js";
|
|
4
|
+
|
|
5
|
+
// export class WebsocketTransport extends EventEmitter {
|
|
6
|
+
// constructor() {
|
|
7
|
+
// super();
|
|
8
|
+
// this.socket = null;
|
|
9
|
+
// }
|
|
10
|
+
|
|
11
|
+
// async connect(url) {
|
|
12
|
+
// return new Promise((resolve, reject) => {
|
|
13
|
+
// this.socket = new WebSocket(url);
|
|
14
|
+
|
|
15
|
+
// this.socket.on("open", () => {
|
|
16
|
+
// resolve(true);
|
|
17
|
+
// });
|
|
18
|
+
|
|
19
|
+
// this.socket.on("error", (err) => {
|
|
20
|
+
// console.error("WS error", err);
|
|
21
|
+
// reject(err);
|
|
22
|
+
// });
|
|
23
|
+
|
|
24
|
+
// this.socket.on("close", (code, reason) => {
|
|
25
|
+
// console.warn("WS closed", code, reason.toString());
|
|
26
|
+
// this.emit("close", { code, reason });
|
|
27
|
+
// });
|
|
28
|
+
|
|
29
|
+
// this.socket.on("message", (data, isBinary) => {
|
|
30
|
+
// var chunk = decodePacket(data);
|
|
31
|
+
// if(chunk){
|
|
32
|
+
// this.emit("message", chunk, isBinary);
|
|
33
|
+
// }
|
|
34
|
+
// });
|
|
35
|
+
// });
|
|
36
|
+
// }
|
|
37
|
+
|
|
38
|
+
// send(data) {
|
|
39
|
+
// if (!this.socket || this.socket.readyState !== WebSocket.OPEN) {
|
|
40
|
+
// throw new Error("WebSocket not connected");
|
|
41
|
+
// }
|
|
42
|
+
// this.socket.send(data);
|
|
43
|
+
// }
|
|
44
|
+
|
|
45
|
+
// sendBinary(buffer) {
|
|
46
|
+
// if (!this.socket || this.socket.readyState !== WebSocket.OPEN) {
|
|
47
|
+
// throw new Error("WebSocket not connected");
|
|
48
|
+
// }
|
|
49
|
+
// this.socket.send(buffer, { binary: true });
|
|
50
|
+
// }
|
|
51
|
+
|
|
52
|
+
// close() {
|
|
53
|
+
// if (this.socket) {
|
|
54
|
+
// this.socket.close();
|
|
55
|
+
// }
|
|
56
|
+
// }
|
|
57
|
+
// }
|
|
58
|
+
|
|
59
|
+
|
|
2
60
|
import EventEmitter from "events";
|
|
3
61
|
import { decodePacket } from "../utils/frame.js";
|
|
4
62
|
|
|
5
63
|
export class WebsocketTransport extends EventEmitter {
|
|
6
|
-
constructor() {
|
|
64
|
+
constructor(WebSocketImpl = null) {
|
|
7
65
|
super();
|
|
8
66
|
this.socket = null;
|
|
67
|
+
this.WebSocketImpl =
|
|
68
|
+
WebSocketImpl ||
|
|
69
|
+
(typeof window !== "undefined" ? window.WebSocket : null);
|
|
70
|
+
|
|
71
|
+
if (!this.WebSocketImpl) {
|
|
72
|
+
throw new Error("No WebSocket implementation provided");
|
|
73
|
+
}
|
|
9
74
|
}
|
|
10
75
|
|
|
11
|
-
|
|
76
|
+
connect(url) {
|
|
12
77
|
return new Promise((resolve, reject) => {
|
|
13
|
-
this.socket = new
|
|
78
|
+
this.socket = new this.WebSocketImpl(url);
|
|
14
79
|
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
});
|
|
80
|
+
// ✅ OPEN
|
|
81
|
+
this._on("open", () => resolve(true));
|
|
18
82
|
|
|
19
|
-
|
|
83
|
+
// ❌ ERROR
|
|
84
|
+
this._on("error", (err) => {
|
|
20
85
|
console.error("WS error", err);
|
|
21
86
|
reject(err);
|
|
22
87
|
});
|
|
23
88
|
|
|
24
|
-
|
|
25
|
-
|
|
89
|
+
// 🔌 CLOSE
|
|
90
|
+
this._on("close", (event) => {
|
|
91
|
+
const code = event?.code;
|
|
92
|
+
const reason = event?.reason;
|
|
26
93
|
this.emit("close", { code, reason });
|
|
27
94
|
});
|
|
28
95
|
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
96
|
+
// 📩 MESSAGE
|
|
97
|
+
this._on("message", (event, isBinary) => {
|
|
98
|
+
const data = event?.data ?? event;
|
|
99
|
+
const chunk = decodePacket(data);
|
|
100
|
+
if (chunk) {
|
|
101
|
+
this.emit("message", chunk, isBinary);
|
|
102
|
+
}
|
|
34
103
|
});
|
|
35
104
|
});
|
|
36
105
|
}
|
|
37
106
|
|
|
107
|
+
_on(event, handler) {
|
|
108
|
+
// Node (ws)
|
|
109
|
+
if (this.socket.on) {
|
|
110
|
+
this.socket.on(event, handler);
|
|
111
|
+
}
|
|
112
|
+
// Browser
|
|
113
|
+
else {
|
|
114
|
+
this.socket[`on${event}`] = handler;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
38
118
|
send(data) {
|
|
39
|
-
if (!this.
|
|
119
|
+
if (!this.isOpen()) {
|
|
40
120
|
throw new Error("WebSocket not connected");
|
|
41
121
|
}
|
|
42
122
|
this.socket.send(data);
|
|
43
123
|
}
|
|
44
124
|
|
|
45
125
|
sendBinary(buffer) {
|
|
46
|
-
if (!this.
|
|
126
|
+
if (!this.isOpen()) {
|
|
47
127
|
throw new Error("WebSocket not connected");
|
|
48
128
|
}
|
|
49
|
-
this.socket.send(buffer
|
|
129
|
+
this.socket.send(buffer); // browser + node compatible
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
isOpen() {
|
|
133
|
+
return (
|
|
134
|
+
this.socket &&
|
|
135
|
+
this.socket.readyState === this.WebSocketImpl.OPEN
|
|
136
|
+
);
|
|
50
137
|
}
|
|
51
138
|
|
|
52
139
|
close() {
|
|
53
|
-
|
|
54
|
-
this.socket.close();
|
|
55
|
-
}
|
|
140
|
+
this.socket?.close();
|
|
56
141
|
}
|
|
57
142
|
}
|