@hyper-fetch/hono 9.8.1 → 10.0.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.
- package/README.md +70 -3
- package/__tests__/features/inputs/inputs.sdk.spec.ts +113 -0
- package/__tests__/features/inputs/inputs.types.spec.ts +87 -0
- package/__tests__/features/paths/paths.sdk.spec.ts +159 -0
- package/__tests__/features/paths/paths.types.spec.ts +223 -0
- package/__tests__/features/realtime/realtime.react.spec.tsx +226 -0
- package/__tests__/features/realtime/realtime.sse.spec.ts +340 -0
- package/__tests__/features/realtime/realtime.types.spec.ts +140 -0
- package/__tests__/features/realtime/realtime.websocket.spec.ts +414 -0
- package/__tests__/features/responses/responses.sdk.spec.ts +149 -0
- package/__tests__/features/responses/responses.types.spec.ts +107 -0
- package/__tests__/features/schema/schema.types.spec.ts +42 -0
- package/__tests__/utils/inputs.app.ts +57 -0
- package/__tests__/utils/paths.app.ts +31 -0
- package/__tests__/utils/realtime-server.ts +333 -0
- package/__tests__/utils/responses.app.ts +54 -0
- package/__tests__/utils/server.ts +18 -0
- package/dist/hono.types.d.ts +105 -10
- package/dist/hono.types.d.ts.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/package.json +6 -2
- package/src/hono.types.ts +162 -26
- package/src/index.ts +1 -1
- package/vite.config.ts +7 -0
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { createNodeWebSocket } from "@hono/node-ws";
|
|
1
2
|
import { createClient, createSdk } from "@hyper-fetch/core";
|
|
2
3
|
import type {
|
|
3
4
|
Client,
|
|
@@ -16,6 +17,7 @@ import { expectTypeOf } from "vitest";
|
|
|
16
17
|
|
|
17
18
|
import type { HonoAppToHyperFetch } from "../../../src";
|
|
18
19
|
import type { User, apiApp, app } from "../../utils/app";
|
|
20
|
+
import type { RealtimeApp } from "../../utils/realtime-server";
|
|
19
21
|
|
|
20
22
|
type Schema = HonoAppToHyperFetch<typeof app>;
|
|
21
23
|
|
|
@@ -161,3 +163,43 @@ describe("HonoAppToHyperFetch [ createSdk ]", () => {
|
|
|
161
163
|
expect(true).toBe(true);
|
|
162
164
|
});
|
|
163
165
|
});
|
|
166
|
+
|
|
167
|
+
describe("HonoAppToHyperFetch [ Realtime routes ]", () => {
|
|
168
|
+
type RealtimeSchema = HonoAppToHyperFetch<RealtimeApp>;
|
|
169
|
+
|
|
170
|
+
it("should leave WebSocket routes out of the schema", () => {
|
|
171
|
+
// /ws, /chat/:roomId, /notifications and /legacy are upgradeWebSocket() routes
|
|
172
|
+
expectTypeOf<keyof RealtimeSchema>().toEqualTypeOf<"health" | "events">();
|
|
173
|
+
expect(true).toBe(true);
|
|
174
|
+
});
|
|
175
|
+
|
|
176
|
+
it("should keep the HTTP methods of a path that also upgrades GET to a WebSocket", () => {
|
|
177
|
+
const { upgradeWebSocket } = createNodeWebSocket({ app: new Hono() });
|
|
178
|
+
const mixed = new Hono()
|
|
179
|
+
.get(
|
|
180
|
+
"/live",
|
|
181
|
+
upgradeWebSocket(() => ({})),
|
|
182
|
+
)
|
|
183
|
+
.post("/live", (c) => c.json({ posted: true }));
|
|
184
|
+
type MixedSchema = HonoAppToHyperFetch<typeof mixed>;
|
|
185
|
+
|
|
186
|
+
expectTypeOf<keyof MixedSchema>().toEqualTypeOf<"live">();
|
|
187
|
+
expectTypeOf<keyof MixedSchema["live"]>().toEqualTypeOf<"$post">();
|
|
188
|
+
expectTypeOf<ExtractResponseType<MixedSchema["live"]["$post"]>>().toEqualTypeOf<{ posted: true }>();
|
|
189
|
+
expect(true).toBe(true);
|
|
190
|
+
});
|
|
191
|
+
|
|
192
|
+
it("should keep a Server-Sent Events route as a GET with an untyped response", () => {
|
|
193
|
+
expectTypeOf<ExtractEndpointType<RealtimeSchema["events"]["$get"]>>().toEqualTypeOf<"/events">();
|
|
194
|
+
expectTypeOf<ExtractResponseType<RealtimeSchema["events"]["$get"]>>().toEqualTypeOf<{}>();
|
|
195
|
+
expect(true).toBe(true);
|
|
196
|
+
});
|
|
197
|
+
|
|
198
|
+
it("should reject a WebSocket route used as a request", () => {
|
|
199
|
+
// @ts-expect-error - /ws is a WebSocket route
|
|
200
|
+
type WebSocketRoute = RealtimeSchema["ws"];
|
|
201
|
+
|
|
202
|
+
expectTypeOf<WebSocketRoute>().toBeAny();
|
|
203
|
+
expect(true).toBe(true);
|
|
204
|
+
});
|
|
205
|
+
});
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { Hono } from "hono";
|
|
2
|
+
import { getCookie } from "hono/cookie";
|
|
3
|
+
import { validator } from "hono/validator";
|
|
4
|
+
|
|
5
|
+
const parseTitle = (value: unknown): { title: string; draft?: boolean } => {
|
|
6
|
+
if (typeof value === "object" && value !== null && "title" in value && typeof value.title === "string") {
|
|
7
|
+
const draft = "draft" in value && typeof value.draft === "boolean" ? value.draft : undefined;
|
|
8
|
+
return draft === undefined ? { title: value.title } : { title: value.title, draft };
|
|
9
|
+
}
|
|
10
|
+
throw new Error("Invalid post");
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* A Hono app with every validator target: `json`, `query` with arrays, `form`, `header`, `cookie`
|
|
15
|
+
* and `param`, a route that combines several, and a validator that answers with its own error.
|
|
16
|
+
*/
|
|
17
|
+
export const inputsApp = new Hono()
|
|
18
|
+
.post("/posts", validator("json", parseTitle), (c) => c.json(c.req.valid("json"), 201))
|
|
19
|
+
.get(
|
|
20
|
+
"/search",
|
|
21
|
+
validator("query", (value) => value),
|
|
22
|
+
(c) => c.json({ query: c.req.valid("query"), tags: c.req.queries("tags") ?? [] }),
|
|
23
|
+
)
|
|
24
|
+
.post(
|
|
25
|
+
"/upload",
|
|
26
|
+
validator("form", (value) => value),
|
|
27
|
+
(c) => {
|
|
28
|
+
const { title } = c.req.valid("form");
|
|
29
|
+
return c.json({
|
|
30
|
+
title: typeof title === "string" ? title : null,
|
|
31
|
+
contentType: c.req.header("content-type") ?? null,
|
|
32
|
+
});
|
|
33
|
+
},
|
|
34
|
+
)
|
|
35
|
+
.get(
|
|
36
|
+
"/whoami",
|
|
37
|
+
validator("header", (value) => ({ requestId: value["x-request-id"] ?? null })),
|
|
38
|
+
validator("cookie", (value) => ({ session: value.session ?? null })),
|
|
39
|
+
(c) => c.json({ ...c.req.valid("header"), ...c.req.valid("cookie"), raw: getCookie(c, "session") ?? null }),
|
|
40
|
+
)
|
|
41
|
+
.put(
|
|
42
|
+
"/posts/:postId",
|
|
43
|
+
validator("param", (value) => ({ postId: Number(value.postId) })),
|
|
44
|
+
validator("json", parseTitle),
|
|
45
|
+
validator("query", (value) => ({ notify: value.notify === "true" })),
|
|
46
|
+
(c) => c.json({ ...c.req.valid("param"), ...c.req.valid("json"), ...c.req.valid("query") }),
|
|
47
|
+
)
|
|
48
|
+
.post(
|
|
49
|
+
"/strict",
|
|
50
|
+
validator("json", (value, c) => {
|
|
51
|
+
if (typeof value !== "object" || value === null || !("name" in value)) {
|
|
52
|
+
return c.json({ error: "Name is required" as const }, 400);
|
|
53
|
+
}
|
|
54
|
+
return { name: String(value.name) };
|
|
55
|
+
}),
|
|
56
|
+
(c) => c.json({ name: c.req.valid("json").name }, 200),
|
|
57
|
+
);
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { Hono } from "hono";
|
|
2
|
+
import { appendTrailingSlash } from "hono/trailing-slash";
|
|
3
|
+
|
|
4
|
+
const files = new Hono().get("/:fileId?", (c) => c.json({ fileId: c.req.param("fileId") ?? null }));
|
|
5
|
+
|
|
6
|
+
const sharedReads = new Hono().get("/", (c) => c.json({ read: true as const }));
|
|
7
|
+
const sharedWrites = new Hono().post("/", (c) => c.json({ written: true as const }));
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* A Hono app with every kind of path segment: optional and regex params, wildcards, `.all()`,
|
|
11
|
+
* `app.on()` with several methods or paths, paths without a leading slash or with a trailing
|
|
12
|
+
* slash (served through `appendTrailingSlash()`), two routers on one path, and a deeply nested route.
|
|
13
|
+
*/
|
|
14
|
+
export const pathsApp = new Hono()
|
|
15
|
+
.use("/slash", appendTrailingSlash())
|
|
16
|
+
.route("/files", files)
|
|
17
|
+
.get("/versions/:major/:minor?/:patch?", (c) => c.json(c.req.param()))
|
|
18
|
+
.get("/posts/:postId{[0-9]+}", (c) => c.json({ postId: c.req.param("postId") }))
|
|
19
|
+
.get("/archive/:year{[0-9]{4}}/:slug", (c) => c.json(c.req.param()))
|
|
20
|
+
.get("/assets/*", (c) => c.json({ path: c.req.path }))
|
|
21
|
+
.all("/echo", (c) => c.json({ method: c.req.method }))
|
|
22
|
+
.on(["PUT", "PATCH"], "/items/:itemId", (c) => c.json({ method: c.req.method, itemId: c.req.param("itemId") }))
|
|
23
|
+
.on("GET", ["/health", "/status"], (c) => c.json({ up: true as const }))
|
|
24
|
+
.get("plain", (c) => c.json({ plain: true as const }))
|
|
25
|
+
.get("/slash/", (c) => c.json({ slash: true as const }))
|
|
26
|
+
.route("/shared", sharedReads)
|
|
27
|
+
.route("/shared", sharedWrites)
|
|
28
|
+
.get("/l1/l2/l3/l4/l5/l6/l7/l8/l9/l10/l11/:leaf", (c) => c.json({ leaf: c.req.param("leaf") }));
|
|
29
|
+
|
|
30
|
+
/** Optional params on the root path resolve to the top level. */
|
|
31
|
+
export const rootOptionalApp = new Hono().get("/:lang?", (c) => c.json({ lang: c.req.param("lang") ?? null }));
|
|
@@ -0,0 +1,333 @@
|
|
|
1
|
+
import { serve } from "@hono/node-server";
|
|
2
|
+
import type { ServerType } from "@hono/node-server";
|
|
3
|
+
import { createNodeWebSocket } from "@hono/node-ws";
|
|
4
|
+
import { Hono } from "hono";
|
|
5
|
+
import { streamSSE } from "hono/streaming";
|
|
6
|
+
import type { WSContext } from "hono/ws";
|
|
7
|
+
import type { AddressInfo } from "node:net";
|
|
8
|
+
|
|
9
|
+
export type ChatMessage = { roomId: string; text: string };
|
|
10
|
+
export type Notification = { userId: string; title: string };
|
|
11
|
+
export type Price = { symbol: string; price: number };
|
|
12
|
+
export type FeedEvent = { id: number; text: string };
|
|
13
|
+
|
|
14
|
+
/** `{ topic, data }` - the frame the WebsocketAdapter and the ServerSentEventsAdapter read and write by default */
|
|
15
|
+
type Frame = { topic: string; data: unknown };
|
|
16
|
+
|
|
17
|
+
const parseFrame = (raw: unknown): Frame | null => {
|
|
18
|
+
if (typeof raw !== "string") {
|
|
19
|
+
return null;
|
|
20
|
+
}
|
|
21
|
+
try {
|
|
22
|
+
const frame: unknown = JSON.parse(raw);
|
|
23
|
+
if (typeof frame === "object" && frame !== null && "topic" in frame && typeof frame.topic === "string") {
|
|
24
|
+
return { topic: frame.topic, data: "data" in frame ? frame.data : undefined };
|
|
25
|
+
}
|
|
26
|
+
} catch {
|
|
27
|
+
// Not JSON - the frame is ignored below
|
|
28
|
+
}
|
|
29
|
+
return null;
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
const readRoomId = (data: unknown): string | null => {
|
|
33
|
+
if (typeof data === "object" && data !== null && "roomId" in data && typeof data.roomId === "string") {
|
|
34
|
+
return data.roomId;
|
|
35
|
+
}
|
|
36
|
+
return null;
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
const readText = (data: unknown): string => {
|
|
40
|
+
if (typeof data === "object" && data !== null && "text" in data && typeof data.text === "string") {
|
|
41
|
+
return data.text;
|
|
42
|
+
}
|
|
43
|
+
return "";
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
const addTo = <K>(map: Map<K, Set<WSContext>>, key: K, ws: WSContext) => {
|
|
47
|
+
const group = map.get(key) ?? new Set<WSContext>();
|
|
48
|
+
group.add(ws);
|
|
49
|
+
map.set(key, group);
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
const removeFrom = <K>(map: Map<K, Set<WSContext>>, key: K, ws: WSContext) => {
|
|
53
|
+
const group = map.get(key);
|
|
54
|
+
group?.delete(ws);
|
|
55
|
+
if (group?.size === 0) {
|
|
56
|
+
map.delete(key);
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
type SseEvent = { id?: string; event?: string; data: string };
|
|
61
|
+
type SseClient = { send: (event: SseEvent) => Promise<void>; close: () => void };
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* A Hono app with the realtime routes the tests run against, and the server-side state the tests assert on.
|
|
65
|
+
* A factory, so every test starts with a fresh app and fresh state.
|
|
66
|
+
*/
|
|
67
|
+
export const createRealtimeApp = () => {
|
|
68
|
+
const base = new Hono();
|
|
69
|
+
const { upgradeWebSocket, injectWebSocket, wss } = createNodeWebSocket({ app: base });
|
|
70
|
+
|
|
71
|
+
const state = {
|
|
72
|
+
/** Open connections of the multiplexed `/ws` route */
|
|
73
|
+
connections: new Set<WSContext>(),
|
|
74
|
+
/** Room subscriptions of the `/ws` route - joined with a `rooms/join` message */
|
|
75
|
+
rooms: new Map<string, Set<WSContext>>(),
|
|
76
|
+
/** `rooms/join` minus `rooms/leave` messages per room - a join without its leave shows up here */
|
|
77
|
+
joinBalance: new Map<string, number>(),
|
|
78
|
+
/** Connections of the per-room `/chat/:roomId` route */
|
|
79
|
+
roomConnections: new Map<string, Set<WSContext>>(),
|
|
80
|
+
/** Connections of the `/notifications` route, by the `userId` query param */
|
|
81
|
+
notificationConnections: new Map<string, Set<WSContext>>(),
|
|
82
|
+
/** Connections of the `/legacy` route, which speaks `{ type, payload }` instead of `{ topic, data }` */
|
|
83
|
+
legacyConnections: new Set<WSContext>(),
|
|
84
|
+
/** Frames the `/legacy` route received */
|
|
85
|
+
legacyFrames: [] as unknown[],
|
|
86
|
+
/** Open `/events` streams */
|
|
87
|
+
sseClients: new Set<SseClient>(),
|
|
88
|
+
/** `Last-Event-ID` header of every `/events` connection, `null` for a fresh one */
|
|
89
|
+
sseLastEventIds: [] as (string | null)[],
|
|
90
|
+
/** Events published on `/events`, replayed after `Last-Event-ID` when a stream reconnects */
|
|
91
|
+
sseLog: [] as (SseEvent & { id: string })[],
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
const app = base
|
|
95
|
+
.get("/health", (c) => c.json({ ok: true }))
|
|
96
|
+
// Multiplexed route: one connection, many rooms. Rooms are joined and left with messages.
|
|
97
|
+
.get(
|
|
98
|
+
"/ws",
|
|
99
|
+
upgradeWebSocket(() => ({
|
|
100
|
+
onOpen: (_event, ws) => {
|
|
101
|
+
state.connections.add(ws);
|
|
102
|
+
},
|
|
103
|
+
onMessage: (event, ws) => {
|
|
104
|
+
const frame = parseFrame(event.data);
|
|
105
|
+
if (!frame) {
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
const roomId = readRoomId(frame.data);
|
|
109
|
+
if (frame.topic === "rooms/join" && roomId) {
|
|
110
|
+
addTo(state.rooms, roomId, ws);
|
|
111
|
+
state.joinBalance.set(roomId, (state.joinBalance.get(roomId) ?? 0) + 1);
|
|
112
|
+
ws.send(JSON.stringify({ topic: "rooms/joined", data: { roomId } }));
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
if (frame.topic === "rooms/leave" && roomId) {
|
|
116
|
+
removeFrom(state.rooms, roomId, ws);
|
|
117
|
+
state.joinBalance.set(roomId, (state.joinBalance.get(roomId) ?? 0) - 1);
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
if (frame.topic === "echo") {
|
|
121
|
+
ws.send(JSON.stringify({ topic: "echo", data: frame.data }));
|
|
122
|
+
return;
|
|
123
|
+
}
|
|
124
|
+
// `chat/<roomId>` - broadcast to everyone who joined the room
|
|
125
|
+
const [scope, room] = frame.topic.split("/");
|
|
126
|
+
if (scope === "chat" && room) {
|
|
127
|
+
const message: ChatMessage = { roomId: room, text: readText(frame.data) };
|
|
128
|
+
state.rooms.get(room)?.forEach((member) => {
|
|
129
|
+
member.send(JSON.stringify({ topic: frame.topic, data: message }));
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
},
|
|
133
|
+
onClose: (_event, ws) => {
|
|
134
|
+
state.connections.delete(ws);
|
|
135
|
+
state.rooms.forEach((_members, roomId) => removeFrom(state.rooms, roomId, ws));
|
|
136
|
+
},
|
|
137
|
+
})),
|
|
138
|
+
)
|
|
139
|
+
// Per-room route: the connection itself is the subscription
|
|
140
|
+
.get(
|
|
141
|
+
"/chat/:roomId",
|
|
142
|
+
upgradeWebSocket((c) => {
|
|
143
|
+
// The upgrade callback gets an untyped context, so the param is `string | undefined` here
|
|
144
|
+
const roomId = c.req.param("roomId") ?? "";
|
|
145
|
+
return {
|
|
146
|
+
onOpen: (_event, ws) => {
|
|
147
|
+
addTo(state.roomConnections, roomId, ws);
|
|
148
|
+
},
|
|
149
|
+
onMessage: (event) => {
|
|
150
|
+
const frame = parseFrame(event.data);
|
|
151
|
+
if (frame?.topic !== "message") {
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
const message: ChatMessage = { roomId, text: readText(frame.data) };
|
|
155
|
+
state.roomConnections.get(roomId)?.forEach((member) => {
|
|
156
|
+
member.send(JSON.stringify({ topic: "message", data: message }));
|
|
157
|
+
});
|
|
158
|
+
},
|
|
159
|
+
onClose: (_event, ws) => {
|
|
160
|
+
removeFrom(state.roomConnections, roomId, ws);
|
|
161
|
+
},
|
|
162
|
+
};
|
|
163
|
+
}),
|
|
164
|
+
)
|
|
165
|
+
// The subscription input travels in the query params of the handshake
|
|
166
|
+
.get(
|
|
167
|
+
"/notifications",
|
|
168
|
+
upgradeWebSocket((c) => {
|
|
169
|
+
const userId = c.req.query("userId") ?? "";
|
|
170
|
+
return {
|
|
171
|
+
onOpen: (_event, ws) => {
|
|
172
|
+
addTo(state.notificationConnections, userId, ws);
|
|
173
|
+
},
|
|
174
|
+
onClose: (_event, ws) => {
|
|
175
|
+
removeFrom(state.notificationConnections, userId, ws);
|
|
176
|
+
},
|
|
177
|
+
};
|
|
178
|
+
}),
|
|
179
|
+
)
|
|
180
|
+
// An app with its own message shape - `{ type, payload }` - and plain-text pings
|
|
181
|
+
.get(
|
|
182
|
+
"/legacy",
|
|
183
|
+
upgradeWebSocket(() => ({
|
|
184
|
+
onOpen: (_event, ws) => {
|
|
185
|
+
state.legacyConnections.add(ws);
|
|
186
|
+
},
|
|
187
|
+
onMessage: (event, ws) => {
|
|
188
|
+
state.legacyFrames.push(typeof event.data === "string" ? JSON.parse(event.data) : event.data);
|
|
189
|
+
ws.send("ping");
|
|
190
|
+
ws.send(JSON.stringify({ type: "price", payload: { symbol: "BTC", price: 100 } }));
|
|
191
|
+
},
|
|
192
|
+
onClose: (_event, ws) => {
|
|
193
|
+
state.legacyConnections.delete(ws);
|
|
194
|
+
},
|
|
195
|
+
})),
|
|
196
|
+
)
|
|
197
|
+
.get("/events", (c) =>
|
|
198
|
+
streamSSE(c, async (stream) => {
|
|
199
|
+
const lastEventId = c.req.header("last-event-id") ?? null;
|
|
200
|
+
state.sseLastEventIds.push(lastEventId);
|
|
201
|
+
|
|
202
|
+
// Tell EventSource to come back quickly after the stream ends
|
|
203
|
+
await stream.write("retry: 10\n\n");
|
|
204
|
+
const missed = lastEventId ? state.sseLog.filter(({ id }) => Number(id) > Number(lastEventId)) : [];
|
|
205
|
+
// One after another - the order of the events is what the client resumes from
|
|
206
|
+
await missed.reduce((written, event) => written.then(() => stream.writeSSE(event)), Promise.resolve());
|
|
207
|
+
|
|
208
|
+
// The stream stays open until the client goes away or the test ends it
|
|
209
|
+
let client: SseClient | undefined;
|
|
210
|
+
await new Promise<void>((resolve) => {
|
|
211
|
+
client = { send: (event) => stream.writeSSE(event), close: resolve };
|
|
212
|
+
state.sseClients.add(client);
|
|
213
|
+
stream.onAbort(resolve);
|
|
214
|
+
});
|
|
215
|
+
if (client) {
|
|
216
|
+
state.sseClients.delete(client);
|
|
217
|
+
}
|
|
218
|
+
}),
|
|
219
|
+
);
|
|
220
|
+
|
|
221
|
+
/** Pushes `{ topic, data }` to every member of a `/ws` room */
|
|
222
|
+
const broadcast = (roomId: string, text: string) => {
|
|
223
|
+
const message: ChatMessage = { roomId, text };
|
|
224
|
+
state.rooms.get(roomId)?.forEach((ws) => ws.send(JSON.stringify({ topic: `chat/${roomId}`, data: message })));
|
|
225
|
+
};
|
|
226
|
+
|
|
227
|
+
const notify = (notification: Notification) => {
|
|
228
|
+
state.notificationConnections
|
|
229
|
+
.get(notification.userId)
|
|
230
|
+
?.forEach((ws) => ws.send(JSON.stringify({ topic: "notification", data: notification })));
|
|
231
|
+
};
|
|
232
|
+
|
|
233
|
+
/** Writes an event on every open `/events` stream with the next id, so a reconnecting stream can resume after it */
|
|
234
|
+
const writeLogged = async (event: SseEvent) => {
|
|
235
|
+
const logged = { ...event, id: String(state.sseLog.length + 1) };
|
|
236
|
+
state.sseLog.push(logged);
|
|
237
|
+
await Promise.all([...state.sseClients].map((client) => client.send(logged)));
|
|
238
|
+
};
|
|
239
|
+
|
|
240
|
+
/** Publishes an unnamed `{ topic, data }` event on `/events` */
|
|
241
|
+
const publish = (frame: Frame) => writeLogged({ data: JSON.stringify(frame) });
|
|
242
|
+
|
|
243
|
+
/** Publishes a named event - `writeSSE({ event: name, data })` - with `data` written as it is */
|
|
244
|
+
const publishNamed = (name: string, data: string) => writeLogged({ event: name, data });
|
|
245
|
+
|
|
246
|
+
/** Sends `data` as it is - for apps whose events are not `{ topic, data }` */
|
|
247
|
+
const publishRaw = async (data: string) => {
|
|
248
|
+
await Promise.all([...state.sseClients].map((client) => client.send({ data })));
|
|
249
|
+
};
|
|
250
|
+
|
|
251
|
+
/** Ends every open `/events` stream - EventSource reconnects on its own with `Last-Event-ID` */
|
|
252
|
+
const endEventStreams = () => {
|
|
253
|
+
const clients = [...state.sseClients];
|
|
254
|
+
state.sseClients.clear();
|
|
255
|
+
clients.forEach((client) => client.close());
|
|
256
|
+
};
|
|
257
|
+
|
|
258
|
+
/** Closes every open `/ws` connection from the server side - `ws.close()` without a code sends 1005 */
|
|
259
|
+
const closeConnections = (code?: number) => {
|
|
260
|
+
state.connections.forEach((ws) => ws.close(code));
|
|
261
|
+
};
|
|
262
|
+
|
|
263
|
+
return {
|
|
264
|
+
app,
|
|
265
|
+
state,
|
|
266
|
+
wss,
|
|
267
|
+
injectWebSocket,
|
|
268
|
+
broadcast,
|
|
269
|
+
notify,
|
|
270
|
+
publish,
|
|
271
|
+
publishNamed,
|
|
272
|
+
publishRaw,
|
|
273
|
+
endEventStreams,
|
|
274
|
+
closeConnections,
|
|
275
|
+
};
|
|
276
|
+
};
|
|
277
|
+
|
|
278
|
+
/** The type the backend shares with the frontend */
|
|
279
|
+
export type RealtimeApp = ReturnType<typeof createRealtimeApp>["app"];
|
|
280
|
+
|
|
281
|
+
const HOST = "127.0.0.1";
|
|
282
|
+
|
|
283
|
+
/**
|
|
284
|
+
* Runs the realtime app on a real Node server. `stop()` drops every connection like a crashed server would,
|
|
285
|
+
* and `start()` afterwards listens on the same port again - a restart.
|
|
286
|
+
*/
|
|
287
|
+
export const createRealtimeServer = () => {
|
|
288
|
+
const realtime = createRealtimeApp();
|
|
289
|
+
let server: ServerType | undefined;
|
|
290
|
+
let port = 0;
|
|
291
|
+
|
|
292
|
+
const start = () =>
|
|
293
|
+
new Promise<void>((resolve) => {
|
|
294
|
+
// An explicit IPv4 host: with "localhost" the client may resolve ::1 and reach another process that got the
|
|
295
|
+
// same port number on the other address family
|
|
296
|
+
const instance = serve({ fetch: realtime.app.fetch, port, hostname: HOST }, () => {
|
|
297
|
+
port = (instance.address() as AddressInfo).port;
|
|
298
|
+
resolve();
|
|
299
|
+
});
|
|
300
|
+
realtime.injectWebSocket(instance);
|
|
301
|
+
server = instance;
|
|
302
|
+
});
|
|
303
|
+
|
|
304
|
+
const stop = () =>
|
|
305
|
+
new Promise<void>((resolve, reject) => {
|
|
306
|
+
const instance = server;
|
|
307
|
+
server = undefined;
|
|
308
|
+
if (!instance) {
|
|
309
|
+
resolve();
|
|
310
|
+
return;
|
|
311
|
+
}
|
|
312
|
+
realtime.wss.clients.forEach((client) => client.terminate());
|
|
313
|
+
realtime.endEventStreams();
|
|
314
|
+
if ("closeAllConnections" in instance) {
|
|
315
|
+
instance.closeAllConnections();
|
|
316
|
+
}
|
|
317
|
+
instance.close((error) => (error ? reject(error) : resolve()));
|
|
318
|
+
});
|
|
319
|
+
|
|
320
|
+
return {
|
|
321
|
+
...realtime,
|
|
322
|
+
start,
|
|
323
|
+
stop,
|
|
324
|
+
get httpUrl() {
|
|
325
|
+
return `http://${HOST}:${port}`;
|
|
326
|
+
},
|
|
327
|
+
get wsUrl() {
|
|
328
|
+
return `ws://${HOST}:${port}`;
|
|
329
|
+
},
|
|
330
|
+
};
|
|
331
|
+
};
|
|
332
|
+
|
|
333
|
+
export type RealtimeServer = ReturnType<typeof createRealtimeServer>;
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { Hono } from "hono";
|
|
2
|
+
import { validator } from "hono/validator";
|
|
3
|
+
|
|
4
|
+
export interface Result {
|
|
5
|
+
ok: boolean;
|
|
6
|
+
note?: string;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
/** Lets a test pick the branch a handler takes with `?flag=yes`. */
|
|
10
|
+
const flag = validator("query", (value) => ({ flag: value.flag === "yes" }));
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* A Hono app with every kind of handler output: JSON primitives, `null`, `{}`, dates, interfaces,
|
|
14
|
+
* unions, several statuses, a middleware that answers early, `c.text()`, `c.body()`,
|
|
15
|
+
* `c.redirect()`, `c.newResponse()` and `c.notFound()`.
|
|
16
|
+
*/
|
|
17
|
+
export const responsesApp = new Hono()
|
|
18
|
+
.get("/json/string", (c) => c.json("a-string"))
|
|
19
|
+
.get("/json/number", (c) => c.json(37))
|
|
20
|
+
.get("/json/boolean", (c) => c.json(true))
|
|
21
|
+
.get("/json/null", (c) => c.json(null))
|
|
22
|
+
.get("/json/empty", (c) => c.json({}))
|
|
23
|
+
.get("/json/date", (c) => c.json({ at: new Date("2024-01-01T00:00:00.000Z") }))
|
|
24
|
+
.get("/json/interface", (c) => {
|
|
25
|
+
const results: Result[] = [{ ok: true }];
|
|
26
|
+
return c.json(results);
|
|
27
|
+
})
|
|
28
|
+
.get("/json/union", flag, (c) => (c.req.valid("query").flag ? c.json({ data: "foo" }) : c.json({ message: "error" })))
|
|
29
|
+
.get("/statuses", flag, (c) => {
|
|
30
|
+
if (c.req.valid("query").flag) {
|
|
31
|
+
return c.json({ message: "Bad request" }, 400);
|
|
32
|
+
}
|
|
33
|
+
return c.json({ data: "foo" }, 200);
|
|
34
|
+
})
|
|
35
|
+
.post(
|
|
36
|
+
"/guarded",
|
|
37
|
+
async (c, next) => {
|
|
38
|
+
if (!c.req.header("authorization")) {
|
|
39
|
+
return c.json({ error: "Unauthorized" as const }, 401);
|
|
40
|
+
}
|
|
41
|
+
await next();
|
|
42
|
+
},
|
|
43
|
+
(c) => c.json({ created: true as const }, 201),
|
|
44
|
+
)
|
|
45
|
+
.get("/text", (c) => c.text("Hello, Hono!"))
|
|
46
|
+
.get("/text/numeric", (c) => c.text("42"))
|
|
47
|
+
.get("/body", (c) => c.body("raw body"))
|
|
48
|
+
.delete("/body/empty", (c) => c.body(null, 204))
|
|
49
|
+
.get("/body/null", (c) => c.body(null))
|
|
50
|
+
.get("/redirect", flag, (c) =>
|
|
51
|
+
c.req.valid("query").flag ? c.redirect("/text") : c.json({ stayed: true as const }, 200),
|
|
52
|
+
)
|
|
53
|
+
.get("/new-response", (c) => c.newResponse("custom", 202))
|
|
54
|
+
.get("/not-found", (c) => c.notFound());
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { serve } from "@hono/node-server";
|
|
2
|
+
import type { ServerType } from "@hono/node-server";
|
|
3
|
+
import type { AddressInfo } from "node:net";
|
|
4
|
+
|
|
5
|
+
type FetchApp = { fetch: (request: Request) => Response | Promise<Response> };
|
|
6
|
+
|
|
7
|
+
/** Serves a Hono app on a free port and resolves with the server and its base URL. */
|
|
8
|
+
export const startServer = (app: FetchApp) =>
|
|
9
|
+
new Promise<{ server: ServerType; url: string }>((resolve) => {
|
|
10
|
+
const server = serve({ fetch: app.fetch, port: 0 }, () => {
|
|
11
|
+
resolve({ server, url: `http://localhost:${(server.address() as AddressInfo).port}` });
|
|
12
|
+
});
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
export const stopServer = (server: ServerType) =>
|
|
16
|
+
new Promise<void>((resolve, reject) => {
|
|
17
|
+
server.close((error) => (error ? reject(error) : resolve()));
|
|
18
|
+
});
|