@hyper-fetch/hono 9.9.0 → 10.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.
@@ -0,0 +1,340 @@
1
+ import { createClient, createSdk } from "@hyper-fetch/core";
2
+ import type { ListenerModel, SSEAdapterOptionsType, SocketInstance } from "@hyper-fetch/sockets";
3
+ import { createSocketSdk, ServerSentEventsAdapter, Socket } from "@hyper-fetch/sockets";
4
+ import { EventSource } from "eventsource";
5
+
6
+ import type { HonoAppToHyperFetch } from "../../../src";
7
+ import type { FeedEvent, Price, RealtimeApp, RealtimeServer } from "../../utils/realtime-server";
8
+ import { createRealtimeServer } from "../../utils/realtime-server";
9
+
10
+ describe("Hono realtime [ Server-Sent Events ]", () => {
11
+ let server: RealtimeServer;
12
+ let sockets: SocketInstance[] = [];
13
+
14
+ const createSocket = (adapterOptions?: SSEAdapterOptionsType, url = `${server.httpUrl}/events`) => {
15
+ // Node has no global EventSource - the one from the `eventsource` package is passed to the adapter.
16
+ // A short reconnect delay: a stream EventSource retries on its own is guarded by `connectionTimeout`.
17
+ const socket = new Socket({
18
+ url,
19
+ adapter: ServerSentEventsAdapter,
20
+ adapterOptions: { EventSource, ...adapterOptions },
21
+ reconnectTime: 10,
22
+ });
23
+ sockets.push(socket);
24
+ return socket;
25
+ };
26
+
27
+ /** Waits for the stream on both ends - the client opened it and the Hono route registered it */
28
+ const waitForStream = (socket: SocketInstance, streams = 1) =>
29
+ vi.waitFor(() => {
30
+ expect(socket.adapter.connected).toBe(true);
31
+ expect(server.state.sseClients.size).toBe(streams);
32
+ });
33
+
34
+ beforeEach(async () => {
35
+ server = createRealtimeServer();
36
+ await server.start();
37
+ });
38
+
39
+ afterEach(async () => {
40
+ await Promise.all(sockets.map((socket) => socket.disconnect()));
41
+ sockets = [];
42
+ await server.stop();
43
+ });
44
+
45
+ describe("when listening by topic", () => {
46
+ it("should deliver the events of the listened topic only", async () => {
47
+ const socket = createSocket();
48
+ const onFeed = vi.fn();
49
+ const onOther = vi.fn();
50
+ socket.createListener<FeedEvent>()({ topic: "feed" }).listen(onFeed);
51
+ socket.createListener<FeedEvent>()({ topic: "other" }).listen(onOther);
52
+ await waitForStream(socket);
53
+
54
+ await server.publish({ topic: "feed", data: { id: 1, text: "first" } });
55
+
56
+ await vi.waitFor(() => {
57
+ expect(onFeed).toHaveBeenCalledTimes(1);
58
+ });
59
+ expect(onFeed.mock.calls[0][0].data).toStrictEqual({ id: 1, text: "first" });
60
+ expect(onFeed.mock.calls[0][0].extra.lastEventId).toBe("1");
61
+ expect(onOther).not.toHaveBeenCalled();
62
+ });
63
+
64
+ it("should match the topic params of the listener", async () => {
65
+ const socket = createSocket();
66
+ const onBtc = vi.fn();
67
+ socket.createListener<Price>()({ topic: "prices/:symbol" }).setParams({ symbol: "BTC" }).listen(onBtc);
68
+ await waitForStream(socket);
69
+
70
+ // Events arrive in order, so the ETH event was already ignored when the BTC one arrives
71
+ await server.publish({ topic: "prices/ETH", data: { symbol: "ETH", price: 10 } });
72
+ await server.publish({ topic: "prices/BTC", data: { symbol: "BTC", price: 100 } });
73
+
74
+ await vi.waitFor(() => {
75
+ expect(onBtc).toHaveBeenCalledTimes(1);
76
+ });
77
+ expect(onBtc.mock.calls[0][0].data).toStrictEqual({ symbol: "BTC", price: 100 });
78
+ });
79
+
80
+ it("should read events that are not { topic, data } with a custom decoder", async () => {
81
+ const socket = createSocket({
82
+ decode: (event) => ({ topic: "ticks", data: JSON.parse(event.data) }),
83
+ });
84
+ const onTick = vi.fn();
85
+ socket.createListener<Price>()({ topic: "ticks" }).listen(onTick);
86
+ await waitForStream(socket);
87
+
88
+ await server.publishRaw(JSON.stringify({ symbol: "BTC", price: 100 }));
89
+
90
+ await vi.waitFor(() => {
91
+ expect(onTick).toHaveBeenCalledTimes(1);
92
+ });
93
+ expect(onTick.mock.calls[0][0].data).toStrictEqual({ symbol: "BTC", price: 100 });
94
+ });
95
+
96
+ it("should report a decoder failure and keep the stream", async () => {
97
+ const socket = createSocket({
98
+ decode: (event) => {
99
+ if (event.data === "not json") {
100
+ throw new Error("Unexpected event");
101
+ }
102
+ return { topic: "ticks", data: JSON.parse(event.data) };
103
+ },
104
+ });
105
+ const onTick = vi.fn();
106
+ const onError = vi.fn();
107
+ socket.onError(onError);
108
+ socket.createListener<Price>()({ topic: "ticks" }).listen(onTick);
109
+ await waitForStream(socket);
110
+
111
+ await server.publishRaw("not json");
112
+ await server.publishRaw(JSON.stringify({ symbol: "BTC", price: 100 }));
113
+
114
+ await vi.waitFor(() => {
115
+ expect(onTick).toHaveBeenCalledTimes(1);
116
+ });
117
+ expect(onError).toHaveBeenCalledTimes(1);
118
+ expect(onError.mock.calls[0][0].error.message).toBe("Unexpected event");
119
+ expect(socket.adapter.connected).toBe(true);
120
+ });
121
+ });
122
+
123
+ describe("when the route writes named events", () => {
124
+ it("should deliver a named event with JSON data to the listeners of the event name", async () => {
125
+ const socket = createSocket();
126
+ const onTick = vi.fn();
127
+ const onStatus = vi.fn();
128
+ socket.createListener<Price>()({ topic: "tick" }).listen(onTick);
129
+ socket.createListener<string>()({ topic: "status" }).listen(onStatus);
130
+ await waitForStream(socket);
131
+
132
+ await server.publishNamed("tick", JSON.stringify({ symbol: "BTC", price: 100 }));
133
+
134
+ await vi.waitFor(() => {
135
+ expect(onTick).toHaveBeenCalledTimes(1);
136
+ });
137
+ expect(onTick.mock.calls[0][0].data).toStrictEqual({ symbol: "BTC", price: 100 });
138
+ expect(onTick.mock.calls[0][0].extra.type).toBe("tick");
139
+ expect(onStatus).not.toHaveBeenCalled();
140
+ });
141
+
142
+ it("should keep data that is not JSON as the raw text", async () => {
143
+ const socket = createSocket();
144
+ const onStatus = vi.fn();
145
+ socket.createListener<string>()({ topic: "status" }).listen(onStatus);
146
+ await waitForStream(socket);
147
+
148
+ await server.publishNamed("status", "online");
149
+
150
+ await vi.waitFor(() => {
151
+ expect(onStatus).toHaveBeenCalledTimes(1);
152
+ });
153
+ expect(onStatus.mock.calls[0][0].data).toBe("online");
154
+ });
155
+
156
+ it("should deliver named and unnamed { topic, data } events side by side", async () => {
157
+ const socket = createSocket();
158
+ const onTick = vi.fn();
159
+ socket.createListener<Price>()({ topic: "tick" }).listen(onTick);
160
+ await waitForStream(socket);
161
+
162
+ await server.publishNamed("tick", JSON.stringify({ symbol: "BTC", price: 1 }));
163
+ await server.publish({ topic: "tick", data: { symbol: "BTC", price: 2 } });
164
+
165
+ await vi.waitFor(() => {
166
+ expect(onTick).toHaveBeenCalledTimes(2);
167
+ });
168
+ expect(onTick.mock.calls.map(([{ data }]) => data.price)).toStrictEqual([1, 2]);
169
+ });
170
+
171
+ it("should start receiving a named event for a listener added after the stream opened", async () => {
172
+ const socket = createSocket();
173
+ await waitForStream(socket);
174
+ const onLate = vi.fn();
175
+
176
+ socket.createListener<string>()({ topic: "late" }).listen(onLate);
177
+ await server.publishNamed("late", "arrived");
178
+
179
+ await vi.waitFor(() => {
180
+ expect(onLate).toHaveBeenCalledTimes(1);
181
+ });
182
+ expect(onLate.mock.calls[0][0].data).toBe("arrived");
183
+ });
184
+
185
+ it("should stop receiving a named event after its last listener is removed", async () => {
186
+ const socket = createSocket();
187
+ const onStatus = vi.fn();
188
+ const onTick = vi.fn();
189
+ const removeStatus = socket.createListener<string>()({ topic: "status" }).listen(onStatus);
190
+ socket.createListener<Price>()({ topic: "tick" }).listen(onTick);
191
+ await waitForStream(socket);
192
+
193
+ removeStatus();
194
+ // Events arrive in order, so the status event was already skipped when the tick arrives
195
+ await server.publishNamed("status", "offline");
196
+ await server.publishNamed("tick", JSON.stringify({ symbol: "BTC", price: 100 }));
197
+
198
+ await vi.waitFor(() => {
199
+ expect(onTick).toHaveBeenCalledTimes(1);
200
+ });
201
+ expect(onStatus).not.toHaveBeenCalled();
202
+ });
203
+
204
+ it("should pass named events to a custom decoder with the event name as the type", async () => {
205
+ const socket = createSocket({
206
+ decode: (event) => ({ topic: event.type, data: { raw: String(event.data) } }),
207
+ });
208
+ const onStatus = vi.fn();
209
+ socket.createListener<{ raw: string }>()({ topic: "status" }).listen(onStatus);
210
+ await waitForStream(socket);
211
+
212
+ await server.publishNamed("status", "online");
213
+
214
+ await vi.waitFor(() => {
215
+ expect(onStatus).toHaveBeenCalledTimes(1);
216
+ });
217
+ expect(onStatus.mock.calls[0][0].data).toStrictEqual({ raw: "online" });
218
+ });
219
+
220
+ it("should resume missed named events after the Hono route ends the stream", async () => {
221
+ const socket = createSocket();
222
+ const onTick = vi.fn();
223
+ socket.createListener<Price>()({ topic: "tick" }).listen(onTick);
224
+ await waitForStream(socket);
225
+ await server.publishNamed("tick", JSON.stringify({ symbol: "BTC", price: 1 }));
226
+ await vi.waitFor(() => {
227
+ expect(onTick).toHaveBeenCalledTimes(1);
228
+ });
229
+
230
+ server.endEventStreams();
231
+ await server.publishNamed("tick", JSON.stringify({ symbol: "BTC", price: 2 }));
232
+
233
+ await vi.waitFor(() => {
234
+ expect(onTick).toHaveBeenCalledTimes(2);
235
+ });
236
+ expect(onTick.mock.calls.map(([{ data }]) => data.price)).toStrictEqual([1, 2]);
237
+ expect(server.state.sseLastEventIds).toStrictEqual([null, "1"]);
238
+ });
239
+
240
+ it("should listen to named events again on the new stream after a reconnect", async () => {
241
+ const socket = createSocket();
242
+ const onTick = vi.fn();
243
+ socket.createListener<Price>()({ topic: "tick" }).listen(onTick);
244
+ await waitForStream(socket);
245
+
246
+ // A new EventSource - the named event handlers of the old one are gone with it
247
+ await socket.reconnect();
248
+ await waitForStream(socket);
249
+ await server.publishNamed("tick", JSON.stringify({ symbol: "BTC", price: 100 }));
250
+
251
+ await vi.waitFor(() => {
252
+ expect(onTick).toHaveBeenCalledTimes(1);
253
+ });
254
+ expect(server.state.sseLastEventIds).toStrictEqual([null, null]);
255
+ });
256
+ });
257
+
258
+ describe("when the stream drops", () => {
259
+ it("should resume after the last event id when the Hono route ends the stream", async () => {
260
+ const socket = createSocket();
261
+ const onFeed = vi.fn();
262
+ socket.createListener<FeedEvent>()({ topic: "feed" }).listen(onFeed);
263
+ await waitForStream(socket);
264
+ await server.publish({ topic: "feed", data: { id: 1, text: "one" } });
265
+ await server.publish({ topic: "feed", data: { id: 2, text: "two" } });
266
+ await vi.waitFor(() => {
267
+ expect(onFeed).toHaveBeenCalledTimes(2);
268
+ });
269
+
270
+ server.endEventStreams();
271
+ // Published while no stream is open - the reconnecting stream gets it as a missed event
272
+ await server.publish({ topic: "feed", data: { id: 3, text: "three" } });
273
+
274
+ await vi.waitFor(() => {
275
+ expect(onFeed).toHaveBeenCalledTimes(3);
276
+ });
277
+ expect(onFeed.mock.calls.map(([{ data }]) => data.id)).toStrictEqual([1, 2, 3]);
278
+ expect(server.state.sseLastEventIds).toStrictEqual([null, "2"]);
279
+ expect(socket.adapter.connected).toBe(true);
280
+ });
281
+
282
+ it("should come back after the Hono server restarts", async () => {
283
+ const socket = createSocket();
284
+ const onFeed = vi.fn();
285
+ const onDisconnected = vi.fn();
286
+ socket.onDisconnected(onDisconnected);
287
+ socket.createListener<FeedEvent>()({ topic: "feed" }).listen(onFeed);
288
+ await waitForStream(socket);
289
+
290
+ await server.stop();
291
+ await vi.waitFor(() => {
292
+ expect(onDisconnected).toHaveBeenCalledTimes(1);
293
+ });
294
+ await server.start();
295
+ await waitForStream(socket);
296
+
297
+ await server.publish({ topic: "feed", data: { id: 1, text: "back online" } });
298
+ await vi.waitFor(() => {
299
+ expect(onFeed).toHaveBeenCalledTimes(1);
300
+ });
301
+ expect(onFeed.mock.calls[0][0].data).toStrictEqual({ id: 1, text: "back online" });
302
+ });
303
+ });
304
+
305
+ describe("when using the SDKs", () => {
306
+ it("should take the stream path from the HTTP schema", async () => {
307
+ const client = createClient({ url: server.httpUrl });
308
+ const sdk = createSdk<typeof client, HonoAppToHyperFetch<RealtimeApp>>(client);
309
+ const socket = createSocket({}, `${client.url}${sdk.events.$get.endpoint}`);
310
+
311
+ await waitForStream(socket);
312
+
313
+ expect(socket.url).toBe(`${server.httpUrl}/events`);
314
+ });
315
+
316
+ it("should listen through a typed socket SDK", async () => {
317
+ type FeedSchema = {
318
+ feed: { $listener: ListenerModel<{ response: FeedEvent; topic: "feed" }> };
319
+ prices: { $symbol: { $listener: ListenerModel<{ response: Price; topic: "prices/:symbol" }> } };
320
+ };
321
+ const socket = createSocket();
322
+ const sdk = createSocketSdk<typeof socket, FeedSchema>(socket);
323
+ const onFeed = vi.fn();
324
+ const onPrice = vi.fn();
325
+ sdk.feed.$listener.listen(onFeed);
326
+ sdk.prices.$symbol.$listener.setParams({ symbol: "BTC" }).listen(onPrice);
327
+ await waitForStream(socket);
328
+
329
+ await server.publish({ topic: "feed", data: { id: 1, text: "typed" } });
330
+ await server.publish({ topic: "prices/BTC", data: { symbol: "BTC", price: 100 } });
331
+
332
+ await vi.waitFor(() => {
333
+ expect(onFeed).toHaveBeenCalledTimes(1);
334
+ expect(onPrice).toHaveBeenCalledTimes(1);
335
+ });
336
+ expect(onFeed.mock.calls[0][0].data).toStrictEqual({ id: 1, text: "typed" });
337
+ expect(onPrice.mock.calls[0][0].data).toStrictEqual({ symbol: "BTC", price: 100 });
338
+ });
339
+ });
340
+ });
@@ -0,0 +1,140 @@
1
+ import { createNodeWebSocket } from "@hono/node-ws";
2
+ import type { EmitterModel, ListenerModel } from "@hyper-fetch/sockets";
3
+ import { createSocketSdk, Socket } from "@hyper-fetch/sockets";
4
+ import { Hono } from "hono";
5
+ import { defineWebSocketHelper } from "hono/ws";
6
+ import { expectTypeOf } from "vitest";
7
+
8
+ import type { HonoAppToHyperFetch, HonoWebSocketPath } from "../../../src";
9
+ import type { ChatMessage, RealtimeApp } from "../../utils/realtime-server";
10
+
11
+ describe("HonoWebSocketPath [ Types ]", () => {
12
+ it("should list the WebSocket routes of the app", () => {
13
+ expectTypeOf<HonoWebSocketPath<RealtimeApp>>().toEqualTypeOf<
14
+ "/ws" | `/chat/${string}` | "/notifications" | "/legacy"
15
+ >();
16
+ expect(true).toBe(true);
17
+ });
18
+
19
+ it("should accept a path with the params filled in", () => {
20
+ const roomId = "42";
21
+ const path: HonoWebSocketPath<RealtimeApp> = `/chat/${roomId}`;
22
+
23
+ expectTypeOf(path).toExtend<HonoWebSocketPath<RealtimeApp>>();
24
+ expect(path).toBe("/chat/42");
25
+ });
26
+
27
+ it("should reject HTTP routes and paths the app does not define", () => {
28
+ // @ts-expect-error - /health is an HTTP route
29
+ const http: HonoWebSocketPath<RealtimeApp> = "/health";
30
+ // @ts-expect-error - /events is a Server-Sent Events route, not a WebSocket
31
+ const sse: HonoWebSocketPath<RealtimeApp> = "/events";
32
+ // @ts-expect-error - the app has no /rooms route
33
+ const typo: HonoWebSocketPath<RealtimeApp> = "/rooms/1";
34
+
35
+ expect([http, sse, typo]).toHaveLength(3);
36
+ });
37
+
38
+ it("should prefix the paths with basePath and app.route", () => {
39
+ const { upgradeWebSocket } = createNodeWebSocket({ app: new Hono() });
40
+ const live = new Hono().get(
41
+ "/rooms/:roomId/:userId",
42
+ upgradeWebSocket(() => ({})),
43
+ );
44
+ const api = new Hono().basePath("/api").route("/live", live);
45
+
46
+ expectTypeOf<HonoWebSocketPath<typeof api>>().toEqualTypeOf<`/api/live/rooms/${string}/${string}`>();
47
+ expect(true).toBe(true);
48
+ });
49
+
50
+ it("should find routes of any runtime helper built on Hono's defineWebSocketHelper", () => {
51
+ // hono/bun, hono/deno and hono/cloudflare-workers export the same UpgradeWebSocket type
52
+ const upgradeWebSocket = defineWebSocketHelper(() => new Response());
53
+ const live = new Hono().get(
54
+ "/live",
55
+ upgradeWebSocket(() => ({})),
56
+ );
57
+
58
+ expectTypeOf<HonoWebSocketPath<typeof live>>().toEqualTypeOf<"/live">();
59
+ expect(true).toBe(true);
60
+ });
61
+
62
+ it("should expand optional params and drop regex patterns like the HTTP schema", () => {
63
+ const upgradeWebSocket = defineWebSocketHelper(() => new Response());
64
+ const live = new Hono()
65
+ .get(
66
+ "/feeds/:feedId?",
67
+ upgradeWebSocket(() => ({})),
68
+ )
69
+ .get(
70
+ "/posts/:id{[0-9]+}/live",
71
+ upgradeWebSocket(() => ({})),
72
+ );
73
+
74
+ expectTypeOf<HonoWebSocketPath<typeof live>>().toEqualTypeOf<
75
+ "/feeds" | `/feeds/${string}` | `/posts/${string}/live`
76
+ >();
77
+ expect(true).toBe(true);
78
+ });
79
+
80
+ it("should leave a WebSocket route out of the HTTP schema but keep the other methods of its path", () => {
81
+ const upgradeWebSocket = defineWebSocketHelper(() => new Response());
82
+ const app = new Hono()
83
+ .get(
84
+ "/chat",
85
+ upgradeWebSocket(() => ({})),
86
+ )
87
+ .post("/chat", (c) => c.json({ sent: true }));
88
+
89
+ type Schema = HonoAppToHyperFetch<typeof app>;
90
+ expectTypeOf<keyof Schema["chat"]>().toEqualTypeOf<"$post">();
91
+ expect(true).toBe(true);
92
+ });
93
+
94
+ it("should resolve to never for an app without WebSocket routes and for anything that is not an app", () => {
95
+ const http = new Hono().get("/users", (c) => c.json([]));
96
+
97
+ expectTypeOf<HonoWebSocketPath<typeof http>>().toBeNever();
98
+ expectTypeOf<HonoWebSocketPath<{ routes: [] }>>().toBeNever();
99
+ expect(true).toBe(true);
100
+ });
101
+ });
102
+
103
+ describe("Hono realtime [ createSocketSdk schema ]", () => {
104
+ type ChatSchema = {
105
+ chat: {
106
+ $roomId: {
107
+ $listener: ListenerModel<{ response: ChatMessage; topic: "chat/:roomId" }>;
108
+ $emitter: EmitterModel<{ payload: { text: string }; topic: "chat/:roomId" }>;
109
+ };
110
+ };
111
+ rooms: {
112
+ join: { $emitter: EmitterModel<{ payload: { roomId: string }; topic: "rooms/join" }> };
113
+ };
114
+ };
115
+
116
+ const socket = new Socket({ url: "ws://localhost/ws", adapterOptions: { autoConnect: false } });
117
+ const sdk = createSocketSdk<typeof socket, ChatSchema>(socket);
118
+
119
+ it("should type the listener response and the topic params", () => {
120
+ const listener = sdk.chat.$roomId.$listener.setParams({ roomId: "1" });
121
+
122
+ listener.listen(({ data }) => {
123
+ expectTypeOf(data).toEqualTypeOf<ChatMessage>();
124
+ });
125
+ // @ts-expect-error - the topic names the param roomId
126
+ sdk.chat.$roomId.$listener.setParams({ id: "1" });
127
+
128
+ expect(listener.topic).toBe("chat/1");
129
+ });
130
+
131
+ it("should type the emitter payload", () => {
132
+ const emitter = sdk.rooms.join.$emitter;
133
+
134
+ expectTypeOf(emitter.emit).parameter(0).toHaveProperty("payload").toEqualTypeOf<{ roomId: string }>();
135
+ // @ts-expect-error - rooms/join takes the room id
136
+ emitter.setPayload({ room: "1" });
137
+
138
+ expect(emitter.topic).toBe("rooms/join");
139
+ });
140
+ });