@hyper-fetch/sockets 9.6.1 → 9.6.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/__tests__/e2e/e2e.lifecycle.spec.ts +258 -0
- package/__tests__/features/adapter/adapter.connection.spec.ts +27 -6
- package/__tests__/features/adapter/adapter.sse.lifecycle.spec.ts +514 -0
- package/__tests__/features/adapter/adapter.sse.spec.ts +20 -6
- package/__tests__/features/adapter/adapter.websocket.heartbeat.timers.spec.ts +337 -0
- package/__tests__/features/adapter/adapter.websocket.lifecycle.spec.ts +528 -0
- package/__tests__/features/adapter/adapter.websocket.reconnection.spec.ts +669 -0
- package/__tests__/features/delivery/delivery.backpressure.spec.ts +382 -0
- package/__tests__/features/emitter/emitter.sending.spec.ts +493 -0
- package/__tests__/features/emitter/emitter.typescript.spec.ts +153 -0
- package/__tests__/features/listener/listener.dispatch.spec.ts +427 -0
- package/__tests__/features/listener/listener.params.spec.ts +192 -0
- package/__tests__/features/socket/socket.app-manager.spec.ts +24 -2
- package/__tests__/features/socket/socket.interceptors.spec.ts +430 -0
- package/__tests__/utils/controlled-event-source.ts +149 -0
- package/__tests__/utils/controlled-websocket.ts +213 -0
- package/dist/adapter/adapter.bindings.d.ts.map +1 -1
- package/dist/adapter/adapter.d.ts.map +1 -1
- package/dist/adapter-sse/sse-adapter.d.ts.map +1 -1
- package/dist/adapter-websockets/websocket-adapter.d.ts.map +1 -1
- package/dist/emitter/emitter.d.ts.map +1 -1
- package/dist/index.mjs +284 -105
- package/dist/index.mjs.map +1 -1
- package/dist/listener/listener.d.ts +2 -0
- package/dist/listener/listener.d.ts.map +1 -1
- package/dist/socket/socket.d.ts +1 -1
- package/dist/socket/socket.utils.d.ts +11 -3
- package/dist/socket/socket.utils.d.ts.map +1 -1
- package/dist/utils/topic.utils.d.ts +10 -0
- package/dist/utils/topic.utils.d.ts.map +1 -0
- package/package.json +1 -1
- package/src/adapter/adapter.bindings.ts +44 -20
- package/src/adapter/adapter.ts +29 -10
- package/src/adapter-sse/sse-adapter.ts +95 -15
- package/src/adapter-websockets/websocket-adapter.ts +124 -41
- package/src/emitter/emitter.ts +16 -9
- package/src/listener/listener.ts +7 -8
- package/src/socket/socket.utils.ts +20 -6
- package/src/utils/topic.utils.ts +26 -0
|
@@ -0,0 +1,493 @@
|
|
|
1
|
+
import { ServerSentEventsAdapter } from "adapter-sse";
|
|
2
|
+
import { Socket } from "socket";
|
|
3
|
+
|
|
4
|
+
import {
|
|
5
|
+
installControlledEventSource,
|
|
6
|
+
openEventSource,
|
|
7
|
+
uninstallControlledEventSource,
|
|
8
|
+
} from "../../utils/controlled-event-source";
|
|
9
|
+
import {
|
|
10
|
+
ControlledWebSocket,
|
|
11
|
+
flushPromises,
|
|
12
|
+
installControlledWebSocket,
|
|
13
|
+
openWebSocket,
|
|
14
|
+
uninstallControlledWebSocket,
|
|
15
|
+
waitForWebSocket,
|
|
16
|
+
} from "../../utils/controlled-websocket";
|
|
17
|
+
|
|
18
|
+
type ChatMessage = { text: string };
|
|
19
|
+
|
|
20
|
+
describe("Emitter [ Sending ]", () => {
|
|
21
|
+
let socket: Socket;
|
|
22
|
+
|
|
23
|
+
/** Collects everything a socket reports about failed emits */
|
|
24
|
+
const trackFailures = (instance: Socket<any> = socket) => {
|
|
25
|
+
const emitterErrors: { message: string; topic: string; payload: unknown }[] = [];
|
|
26
|
+
const socketErrors: string[] = [];
|
|
27
|
+
instance.events.onEmitterError(({ error, emitter }) => {
|
|
28
|
+
emitterErrors.push({ message: error.message, topic: emitter.topic, payload: emitter.payload });
|
|
29
|
+
});
|
|
30
|
+
instance.onError(({ error }: { error: Error }) => socketErrors.push(error.message));
|
|
31
|
+
return { emitterErrors, socketErrors };
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
beforeEach(() => {
|
|
35
|
+
installControlledWebSocket();
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
afterEach(async () => {
|
|
39
|
+
await socket?.disconnect();
|
|
40
|
+
uninstallControlledWebSocket();
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
describe("When the connection is open", () => {
|
|
44
|
+
let websocket: ControlledWebSocket;
|
|
45
|
+
|
|
46
|
+
beforeEach(async () => {
|
|
47
|
+
socket = new Socket({ url: "ws://emitter" });
|
|
48
|
+
websocket = await openWebSocket();
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
it("should send the payload passed to emit", async () => {
|
|
52
|
+
socket
|
|
53
|
+
.createEmitter<ChatMessage>()({ topic: "chat" })
|
|
54
|
+
.emit({ payload: { text: "hi" } });
|
|
55
|
+
await flushPromises();
|
|
56
|
+
|
|
57
|
+
expect(websocket.sentMessages).toStrictEqual([{ topic: "chat", data: { text: "hi" } }]);
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
it("should send the payload set on the emitter", async () => {
|
|
61
|
+
socket.createEmitter<ChatMessage>()({ topic: "chat" }).setPayload({ text: "hi" }).emit();
|
|
62
|
+
await flushPromises();
|
|
63
|
+
|
|
64
|
+
expect(websocket.sentMessages).toStrictEqual([{ topic: "chat", data: { text: "hi" } }]);
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
it("should prefer the payload passed to emit over the one set on the emitter", async () => {
|
|
68
|
+
socket
|
|
69
|
+
.createEmitter<ChatMessage>()({ topic: "chat" })
|
|
70
|
+
.setPayload({ text: "template" })
|
|
71
|
+
.emit({ payload: { text: "override" } });
|
|
72
|
+
await flushPromises();
|
|
73
|
+
|
|
74
|
+
expect(websocket.sentMessages).toStrictEqual([{ topic: "chat", data: { text: "override" } }]);
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
it("should fill the topic params passed to emit", async () => {
|
|
78
|
+
socket
|
|
79
|
+
.createEmitter<ChatMessage>()({ topic: "rooms/:roomId/users/:userId" })
|
|
80
|
+
.emit({ payload: { text: "hi" }, params: { roomId: 7, userId: "ann" } });
|
|
81
|
+
await flushPromises();
|
|
82
|
+
|
|
83
|
+
expect(websocket.sentMessages[0].topic).toBe("rooms/7/users/ann");
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
it.each([
|
|
87
|
+
{ name: "zero", payload: 0 },
|
|
88
|
+
{ name: "an empty string", payload: "" },
|
|
89
|
+
{ name: "false", payload: false },
|
|
90
|
+
{ name: "null", payload: null },
|
|
91
|
+
{ name: "an empty array", payload: [] },
|
|
92
|
+
])("should send $name as a payload", async ({ payload }) => {
|
|
93
|
+
socket.createEmitter<unknown>()({ topic: "values" }).emit({ payload });
|
|
94
|
+
await flushPromises();
|
|
95
|
+
|
|
96
|
+
expect(websocket.sentMessages).toStrictEqual([{ topic: "values", data: payload }]);
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
it("should keep the order of many messages", async () => {
|
|
100
|
+
const emitter = socket.createEmitter<number>()({ topic: "sequence" });
|
|
101
|
+
|
|
102
|
+
for (let i = 0; i < 500; i += 1) {
|
|
103
|
+
emitter.emit({ payload: i });
|
|
104
|
+
}
|
|
105
|
+
await flushPromises();
|
|
106
|
+
|
|
107
|
+
expect(websocket.sentMessages.map((message) => message.data)).toStrictEqual(
|
|
108
|
+
Array.from({ length: 500 }, (_, index) => index),
|
|
109
|
+
);
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
it("should keep the order of messages emitted on different topics", async () => {
|
|
113
|
+
const first = socket.createEmitter<number>()({ topic: "first" });
|
|
114
|
+
const second = socket.createEmitter<number>()({ topic: "second" });
|
|
115
|
+
|
|
116
|
+
first.emit({ payload: 1 });
|
|
117
|
+
second.emit({ payload: 2 });
|
|
118
|
+
first.emit({ payload: 3 });
|
|
119
|
+
second.emit({ payload: 4 });
|
|
120
|
+
await flushPromises();
|
|
121
|
+
|
|
122
|
+
expect(websocket.sentMessages).toStrictEqual([
|
|
123
|
+
{ topic: "first", data: 1 },
|
|
124
|
+
{ topic: "second", data: 2 },
|
|
125
|
+
{ topic: "first", data: 3 },
|
|
126
|
+
{ topic: "second", data: 4 },
|
|
127
|
+
]);
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
it("should announce every sent message with the emitter start events", async () => {
|
|
131
|
+
const emitter = socket.createEmitter<ChatMessage>()({ topic: "chat" });
|
|
132
|
+
const global = vi.fn();
|
|
133
|
+
const byTopic = vi.fn();
|
|
134
|
+
const otherTopic = vi.fn();
|
|
135
|
+
socket.events.onEmitterStartEvent(({ emitter: started }) => global(started.topic, started.payload));
|
|
136
|
+
socket.events.onEmitterStartEventByTopic(emitter, ({ emitter: started }) => byTopic(started.payload));
|
|
137
|
+
socket.events.onEmitterStartEventByTopic({ topic: "other" }, otherTopic);
|
|
138
|
+
|
|
139
|
+
emitter.emit({ payload: { text: "hi" } });
|
|
140
|
+
await flushPromises();
|
|
141
|
+
|
|
142
|
+
expect(global).toHaveBeenCalledWith("chat", { text: "hi" });
|
|
143
|
+
expect(byTopic).toHaveBeenCalledWith({ text: "hi" });
|
|
144
|
+
expect(otherTopic).not.toHaveBeenCalled();
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
it("should not change the emitter used as a template", async () => {
|
|
148
|
+
const emitter = socket.createEmitter<ChatMessage>()({ topic: "rooms/:roomId" });
|
|
149
|
+
|
|
150
|
+
emitter.emit({ payload: { text: "hi" }, params: { roomId: 1 } });
|
|
151
|
+
await flushPromises();
|
|
152
|
+
|
|
153
|
+
expect(emitter.topic).toBe("rooms/:roomId");
|
|
154
|
+
expect(emitter.payload).toBeUndefined();
|
|
155
|
+
expect(emitter.params).toBeUndefined();
|
|
156
|
+
});
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
describe("When mapping the payload", () => {
|
|
160
|
+
let websocket: ControlledWebSocket;
|
|
161
|
+
|
|
162
|
+
beforeEach(async () => {
|
|
163
|
+
socket = new Socket({ url: "ws://emitter" });
|
|
164
|
+
websocket = await openWebSocket();
|
|
165
|
+
});
|
|
166
|
+
|
|
167
|
+
it("should send the mapped payload", async () => {
|
|
168
|
+
socket
|
|
169
|
+
.createEmitter<ChatMessage>()({ topic: "chat" })
|
|
170
|
+
.setPayloadMapper((payload) => ({ ...payload, version: 2 }))
|
|
171
|
+
.emit({ payload: { text: "hi" } });
|
|
172
|
+
await flushPromises();
|
|
173
|
+
|
|
174
|
+
expect(websocket.sentMessages).toStrictEqual([{ topic: "chat", data: { text: "hi", version: 2 } }]);
|
|
175
|
+
});
|
|
176
|
+
|
|
177
|
+
it("should wait for an async payload mapper", async () => {
|
|
178
|
+
socket
|
|
179
|
+
.createEmitter<ChatMessage>()({ topic: "chat" })
|
|
180
|
+
.setPayloadMapper(async (payload) => ({ ...payload, signed: true }))
|
|
181
|
+
.emit({ payload: { text: "hi" } });
|
|
182
|
+
await flushPromises();
|
|
183
|
+
|
|
184
|
+
expect(websocket.sentMessages).toStrictEqual([{ topic: "chat", data: { text: "hi", signed: true } }]);
|
|
185
|
+
});
|
|
186
|
+
|
|
187
|
+
it("should keep the mapper on clones created by the emitter methods", async () => {
|
|
188
|
+
socket
|
|
189
|
+
.createEmitter<ChatMessage>()({ topic: "rooms/:roomId" })
|
|
190
|
+
.setPayloadMapper((payload) => ({ ...payload, mapped: true }))
|
|
191
|
+
.setParams({ roomId: 1 })
|
|
192
|
+
.setPayload({ text: "hi" })
|
|
193
|
+
.emit();
|
|
194
|
+
await flushPromises();
|
|
195
|
+
|
|
196
|
+
expect(websocket.sentMessages).toStrictEqual([{ topic: "rooms/1", data: { text: "hi", mapped: true } }]);
|
|
197
|
+
});
|
|
198
|
+
|
|
199
|
+
it("should map the payload once per emit", async () => {
|
|
200
|
+
const mapper = vi.fn((payload: ChatMessage) => ({ ...payload, mapped: true }));
|
|
201
|
+
const emitter = socket.createEmitter<ChatMessage>()({ topic: "chat" }).setPayloadMapper(mapper);
|
|
202
|
+
|
|
203
|
+
emitter.emit({ payload: { text: "one" } });
|
|
204
|
+
emitter.emit({ payload: { text: "two" } });
|
|
205
|
+
await flushPromises();
|
|
206
|
+
|
|
207
|
+
expect(mapper).toHaveBeenCalledTimes(2);
|
|
208
|
+
expect(websocket.sentMessages.map((message) => message.data)).toStrictEqual([
|
|
209
|
+
{ text: "one", mapped: true },
|
|
210
|
+
{ text: "two", mapped: true },
|
|
211
|
+
]);
|
|
212
|
+
});
|
|
213
|
+
|
|
214
|
+
it("should report a throwing payload mapper and send nothing", async () => {
|
|
215
|
+
const { emitterErrors, socketErrors } = trackFailures();
|
|
216
|
+
|
|
217
|
+
socket
|
|
218
|
+
.createEmitter<ChatMessage>()({ topic: "chat" })
|
|
219
|
+
.setPayloadMapper(() => {
|
|
220
|
+
throw new Error("Cannot serialize");
|
|
221
|
+
})
|
|
222
|
+
.emit({ payload: { text: "hi" } });
|
|
223
|
+
await flushPromises();
|
|
224
|
+
|
|
225
|
+
expect(websocket.sent).toStrictEqual([]);
|
|
226
|
+
expect(emitterErrors).toStrictEqual([{ message: "Cannot serialize", topic: "chat", payload: { text: "hi" } }]);
|
|
227
|
+
expect(socketErrors).toStrictEqual(["Cannot serialize"]);
|
|
228
|
+
});
|
|
229
|
+
|
|
230
|
+
it("should report a rejecting payload mapper and send nothing", async () => {
|
|
231
|
+
const { emitterErrors } = trackFailures();
|
|
232
|
+
|
|
233
|
+
socket
|
|
234
|
+
.createEmitter<ChatMessage>()({ topic: "chat" })
|
|
235
|
+
.setPayloadMapper(async () => {
|
|
236
|
+
throw new Error("Cannot sign");
|
|
237
|
+
})
|
|
238
|
+
.emit({ payload: { text: "hi" } });
|
|
239
|
+
await flushPromises();
|
|
240
|
+
|
|
241
|
+
expect(websocket.sent).toStrictEqual([]);
|
|
242
|
+
expect(emitterErrors.map((failure) => failure.message)).toStrictEqual(["Cannot sign"]);
|
|
243
|
+
});
|
|
244
|
+
});
|
|
245
|
+
|
|
246
|
+
describe("When the connection is not open", () => {
|
|
247
|
+
it("should drop the message and report it when the socket never connected", async () => {
|
|
248
|
+
socket = new Socket({ url: "ws://emitter", adapterOptions: { autoConnect: false } });
|
|
249
|
+
const { emitterErrors, socketErrors } = trackFailures();
|
|
250
|
+
const started = vi.fn();
|
|
251
|
+
socket.events.onEmitterStartEvent(started);
|
|
252
|
+
|
|
253
|
+
socket
|
|
254
|
+
.createEmitter<ChatMessage>()({ topic: "chat" })
|
|
255
|
+
.emit({ payload: { text: "hi" } });
|
|
256
|
+
await flushPromises();
|
|
257
|
+
|
|
258
|
+
expect(emitterErrors).toStrictEqual([
|
|
259
|
+
{ message: "Cannot emit event when connection is not open", topic: "chat", payload: { text: "hi" } },
|
|
260
|
+
]);
|
|
261
|
+
expect(socketErrors).toStrictEqual([]);
|
|
262
|
+
expect(started).not.toHaveBeenCalled();
|
|
263
|
+
expect(ControlledWebSocket.instances).toHaveLength(0);
|
|
264
|
+
});
|
|
265
|
+
|
|
266
|
+
it("should drop the message and report it while the socket is connecting", async () => {
|
|
267
|
+
socket = new Socket({ url: "ws://emitter" });
|
|
268
|
+
const websocket = await waitForWebSocket();
|
|
269
|
+
const { emitterErrors } = trackFailures();
|
|
270
|
+
|
|
271
|
+
socket
|
|
272
|
+
.createEmitter<ChatMessage>()({ topic: "chat" })
|
|
273
|
+
.emit({ payload: { text: "hi" } });
|
|
274
|
+
await flushPromises();
|
|
275
|
+
websocket.serverOpen();
|
|
276
|
+
await flushPromises();
|
|
277
|
+
|
|
278
|
+
expect(websocket.sent).toStrictEqual([]);
|
|
279
|
+
expect(emitterErrors.map((failure) => failure.message)).toStrictEqual([
|
|
280
|
+
"Cannot emit event when connection is not open",
|
|
281
|
+
]);
|
|
282
|
+
});
|
|
283
|
+
|
|
284
|
+
it("should drop the message and report it after a disconnect", async () => {
|
|
285
|
+
socket = new Socket({ url: "ws://emitter" });
|
|
286
|
+
const websocket = await openWebSocket();
|
|
287
|
+
await socket.disconnect();
|
|
288
|
+
const { emitterErrors } = trackFailures();
|
|
289
|
+
|
|
290
|
+
socket
|
|
291
|
+
.createEmitter<ChatMessage>()({ topic: "chat" })
|
|
292
|
+
.emit({ payload: { text: "hi" } });
|
|
293
|
+
await flushPromises();
|
|
294
|
+
|
|
295
|
+
expect(websocket.sent).toStrictEqual([]);
|
|
296
|
+
expect(emitterErrors).toHaveLength(1);
|
|
297
|
+
});
|
|
298
|
+
|
|
299
|
+
it("should report the dropped message only to the subscribers of its topic", async () => {
|
|
300
|
+
socket = new Socket({ url: "ws://emitter", adapterOptions: { autoConnect: false } });
|
|
301
|
+
const emitter = socket.createEmitter<ChatMessage>()({ topic: "chat" });
|
|
302
|
+
const sameTopic = vi.fn();
|
|
303
|
+
const otherTopic = vi.fn();
|
|
304
|
+
socket.events.onEmitterErrorByTopic(emitter, sameTopic);
|
|
305
|
+
socket.events.onEmitterErrorByTopic({ topic: "other" }, otherTopic);
|
|
306
|
+
|
|
307
|
+
emitter.emit({ payload: { text: "hi" } });
|
|
308
|
+
await flushPromises();
|
|
309
|
+
|
|
310
|
+
expect(sameTopic).toHaveBeenCalledTimes(1);
|
|
311
|
+
expect(otherTopic).not.toHaveBeenCalled();
|
|
312
|
+
});
|
|
313
|
+
|
|
314
|
+
it("should not run the payload mapper or the interceptors for a dropped message", async () => {
|
|
315
|
+
const mapper = vi.fn((payload: ChatMessage) => payload);
|
|
316
|
+
const interceptor = vi.fn(({ emitter }) => emitter);
|
|
317
|
+
socket = new Socket({ url: "ws://emitter", adapterOptions: { autoConnect: false } }).onSend(interceptor);
|
|
318
|
+
|
|
319
|
+
socket
|
|
320
|
+
.createEmitter<ChatMessage>()({ topic: "chat" })
|
|
321
|
+
.setPayloadMapper(mapper)
|
|
322
|
+
.emit({ payload: { text: "hi" } });
|
|
323
|
+
await flushPromises();
|
|
324
|
+
|
|
325
|
+
expect(mapper).not.toHaveBeenCalled();
|
|
326
|
+
expect(interceptor).not.toHaveBeenCalled();
|
|
327
|
+
});
|
|
328
|
+
|
|
329
|
+
it("should not send dropped messages once the connection opens", async () => {
|
|
330
|
+
socket = new Socket({ url: "ws://emitter", adapterOptions: { autoConnect: false } });
|
|
331
|
+
const emitter = socket.createEmitter<ChatMessage>()({ topic: "chat" });
|
|
332
|
+
trackFailures();
|
|
333
|
+
|
|
334
|
+
emitter.emit({ payload: { text: "too early" } });
|
|
335
|
+
const connecting = socket.connect();
|
|
336
|
+
const websocket = await openWebSocket();
|
|
337
|
+
await connecting;
|
|
338
|
+
emitter.emit({ payload: { text: "on time" } });
|
|
339
|
+
await flushPromises();
|
|
340
|
+
|
|
341
|
+
expect(websocket.sentMessages).toStrictEqual([{ topic: "chat", data: { text: "on time" } }]);
|
|
342
|
+
});
|
|
343
|
+
|
|
344
|
+
it("should send again after reconnecting", async () => {
|
|
345
|
+
socket = new Socket({ url: "ws://emitter" });
|
|
346
|
+
await openWebSocket();
|
|
347
|
+
const emitter = socket.createEmitter<ChatMessage>()({ topic: "chat" });
|
|
348
|
+
|
|
349
|
+
const reconnecting = socket.reconnect();
|
|
350
|
+
const next = await openWebSocket(2);
|
|
351
|
+
await reconnecting;
|
|
352
|
+
emitter.emit({ payload: { text: "back" } });
|
|
353
|
+
await flushPromises();
|
|
354
|
+
|
|
355
|
+
expect(next.sentMessages).toStrictEqual([{ topic: "chat", data: { text: "back" } }]);
|
|
356
|
+
});
|
|
357
|
+
});
|
|
358
|
+
|
|
359
|
+
describe("When the transport cannot send the message", () => {
|
|
360
|
+
it("should report an encoder failure for the emitter and the socket", async () => {
|
|
361
|
+
socket = new Socket({
|
|
362
|
+
url: "ws://emitter",
|
|
363
|
+
adapterOptions: {
|
|
364
|
+
encode: () => {
|
|
365
|
+
throw new Error("Cannot encode");
|
|
366
|
+
},
|
|
367
|
+
},
|
|
368
|
+
});
|
|
369
|
+
const websocket = await openWebSocket();
|
|
370
|
+
const { emitterErrors, socketErrors } = trackFailures();
|
|
371
|
+
|
|
372
|
+
socket
|
|
373
|
+
.createEmitter<ChatMessage>()({ topic: "chat" })
|
|
374
|
+
.emit({ payload: { text: "hi" } });
|
|
375
|
+
await flushPromises();
|
|
376
|
+
|
|
377
|
+
expect(websocket.sent).toStrictEqual([]);
|
|
378
|
+
expect(emitterErrors.map((failure) => failure.message)).toStrictEqual(["Cannot encode"]);
|
|
379
|
+
expect(socketErrors).toStrictEqual(["Cannot encode"]);
|
|
380
|
+
});
|
|
381
|
+
|
|
382
|
+
it("should report a payload that cannot be serialized", async () => {
|
|
383
|
+
socket = new Socket({ url: "ws://emitter" });
|
|
384
|
+
const websocket = await openWebSocket();
|
|
385
|
+
const { emitterErrors } = trackFailures();
|
|
386
|
+
const circular: Record<string, unknown> = {};
|
|
387
|
+
circular.self = circular;
|
|
388
|
+
|
|
389
|
+
socket.createEmitter<unknown>()({ topic: "chat" }).emit({ payload: circular });
|
|
390
|
+
await flushPromises();
|
|
391
|
+
|
|
392
|
+
expect(websocket.sent).toStrictEqual([]);
|
|
393
|
+
expect(emitterErrors).toHaveLength(1);
|
|
394
|
+
expect(socket.adapter.connected).toBeTrue();
|
|
395
|
+
});
|
|
396
|
+
|
|
397
|
+
it("should report a transport that throws on send", async () => {
|
|
398
|
+
socket = new Socket({ url: "ws://emitter" });
|
|
399
|
+
const websocket = await openWebSocket();
|
|
400
|
+
const { emitterErrors, socketErrors } = trackFailures();
|
|
401
|
+
websocket.send = () => {
|
|
402
|
+
throw new Error("Buffer is full");
|
|
403
|
+
};
|
|
404
|
+
|
|
405
|
+
socket
|
|
406
|
+
.createEmitter<ChatMessage>()({ topic: "chat" })
|
|
407
|
+
.emit({ payload: { text: "hi" } });
|
|
408
|
+
await flushPromises();
|
|
409
|
+
|
|
410
|
+
expect(emitterErrors.map((failure) => failure.message)).toStrictEqual(["Buffer is full"]);
|
|
411
|
+
expect(socketErrors).toStrictEqual(["Buffer is full"]);
|
|
412
|
+
});
|
|
413
|
+
|
|
414
|
+
it("should keep sending the next messages after a failure", async () => {
|
|
415
|
+
socket = new Socket({
|
|
416
|
+
url: "ws://emitter",
|
|
417
|
+
adapterOptions: {
|
|
418
|
+
encode: ({ topic, payload }) => {
|
|
419
|
+
if (payload === "bad") {
|
|
420
|
+
throw new Error("Cannot encode");
|
|
421
|
+
}
|
|
422
|
+
return JSON.stringify({ topic, data: payload });
|
|
423
|
+
},
|
|
424
|
+
},
|
|
425
|
+
});
|
|
426
|
+
const websocket = await openWebSocket();
|
|
427
|
+
trackFailures();
|
|
428
|
+
const emitter = socket.createEmitter<string>()({ topic: "chat" });
|
|
429
|
+
|
|
430
|
+
emitter.emit({ payload: "good" });
|
|
431
|
+
emitter.emit({ payload: "bad" });
|
|
432
|
+
emitter.emit({ payload: "good again" });
|
|
433
|
+
await flushPromises();
|
|
434
|
+
|
|
435
|
+
expect(websocket.sentMessages.map((message) => message.data)).toStrictEqual(["good", "good again"]);
|
|
436
|
+
});
|
|
437
|
+
});
|
|
438
|
+
|
|
439
|
+
describe("When the adapter cannot emit at all", () => {
|
|
440
|
+
afterEach(() => {
|
|
441
|
+
uninstallControlledEventSource();
|
|
442
|
+
});
|
|
443
|
+
|
|
444
|
+
it("should throw from emit on a Server-Sent Events socket", async () => {
|
|
445
|
+
installControlledEventSource();
|
|
446
|
+
const sseSocket = new Socket({ url: "http://emitter", adapter: ServerSentEventsAdapter });
|
|
447
|
+
await openEventSource();
|
|
448
|
+
|
|
449
|
+
expect(() =>
|
|
450
|
+
sseSocket
|
|
451
|
+
.createEmitter<ChatMessage>()({ topic: "chat" })
|
|
452
|
+
.emit({ payload: { text: "hi" } }),
|
|
453
|
+
).toThrow("Cannot emit events in SSE adapter");
|
|
454
|
+
await sseSocket.disconnect();
|
|
455
|
+
});
|
|
456
|
+
|
|
457
|
+
it("should report the rejection of a custom adapter instead of leaving it unhandled", async () => {
|
|
458
|
+
socket = new Socket({ url: "ws://emitter" });
|
|
459
|
+
await openWebSocket();
|
|
460
|
+
const { emitterErrors, socketErrors } = trackFailures();
|
|
461
|
+
socket.adapter.emit = async () => {
|
|
462
|
+
throw new Error("Cannot emit from this adapter");
|
|
463
|
+
};
|
|
464
|
+
|
|
465
|
+
expect(() =>
|
|
466
|
+
socket
|
|
467
|
+
.createEmitter<ChatMessage>()({ topic: "chat" })
|
|
468
|
+
.emit({ payload: { text: "hi" } }),
|
|
469
|
+
).not.toThrow();
|
|
470
|
+
await flushPromises();
|
|
471
|
+
|
|
472
|
+
expect(emitterErrors).toStrictEqual([
|
|
473
|
+
{ message: "Cannot emit from this adapter", topic: "chat", payload: { text: "hi" } },
|
|
474
|
+
]);
|
|
475
|
+
expect(socketErrors).toStrictEqual(["Cannot emit from this adapter"]);
|
|
476
|
+
});
|
|
477
|
+
|
|
478
|
+
it("should wrap a non-error rejection of a custom adapter", async () => {
|
|
479
|
+
socket = new Socket({ url: "ws://emitter" });
|
|
480
|
+
await openWebSocket();
|
|
481
|
+
const { emitterErrors } = trackFailures();
|
|
482
|
+
// eslint-disable-next-line prefer-promise-reject-errors
|
|
483
|
+
socket.adapter.emit = () => Promise.reject("plain text failure");
|
|
484
|
+
|
|
485
|
+
socket
|
|
486
|
+
.createEmitter<ChatMessage>()({ topic: "chat" })
|
|
487
|
+
.emit({ payload: { text: "hi" } });
|
|
488
|
+
await flushPromises();
|
|
489
|
+
|
|
490
|
+
expect(emitterErrors.map((failure) => failure.message)).toStrictEqual(["plain text failure"]);
|
|
491
|
+
});
|
|
492
|
+
});
|
|
493
|
+
});
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import type { ServerSentEventsAdapterType } from "adapter-sse";
|
|
2
|
+
import { ServerSentEventsAdapter } from "adapter-sse";
|
|
3
|
+
import type { WebsocketAdapterType } from "adapter-websockets";
|
|
4
|
+
import type { EmitterInstance, EmitterModel } from "emitter";
|
|
5
|
+
import type { ListenerInstance, ListenerModel } from "listener";
|
|
6
|
+
import { Socket } from "socket";
|
|
7
|
+
import type {
|
|
8
|
+
ExtractEmitterHasParamsType,
|
|
9
|
+
ExtractEmitterHasPayloadType,
|
|
10
|
+
ExtractEmitterPayloadType,
|
|
11
|
+
ExtractEmitterTopicType,
|
|
12
|
+
ExtractListenerResponseType,
|
|
13
|
+
ExtractListenerTopicType,
|
|
14
|
+
ExtractSocketAdapterType,
|
|
15
|
+
ExtractSocketExtraType,
|
|
16
|
+
} from "types";
|
|
17
|
+
import { expectTypeOf } from "vitest";
|
|
18
|
+
|
|
19
|
+
type ChatMessage = { text: string; author: string };
|
|
20
|
+
|
|
21
|
+
const socket = new Socket({ url: "ws://types", adapterOptions: { autoConnect: false } });
|
|
22
|
+
const sseSocket = new Socket({
|
|
23
|
+
url: "http://types",
|
|
24
|
+
adapter: ServerSentEventsAdapter,
|
|
25
|
+
adapterOptions: { autoConnect: false },
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
const emitter = socket.createEmitter<ChatMessage>()({ topic: "chat" });
|
|
29
|
+
const roomEmitter = socket.createEmitter<ChatMessage>()({ topic: "rooms/:roomId" });
|
|
30
|
+
const listener = socket.createListener<ChatMessage>()({ topic: "chat" });
|
|
31
|
+
|
|
32
|
+
describe("Socket [ TypeScript ]", () => {
|
|
33
|
+
describe("When typing emitters", () => {
|
|
34
|
+
it("should extract the payload and the topic", () => {
|
|
35
|
+
expectTypeOf<ExtractEmitterPayloadType<typeof emitter>>().toEqualTypeOf<ChatMessage>();
|
|
36
|
+
expectTypeOf<ExtractEmitterTopicType<typeof emitter>>().toEqualTypeOf<"chat">();
|
|
37
|
+
expectTypeOf<ExtractEmitterTopicType<typeof roomEmitter>>().toEqualTypeOf<"rooms/:roomId">();
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
it("should track whether the payload and the params were set", () => {
|
|
41
|
+
const withPayload = emitter.setPayload({ text: "hi", author: "me" });
|
|
42
|
+
const withParams = roomEmitter.setParams({ roomId: 1 });
|
|
43
|
+
|
|
44
|
+
expectTypeOf<ExtractEmitterHasPayloadType<typeof emitter>>().toEqualTypeOf<false>();
|
|
45
|
+
expectTypeOf<ExtractEmitterHasPayloadType<typeof withPayload>>().toEqualTypeOf<true>();
|
|
46
|
+
expectTypeOf<ExtractEmitterHasParamsType<typeof roomEmitter>>().toEqualTypeOf<false>();
|
|
47
|
+
expectTypeOf<ExtractEmitterHasParamsType<typeof withParams>>().toEqualTypeOf<true>();
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
it("should require the payload in emit until it is set", () => {
|
|
51
|
+
expectTypeOf(emitter.emit).toBeCallableWith({ payload: { text: "hi", author: "me" } });
|
|
52
|
+
expectTypeOf(emitter.setPayload({ text: "hi", author: "me" }).emit).toBeCallableWith();
|
|
53
|
+
// @ts-expect-error - payload is required
|
|
54
|
+
expectTypeOf(emitter.emit).toBeCallableWith();
|
|
55
|
+
// @ts-expect-error - payload misses a field
|
|
56
|
+
expectTypeOf(emitter.emit).toBeCallableWith({ payload: { text: "hi" } });
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
it("should reject payloads of a wrong shape in setPayload", () => {
|
|
60
|
+
expectTypeOf(emitter.setPayload).toBeCallableWith({ text: "hi", author: "me" });
|
|
61
|
+
// @ts-expect-error - text must be a string
|
|
62
|
+
emitter.setPayload({ text: 1, author: "me" });
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
it("should type the payload mapper input", () => {
|
|
66
|
+
emitter.setPayloadMapper((payload) => {
|
|
67
|
+
expectTypeOf(payload).toEqualTypeOf<ChatMessage>();
|
|
68
|
+
return payload;
|
|
69
|
+
});
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
it("should return nothing from emit", () => {
|
|
73
|
+
expectTypeOf(emitter.emit).returns.toEqualTypeOf<void>();
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
it("should accept concrete emitters as instances and models", () => {
|
|
77
|
+
expectTypeOf(emitter).toExtend<EmitterInstance>();
|
|
78
|
+
expectTypeOf(emitter).toExtend<EmitterInstance<{ payload: ChatMessage }>>();
|
|
79
|
+
expectTypeOf<EmitterModel<{ payload: ChatMessage; topic: "chat" }>["topic"]>().toEqualTypeOf<"chat">();
|
|
80
|
+
expectTypeOf<ExtractEmitterPayloadType<EmitterModel<{ payload: ChatMessage }>>>().toEqualTypeOf<ChatMessage>();
|
|
81
|
+
expectTypeOf<ExtractEmitterPayloadType<EmitterModel>>().toEqualTypeOf<undefined>();
|
|
82
|
+
});
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
describe("When typing listeners", () => {
|
|
86
|
+
it("should extract the response and the topic", () => {
|
|
87
|
+
expectTypeOf<ExtractListenerResponseType<typeof listener>>().toEqualTypeOf<ChatMessage>();
|
|
88
|
+
expectTypeOf<ExtractListenerTopicType<typeof listener>>().toEqualTypeOf<"chat">();
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
it("should type the callback data and return an unsubscribe function", () => {
|
|
92
|
+
const stop = listener.listen(({ data }) => {
|
|
93
|
+
expectTypeOf(data).toEqualTypeOf<ChatMessage>();
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
expectTypeOf(stop).toEqualTypeOf<() => void>();
|
|
97
|
+
stop();
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
it("should accept concrete listeners as instances and models", () => {
|
|
101
|
+
expectTypeOf(listener).toExtend<ListenerInstance>();
|
|
102
|
+
expectTypeOf(listener).toExtend<ListenerInstance<{ response: { text: string } }>>();
|
|
103
|
+
expectTypeOf<
|
|
104
|
+
ExtractListenerResponseType<ListenerModel<{ response: ChatMessage }>>
|
|
105
|
+
>().toEqualTypeOf<ChatMessage>();
|
|
106
|
+
expectTypeOf<ExtractListenerResponseType<ListenerModel>>().toEqualTypeOf<unknown>();
|
|
107
|
+
});
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
describe("When typing sockets", () => {
|
|
111
|
+
it("should default to the WebSocket adapter", () => {
|
|
112
|
+
expectTypeOf<ExtractSocketAdapterType<typeof socket>>().toEqualTypeOf<WebsocketAdapterType>();
|
|
113
|
+
expectTypeOf<ExtractSocketExtraType<typeof socket>>().toEqualTypeOf<MessageEvent<any>>();
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
it("should follow the adapter passed to the socket", () => {
|
|
117
|
+
expectTypeOf<ExtractSocketAdapterType<typeof sseSocket>>().toEqualTypeOf<ServerSentEventsAdapterType>();
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
it("should type the adapter options by the adapter", () => {
|
|
121
|
+
expectTypeOf<NonNullable<typeof socket.options.adapterOptions>>().toHaveProperty("heartbeat");
|
|
122
|
+
expectTypeOf<NonNullable<typeof sseSocket.options.adapterOptions>>().toHaveProperty("eventSourceInit");
|
|
123
|
+
expectTypeOf<NonNullable<typeof sseSocket.options.adapterOptions>>().not.toHaveProperty("heartbeat");
|
|
124
|
+
expectTypeOf<NonNullable<typeof socket.options.adapterOptions>>().not.toHaveProperty("eventSourceInit");
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
it("should type the connection passed to onConnect", () => {
|
|
128
|
+
socket.onConnect(({ connection, attempt }) => {
|
|
129
|
+
expectTypeOf(attempt).toEqualTypeOf<number>();
|
|
130
|
+
expectTypeOf(connection.url).toEqualTypeOf<string>();
|
|
131
|
+
expectTypeOf<NonNullable<typeof connection.adapterOptions>>().toHaveProperty("protocols");
|
|
132
|
+
return connection;
|
|
133
|
+
});
|
|
134
|
+
// @ts-expect-error - the interceptor must return the connection
|
|
135
|
+
socket.onConnect(() => null);
|
|
136
|
+
socket.unstable_onConnectCallbacks = [];
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
it("should return promises from the connection methods", () => {
|
|
140
|
+
expectTypeOf(socket.connect).returns.toEqualTypeOf<Promise<void>>();
|
|
141
|
+
expectTypeOf(socket.disconnect).returns.toEqualTypeOf<Promise<void>>();
|
|
142
|
+
expectTypeOf(socket.reconnect).returns.toEqualTypeOf<Promise<void>>();
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
it("should keep the socket type through the chained callbacks", () => {
|
|
146
|
+
const chained = socket.onConnected(() => null).onDisconnected(() => null);
|
|
147
|
+
|
|
148
|
+
expectTypeOf(chained).toEqualTypeOf(socket);
|
|
149
|
+
socket.unstable_onConnectedCallbacks = [];
|
|
150
|
+
socket.unstable_onDisconnectCallbacks = [];
|
|
151
|
+
});
|
|
152
|
+
});
|
|
153
|
+
});
|