@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 CHANGED
@@ -31,8 +31,9 @@
31
31
  ## ๐Ÿ“– About
32
32
 
33
33
  `@hyper-fetch/hono` turns the type of a Hono app into a HyperFetch SDK schema. Your frontend calls the backend through
34
- `createSdk` with response, payload, query and param types read straight from your Hono routes and validators. It ships
35
- types only, so nothing from your server ends up in the client bundle.
34
+ `createSdk` with response, payload, query and param types read straight from your Hono routes and validators, and its
35
+ sockets connect to `upgradeWebSocket()` and `streamSSE()` routes at type-checked paths. It ships types only, so nothing
36
+ from your server ends up in the client bundle.
36
37
 
37
38
  ## ๐ŸŽฏ Key Capabilities
38
39
 
@@ -40,7 +41,10 @@ types only, so nothing from your server ends up in the client bundle.
40
41
  - ๐Ÿงญ **Paths become properties** - `/users/:userId/posts` is `sdk.users.$userId.posts.$get`, with typed `setParams()`
41
42
  - ๐Ÿ›‚ **Validators drive the payload** - `json` and `query` validators type `setPayload()` and `setQueryParams()`
42
43
  - ๐Ÿงฉ **Mounted routers included** - `app.route()` and `basePath()` prefixes land in the endpoint and the nesting
43
- - ๐Ÿชถ **Zero runtime** - A single type export, so it adds no code to your bundle
44
+ - ๐Ÿงท **Every path shape** - Optional `:id?` and regex `:id{[0-9]+}` params, `.all()` and `app.on()` get typed accessors
45
+ - ๐Ÿ“ก **Realtime routes too** - `HonoWebSocketPath` rejects socket URLs that match no `upgradeWebSocket()` route
46
+ - ๐Ÿšซ **No fake requests** - WebSocket routes stay out of the HTTP SDK, so nobody calls `send()` on them
47
+ - ๐Ÿชถ **Zero runtime** - Type exports only, so it adds no code to your bundle
44
48
  - โšก **Every HyperFetch feature** - Cache, retries, deduplication, offline and React hooks work on every route
45
49
 
46
50
  ## ๐Ÿš€ Quick Start
@@ -73,6 +77,7 @@ const { data } = await sdk.users.$userId.$get.setParams({ userId: "1" }).send();
73
77
  ## ๐Ÿ“š Documentation
74
78
 
75
79
  - [Hono Integration Docs](https://hyperfetch.bettertyped.com/docs/integrations/hono/overview)
80
+ - [Hono Realtime](https://hyperfetch.bettertyped.com/docs/integrations/hono/realtime)
76
81
  - [SDK Guide](https://hyperfetch.bettertyped.com/docs/core/sdk)
77
82
  - [Getting Started](https://hyperfetch.bettertyped.com/docs/getting-started/quick-start)
78
83
 
@@ -123,6 +128,68 @@ export const UserName = ({ userId }: { userId: string }) => {
123
128
  };
124
129
  ```
125
130
 
131
+ ### WebSocket routes with a typed socket SDK
132
+
133
+ ```ts
134
+ // backend
135
+ import { createNodeWebSocket } from "@hono/node-ws";
136
+ import type { ListenerModel } from "@hyper-fetch/sockets";
137
+
138
+ const base = new Hono();
139
+ const { upgradeWebSocket } = createNodeWebSocket({ app: base }); // plus injectWebSocket(server) on Node
140
+
141
+ const app = base.get(
142
+ "/chat/:roomId",
143
+ upgradeWebSocket((c) => ({
144
+ onOpen: (_event, ws) => ws.send(JSON.stringify({ topic: "message", data: { text: "Welcome" } })),
145
+ })),
146
+ );
147
+
148
+ export type AppType = typeof app;
149
+ export type ChatSchema = { message: { $listener: ListenerModel<{ response: { text: string }; topic: "message" }> } };
150
+ ```
151
+
152
+ ```ts
153
+ // frontend
154
+ import { createSocketSdk, Socket } from "@hyper-fetch/sockets";
155
+ import type { HonoWebSocketPath } from "@hyper-fetch/hono";
156
+
157
+ const path: HonoWebSocketPath<AppType> = `/chat/${roomId}`; // "/rooms/1" would not compile
158
+ const socket = new Socket({ url: `wss://api.example.com${path}` });
159
+ const chat = createSocketSdk<typeof socket, ChatSchema>(socket);
160
+
161
+ chat.message.$listener.listen(({ data }) => console.log(data.text));
162
+ ```
163
+
164
+ ### Server-Sent Events with named events
165
+
166
+ ```ts
167
+ // backend: named events reach the listeners of the event name, JSON data is parsed
168
+ app.get("/events", (c) =>
169
+ streamSSE(c, async (stream) => {
170
+ await stream.writeSSE({ id: "1", event: "tick", data: JSON.stringify({ symbol: "BTC", price: 100 }) });
171
+ }),
172
+ );
173
+ ```
174
+
175
+ ```ts
176
+ // frontend: Node has no global EventSource, so pass the `eventsource` package there
177
+ import { EventSource } from "eventsource";
178
+ import { ServerSentEventsAdapter, Socket } from "@hyper-fetch/sockets";
179
+
180
+ const events = new Socket({
181
+ url: "http://localhost:3000/events",
182
+ adapter: ServerSentEventsAdapter,
183
+ adapterOptions: { EventSource },
184
+ });
185
+
186
+ events
187
+ .createListener<{ symbol: string; price: number }>()({ topic: "tick" })
188
+ .listen(({ data }) => {
189
+ console.log(data.price);
190
+ });
191
+ ```
192
+
126
193
  ## License
127
194
 
128
195
  [Apache-2.0](https://github.com/BetterTyped/hyper-fetch/blob/main/License.md)
@@ -0,0 +1,113 @@
1
+ import type { ServerType } from "@hono/node-server";
2
+ import { createClient, createSdk } from "@hyper-fetch/core";
3
+
4
+ import type { HonoAppToHyperFetch } from "../../../src";
5
+ import { inputsApp } from "../../utils/inputs.app";
6
+ import { startServer, stopServer } from "../../utils/server";
7
+
8
+ type Schema = HonoAppToHyperFetch<typeof inputsApp>;
9
+
10
+ describe("HonoAppToHyperFetch [ Validator inputs against a Hono server ]", () => {
11
+ let server: ServerType;
12
+ let url: string;
13
+
14
+ const createAppSdk = () => {
15
+ const client = createClient({ url });
16
+ return { client, sdk: createSdk<typeof client, Schema>(client) };
17
+ };
18
+
19
+ beforeAll(async () => {
20
+ ({ server, url } = await startServer(inputsApp));
21
+ });
22
+
23
+ afterAll(async () => {
24
+ await stopServer(server);
25
+ });
26
+
27
+ it("should send the payload as the JSON body the json validator reads", async () => {
28
+ const { sdk } = createAppSdk();
29
+
30
+ const { data, status } = await sdk.posts.$post.setPayload({ title: "Hello", draft: true }).send();
31
+
32
+ expect(status).toBe(201);
33
+ expect(data).toStrictEqual({ title: "Hello", draft: true });
34
+ });
35
+
36
+ it("should send array query params in the bracket format by default", async () => {
37
+ const { sdk } = createAppSdk();
38
+
39
+ const { data } = await sdk.search.$get.setQueryParams({ q: "hono", tags: ["a", "b"] }).send();
40
+
41
+ expect(data).toStrictEqual({ query: { q: "hono", "tags[]": ["a", "b"] }, tags: [] });
42
+ });
43
+
44
+ it("should send array query params as repeated keys with the none array format", async () => {
45
+ const { client, sdk } = createAppSdk();
46
+ client.adapter.setQueryParamsMapperConfig({ arrayFormat: "none" });
47
+
48
+ const { data } = await sdk.search.$get.setQueryParams({ q: "hono", tags: ["a", "b"] }).send();
49
+
50
+ expect(data).toStrictEqual({ query: { q: "hono", tags: ["a", "b"] }, tags: ["a", "b"] });
51
+ });
52
+
53
+ it("should send array query params as one comma separated value with the comma array format", async () => {
54
+ const { client, sdk } = createAppSdk();
55
+ client.adapter.setQueryParamsMapperConfig({ arrayFormat: "comma" });
56
+
57
+ const { data } = await sdk.search.$get.setQueryParams({ tags: ["a", "b"] }).send();
58
+
59
+ expect(data).toStrictEqual({ query: { tags: "a,b" }, tags: ["a,b"] });
60
+ });
61
+
62
+ it("should send no body to a form route, so the form validator reads an empty form", async () => {
63
+ const { sdk } = createAppSdk();
64
+
65
+ const { data, status } = await sdk.upload.$post.send();
66
+
67
+ expect(status).toBe(200);
68
+ expect(data).toStrictEqual({ title: null, contentType: null });
69
+ });
70
+
71
+ it("should reach a form route with a FormData payload", async () => {
72
+ const { client } = createAppSdk();
73
+ const request = client.createRequest<{ payload: FormData }>()({ endpoint: "/upload", method: "POST" });
74
+ const form = new FormData();
75
+ form.append("title", "Hello");
76
+
77
+ const { data } = await request.setPayload(form).send();
78
+
79
+ expect(data).toMatchObject({ title: "Hello", contentType: expect.stringContaining("multipart/form-data") });
80
+ });
81
+
82
+ it("should pass header and cookie validators with headers set on the request", async () => {
83
+ const { sdk } = createAppSdk();
84
+
85
+ const { data } = await sdk.whoami.$get.setHeaders({ "x-request-id": "req-1", cookie: "session=abc" }).send();
86
+
87
+ expect(data).toStrictEqual({ requestId: "req-1", session: "abc", raw: "abc" });
88
+ });
89
+
90
+ it("should combine params, payload and query params on one route", async () => {
91
+ const { sdk } = createAppSdk();
92
+
93
+ const { data } = await sdk.posts.$postId.$put
94
+ .setParams({ postId: "7" })
95
+ .setPayload({ title: "Edited" })
96
+ .setQueryParams({ notify: "true" })
97
+ .send();
98
+
99
+ expect(data).toStrictEqual({ postId: 7, title: "Edited", notify: true });
100
+ });
101
+
102
+ it("should resolve the response a validator returns as the error", async () => {
103
+ const { client } = createAppSdk();
104
+ const request = client.createRequest<{ payload: { title: string } }>()({ endpoint: "/strict", method: "POST" });
105
+
106
+ const { data, error, status, success } = await request.setPayload({ title: "No name" }).send();
107
+
108
+ expect(success).toBe(false);
109
+ expect(status).toBe(400);
110
+ expect(data).toBeNull();
111
+ expect(error).toStrictEqual({ error: "Name is required" });
112
+ });
113
+ });
@@ -0,0 +1,87 @@
1
+ import { createClient, createSdk } from "@hyper-fetch/core";
2
+ import type { ExtractPayloadType, ExtractQueryParamsType, ExtractResponseType } from "@hyper-fetch/core";
3
+ import { expectTypeOf } from "vitest";
4
+
5
+ import type { HonoAppToHyperFetch } from "../../../src";
6
+ import type { inputsApp } from "../../utils/inputs.app";
7
+
8
+ type Schema = HonoAppToHyperFetch<typeof inputsApp>;
9
+
10
+ describe("HonoAppToHyperFetch [ Validator inputs ]", () => {
11
+ it("should take the payload from the json validator, optional fields included", () => {
12
+ expectTypeOf<ExtractPayloadType<Schema["posts"]["$post"]>>().toEqualTypeOf<{ title: string; draft?: boolean }>();
13
+ expect(true).toBe(true);
14
+ });
15
+
16
+ it("should take the query params from an untyped query validator", () => {
17
+ expectTypeOf<ExtractQueryParamsType<Schema["search"]["$get"]>>().toEqualTypeOf<{
18
+ [key: string]: string | string[];
19
+ }>();
20
+ expect(true).toBe(true);
21
+ });
22
+
23
+ it("should leave the payload undefined for a form validator", () => {
24
+ expectTypeOf<ExtractPayloadType<Schema["upload"]["$post"]>>().toEqualTypeOf<undefined>();
25
+ expect(true).toBe(true);
26
+ });
27
+
28
+ it("should leave header and cookie validators out of the request", () => {
29
+ expectTypeOf<ExtractPayloadType<Schema["whoami"]["$get"]>>().toEqualTypeOf<undefined>();
30
+ expectTypeOf<ExtractQueryParamsType<Schema["whoami"]["$get"]>>().toEqualTypeOf<undefined>();
31
+ expect(true).toBe(true);
32
+ });
33
+
34
+ it("should combine param, json and query validators on one route", () => {
35
+ type Update = Schema["posts"]["$postId"]["$put"];
36
+
37
+ expectTypeOf<ExtractPayloadType<Update>>().toEqualTypeOf<{ title: string; draft?: boolean }>();
38
+ expectTypeOf<ExtractQueryParamsType<Update>>().toEqualTypeOf<{ notify: string | string[] }>();
39
+ expectTypeOf<ExtractResponseType<Update>>().toEqualTypeOf<{
40
+ title: string;
41
+ draft?: boolean;
42
+ postId: number;
43
+ notify: boolean;
44
+ }>();
45
+ expect(true).toBe(true);
46
+ });
47
+
48
+ it("should add the response a validator returns to the route response", () => {
49
+ expectTypeOf<ExtractResponseType<Schema["strict"]["$post"]>>().toEqualTypeOf<
50
+ { name: string } | { error: "Name is required" }
51
+ >();
52
+ expect(true).toBe(true);
53
+ });
54
+ });
55
+
56
+ describe("HonoAppToHyperFetch [ Validator inputs on createSdk ]", () => {
57
+ const client = createClient({ url: "http://localhost" });
58
+ const sdk = createSdk<typeof client, Schema>(client);
59
+
60
+ it("should accept a payload without its optional fields", () => {
61
+ sdk.posts.$post.setPayload({ title: "Hello" });
62
+ sdk.posts.$post.setPayload({ title: "Hello", draft: true });
63
+ // @ts-expect-error - draft is a boolean
64
+ sdk.posts.$post.setPayload({ title: "Hello", draft: "yes" });
65
+ expect(true).toBe(true);
66
+ });
67
+
68
+ it("should accept arrays in the query params", () => {
69
+ sdk.search.$get.setQueryParams({ q: "hono", tags: ["a", "b"] });
70
+ // @ts-expect-error - query values are strings or string arrays
71
+ sdk.search.$get.setQueryParams({ page: 1 });
72
+ expect(true).toBe(true);
73
+ });
74
+
75
+ it("should take the params of a param validator from the Hono path", () => {
76
+ sdk.posts.$postId.$put.setParams({ postId: "1" });
77
+ // @ts-expect-error - the Hono path names the param postId
78
+ sdk.posts.$postId.$put.setParams({ id: "1" });
79
+ expect(true).toBe(true);
80
+ });
81
+
82
+ it("should reject a payload on a form route", () => {
83
+ // @ts-expect-error - the payload of a form route is undefined
84
+ sdk.upload.$post.setPayload(new FormData());
85
+ expect(true).toBe(true);
86
+ });
87
+ });
@@ -0,0 +1,159 @@
1
+ import type { ServerType } from "@hono/node-server";
2
+ import { createClient, createSdk } from "@hyper-fetch/core";
3
+
4
+ import type { HonoAppToHyperFetch } from "../../../src";
5
+ import { pathsApp } from "../../utils/paths.app";
6
+ import { startServer, stopServer } from "../../utils/server";
7
+
8
+ type Schema = HonoAppToHyperFetch<typeof pathsApp>;
9
+
10
+ describe("HonoAppToHyperFetch [ Paths against a Hono server ]", () => {
11
+ let server: ServerType;
12
+ let url: string;
13
+
14
+ const createAppSdk = () => {
15
+ const client = createClient({ url });
16
+ return createSdk<typeof client, Schema>(client);
17
+ };
18
+
19
+ beforeAll(async () => {
20
+ ({ server, url } = await startServer(pathsApp));
21
+ });
22
+
23
+ afterAll(async () => {
24
+ await stopServer(server);
25
+ });
26
+
27
+ it("should call a route with an optional param both without and with the param", async () => {
28
+ const sdk = createAppSdk();
29
+
30
+ const without = await sdk.files.$get.send();
31
+ const withParam = await sdk.files.$fileId.$get.setParams({ fileId: "report" }).send();
32
+
33
+ expect(sdk.files.$get.endpoint).toBe("/files");
34
+ expect(sdk.files.$fileId.$get.endpoint).toBe("/files/:fileId");
35
+ expect(without.data).toStrictEqual({ fileId: null });
36
+ expect(withParam.data).toStrictEqual({ fileId: "report" });
37
+ });
38
+
39
+ it("should call every prefix of a route with several optional params", async () => {
40
+ const sdk = createAppSdk();
41
+
42
+ const major = await sdk.versions.$major.$get.setParams({ major: "1" }).send();
43
+ const minor = await sdk.versions.$major.$minor.$get.setParams({ major: "1", minor: "2" }).send();
44
+ const patch = await sdk.versions.$major.$minor.$patch.$get.setParams({ major: "1", minor: "2", patch: "3" }).send();
45
+
46
+ expect(major.data).toStrictEqual({ major: "1" });
47
+ expect(minor.data).toStrictEqual({ major: "1", minor: "2" });
48
+ expect(patch.data).toStrictEqual({ major: "1", minor: "2", patch: "3" });
49
+ });
50
+
51
+ it("should fill a regex param by its name", async () => {
52
+ const sdk = createAppSdk();
53
+ const request = sdk.posts.$postId.$get;
54
+
55
+ const { data } = await request.setParams({ postId: "42" }).send();
56
+
57
+ expect(request.endpoint).toBe("/posts/:postId");
58
+ expect(data).toStrictEqual({ postId: "42" });
59
+ });
60
+
61
+ it("should fill a regex param whose pattern holds braces", async () => {
62
+ const sdk = createAppSdk();
63
+
64
+ const { data } = await sdk.archive.$year.$slug.$get.setParams({ year: "2024", slug: "launch" }).send();
65
+
66
+ expect(data).toStrictEqual({ year: "2024", slug: "launch" });
67
+ });
68
+
69
+ it("should not match a regex param with a value the pattern rejects", async () => {
70
+ const sdk = createAppSdk();
71
+
72
+ const { status, success } = await sdk.posts.$postId.$get.setParams({ postId: "latest" }).send();
73
+
74
+ expect(success).toBe(false);
75
+ expect(status).toBe(404);
76
+ });
77
+
78
+ it("should send every standard method to an .all() route", async () => {
79
+ const sdk = createAppSdk();
80
+
81
+ const get = await sdk.echo.$get.send();
82
+ const post = await sdk.echo.$post.send();
83
+ const del = await sdk.echo.$delete.send();
84
+
85
+ expect(get.data).toStrictEqual({ method: "GET" });
86
+ expect(post.data).toStrictEqual({ method: "POST" });
87
+ expect(del.data).toStrictEqual({ method: "DELETE" });
88
+ });
89
+
90
+ it("should send each method of an app.on() route with several methods", async () => {
91
+ const sdk = createAppSdk();
92
+
93
+ const put = await sdk.items.$itemId.$put.setParams({ itemId: "1" }).send();
94
+ const patch = await sdk.items.$itemId.$patch.setParams({ itemId: "1" }).send();
95
+
96
+ expect(put.data).toStrictEqual({ method: "PUT", itemId: "1" });
97
+ expect(patch.data).toStrictEqual({ method: "PATCH", itemId: "1" });
98
+ });
99
+
100
+ it("should send to each path of an app.on() route with several paths", async () => {
101
+ const sdk = createAppSdk();
102
+
103
+ const health = await sdk.health.$get.send();
104
+ const status = await sdk.status.$get.send();
105
+
106
+ expect(health.data).toStrictEqual({ up: true });
107
+ expect(status.data).toStrictEqual({ up: true });
108
+ });
109
+
110
+ it("should send to a path registered without a leading slash", async () => {
111
+ const sdk = createAppSdk();
112
+ const request = sdk.plain.$get;
113
+
114
+ const { data } = await request.send();
115
+
116
+ expect(request.endpoint).toBe("/plain");
117
+ expect(data).toStrictEqual({ plain: true });
118
+ });
119
+
120
+ it("should send to a path registered with a trailing slash without the slash", async () => {
121
+ const sdk = createAppSdk();
122
+ const request = sdk.slash.$get;
123
+
124
+ const { data } = await request.send();
125
+
126
+ expect(request.endpoint).toBe("/slash");
127
+ expect(data).toStrictEqual({ slash: true });
128
+ });
129
+
130
+ it("should send to a wildcard route through its literal path", async () => {
131
+ const sdk = createAppSdk();
132
+ const request = sdk.assets["*"].$get;
133
+
134
+ const { data } = await request.send();
135
+
136
+ expect(request.endpoint).toBe("/assets/*");
137
+ expect(data).toStrictEqual({ path: "/assets/*" });
138
+ });
139
+
140
+ it("should send each method of two routers mounted on one path", async () => {
141
+ const sdk = createAppSdk();
142
+
143
+ const read = await sdk.shared.$get.send();
144
+ const written = await sdk.shared.$post.send();
145
+
146
+ expect(read.data).toStrictEqual({ read: true });
147
+ expect(written.data).toStrictEqual({ written: true });
148
+ });
149
+
150
+ it("should send to a route nested deeper than createSdk injects its client", async () => {
151
+ const sdk = createAppSdk();
152
+ const request = sdk.l1.l2.l3.l4.l5.l6.l7.l8.l9.l10.l11.$leaf.$get;
153
+
154
+ const { data } = await request.setParams({ leaf: "end" }).send();
155
+
156
+ expect(request.endpoint).toBe("/l1/l2/l3/l4/l5/l6/l7/l8/l9/l10/l11/:leaf");
157
+ expect(data).toStrictEqual({ leaf: "end" });
158
+ });
159
+ });