@hyper-fetch/orpc 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.
- package/README.md +117 -31
- package/__tests__/e2e/e2e.orpc-realtime-server.ts +181 -0
- package/__tests__/e2e/e2e.react-realtime.spec.tsx +181 -0
- package/__tests__/e2e/e2e.realtime.spec.ts +310 -0
- package/__tests__/features/adapter/adapter.lifecycle.spec.ts +23 -0
- package/__tests__/features/adapter/adapter.schema.spec.ts +19 -0
- package/__tests__/features/socket/socket.schema.spec.ts +179 -0
- package/__tests__/features/stream-adapter/stream-adapter.environment.spec.ts +163 -0
- package/__tests__/features/stream-adapter/stream-adapter.lifecycle.spec.ts +558 -0
- package/__tests__/features/stream-adapter/stream-adapter.listener-lifecycle.spec.ts +291 -0
- package/__tests__/features/stream-adapter/stream-adapter.protocol.spec.ts +609 -0
- package/__tests__/features/stream-adapter/stream-adapter.subscriptions.spec.ts +270 -0
- package/__tests__/features/websocket-adapter/websocket-adapter.environment.spec.ts +153 -0
- package/__tests__/features/websocket-adapter/websocket-adapter.handshake-error.spec.ts +80 -0
- package/__tests__/features/websocket-adapter/websocket-adapter.lifecycle.spec.ts +448 -0
- package/__tests__/features/websocket-adapter/websocket-adapter.listener-lifecycle.spec.ts +222 -0
- package/__tests__/features/websocket-adapter/websocket-adapter.protocol.spec.ts +415 -0
- package/__tests__/features/websocket-adapter/websocket-adapter.subscriptions.spec.ts +172 -0
- package/__tests__/utils/controlled-fetch.ts +160 -0
- package/__tests__/utils/controlled-websocket.ts +140 -0
- package/__tests__/utils/socket-error.ts +7 -0
- package/__tests__/utils/stream-socket.ts +54 -0
- package/__tests__/utils/websocket-socket.ts +45 -0
- package/__tests__/vitest.setup.ts +20 -0
- package/dist/adapter/adapter.fetch.d.ts.map +1 -1
- package/dist/adapter/adapter.schema.d.ts +32 -0
- package/dist/adapter/adapter.schema.d.ts.map +1 -1
- package/dist/adapter/adapter.utils.d.ts +22 -4
- package/dist/adapter/adapter.utils.d.ts.map +1 -1
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.mjs +843 -13
- package/dist/index.mjs.map +1 -1
- package/dist/socket/index.d.ts +3 -0
- package/dist/socket/index.d.ts.map +1 -0
- package/dist/socket/socket.subscriptions.d.ts +31 -0
- package/dist/socket/socket.subscriptions.d.ts.map +1 -0
- package/dist/socket/socket.types.d.ts +62 -0
- package/dist/socket/socket.types.d.ts.map +1 -0
- package/dist/socket/socket.utils.d.ts +56 -0
- package/dist/socket/socket.utils.d.ts.map +1 -0
- package/dist/stream-adapter/index.d.ts +3 -0
- package/dist/stream-adapter/index.d.ts.map +1 -0
- package/dist/stream-adapter/stream-adapter.d.ts +21 -0
- package/dist/stream-adapter/stream-adapter.d.ts.map +1 -0
- package/dist/stream-adapter/stream-adapter.types.d.ts +22 -0
- package/dist/stream-adapter/stream-adapter.types.d.ts.map +1 -0
- package/dist/stream-adapter/stream-adapter.utils.d.ts +22 -0
- package/dist/stream-adapter/stream-adapter.utils.d.ts.map +1 -0
- package/dist/websocket-adapter/index.d.ts +3 -0
- package/dist/websocket-adapter/index.d.ts.map +1 -0
- package/dist/websocket-adapter/websocket-adapter.d.ts +21 -0
- package/dist/websocket-adapter/websocket-adapter.d.ts.map +1 -0
- package/dist/websocket-adapter/websocket-adapter.types.d.ts +22 -0
- package/dist/websocket-adapter/websocket-adapter.types.d.ts.map +1 -0
- package/dist/websocket-adapter/websocket-adapter.utils.d.ts +35 -0
- package/dist/websocket-adapter/websocket-adapter.utils.d.ts.map +1 -0
- package/package.json +3 -1
- package/src/adapter/adapter.fetch.ts +4 -3
- package/src/adapter/adapter.schema.ts +57 -0
- package/src/adapter/adapter.utils.ts +40 -10
- package/src/index.ts +3 -0
- package/src/socket/index.ts +2 -0
- package/src/socket/socket.subscriptions.ts +178 -0
- package/src/socket/socket.types.ts +64 -0
- package/src/socket/socket.utils.ts +110 -0
- package/src/stream-adapter/index.ts +2 -0
- package/src/stream-adapter/stream-adapter.ts +301 -0
- package/src/stream-adapter/stream-adapter.types.ts +31 -0
- package/src/stream-adapter/stream-adapter.utils.ts +98 -0
- package/src/websocket-adapter/index.ts +2 -0
- package/src/websocket-adapter/websocket-adapter.ts +315 -0
- package/src/websocket-adapter/websocket-adapter.types.ts +31 -0
- package/src/websocket-adapter/websocket-adapter.utils.ts +119 -0
package/README.md
CHANGED
|
@@ -1,41 +1,41 @@
|
|
|
1
|
-
|
|
1
|
+
<p align="center">
|
|
2
|
+
<a href="https://hyperfetch.bettertyped.com/docs/integrations/adapter-orpc/overview"><img src="https://raw.githubusercontent.com/BetterTyped/hyper-fetch/main/.github/assets/packages/orpc.png" alt="Hyper Fetch oRPC. oRPC procedures. Typed down to errors. Inputs, outputs and defined errors inferred from your router, with event iterators as live listeners." /></a>
|
|
3
|
+
</p>
|
|
2
4
|
|
|
3
5
|
<p align="center">
|
|
4
|
-
<b>
|
|
6
|
+
<a href="https://hyperfetch.bettertyped.com/docs/integrations/adapter-orpc/overview"><b>Quick Start</b></a> ·
|
|
7
|
+
<a href="https://hyperfetch.bettertyped.com/docs/integrations/adapter-orpc/overview">Documentation</a> ·
|
|
8
|
+
<a href="https://hyperfetch.bettertyped.com/docs/api/adapter-orpc/Functions/OrpcAdapter">API Reference</a> ·
|
|
9
|
+
<a href="https://github.com/BetterTyped/hyper-fetch">GitHub</a> ·
|
|
10
|
+
<a href="https://discord.gg/7upC2kVmyM">Discord</a>
|
|
5
11
|
</p>
|
|
6
12
|
|
|
7
13
|
<p align="center">
|
|
8
|
-
<a href="https://github.com/BetterTyped/hyper-fetch">
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
<a href="https://
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
<a href="https://
|
|
15
|
-
<img src="https://img.shields.io/npm/dm/@hyper-fetch/orpc.svg?logo=npm&color=2a9d8f" />
|
|
16
|
-
</a>
|
|
17
|
-
<a href="https://bundlephobia.com/package/@hyper-fetch/orpc">
|
|
18
|
-
<img src="https://img.shields.io/bundlephobia/minzip/@hyper-fetch/orpc?color=8338ec" />
|
|
19
|
-
</a>
|
|
20
|
-
<a href="https://github.com/BetterTyped/hyper-fetch/blob/main/License.md">
|
|
21
|
-
<img src="https://img.shields.io/github/license/BetterTyped/hyper-fetch?color=yellow" />
|
|
22
|
-
</a>
|
|
23
|
-
<img src="https://img.shields.io/badge/TypeScript-ready-3178c6?logo=typescript&logoColor=white" />
|
|
24
|
-
<img src="https://img.shields.io/badge/oRPC-v1-000000" />
|
|
14
|
+
<a href="https://github.com/BetterTyped/hyper-fetch"><img src="https://img.shields.io/github/stars/BetterTyped/hyper-fetch?style=flat&logo=github&color=333" alt="GitHub stars" /></a>
|
|
15
|
+
<a href="https://www.npmjs.com/package/@hyper-fetch/orpc"><img src="https://img.shields.io/npm/v/@hyper-fetch/orpc?logo=npm&color=e76f51" alt="npm version" /></a>
|
|
16
|
+
<a href="https://www.npmjs.com/package/@hyper-fetch/orpc"><img src="https://api.maciejpyrc.com/portfolio/npm/downloads.svg?packages=@hyper-fetch/orpc&color=fbc646" alt="Monthly downloads" /></a>
|
|
17
|
+
<a href="https://bundlejs.com/?q=@hyper-fetch/orpc"><img src="https://api.maciejpyrc.com/portfolio/npm/size.svg?package=@hyper-fetch/orpc&external=@hyper-fetch/core,@orpc/client,@orpc/server" alt="Bundle size" /></a>
|
|
18
|
+
<a href="https://github.com/BetterTyped/hyper-fetch"><img src="https://img.shields.io/badge/TypeScript-strict-3178C6?logo=typescript&logoColor=white" alt="TypeScript" /></a>
|
|
19
|
+
<a href="https://hyperfetch.bettertyped.com/docs/integrations/adapter-orpc/overview"><img src="https://img.shields.io/badge/oRPC-v1-FF6CA5" alt="Integration" /></a>
|
|
20
|
+
<a href="https://github.com/BetterTyped/hyper-fetch/blob/main/License.md"><img src="https://img.shields.io/github/license/BetterTyped/hyper-fetch?color=blue" alt="License" /></a>
|
|
25
21
|
</p>
|
|
26
22
|
|
|
27
23
|
## 📖 About
|
|
28
24
|
|
|
29
|
-
|
|
30
|
-
requests
|
|
25
|
+
`@hyper-fetch/orpc` connects Hyper Fetch to an oRPC server through the oRPC RPC protocol. Procedures become regular
|
|
26
|
+
Hyper Fetch requests through `createSdk`, with inputs, outputs and defined errors inferred from your router or
|
|
27
|
+
contract, and event iterators become typed socket listeners. Rich types survive the wire thanks to the oRPC serializer.
|
|
31
28
|
|
|
32
29
|
## 🎯 Key Capabilities
|
|
33
30
|
|
|
34
|
-
- 🔮 **
|
|
31
|
+
- 🔮 **Types from your router or contract** - Inputs, outputs and `.errors()` maps inferred, no codegen
|
|
32
|
+
- 🛡️ **Defined errors you can switch on** - `error.code` narrows `error.data` to the shape you declared on the server
|
|
35
33
|
- 📅 **Rich types on the wire** - `Date`, `BigInt`, `Map`, `Set`, `URL` and files, encoded by the oRPC serializer
|
|
36
34
|
- 💾 **Cache per input** - `{ id: 1 }` and `{ id: 2 }` are cached, deduplicated and queued separately
|
|
37
|
-
-
|
|
38
|
-
-
|
|
35
|
+
- 🌐 **GET when your server allows it** - `queryMethod: "GET"` makes queries cacheable by browsers and CDNs
|
|
36
|
+
- ⚛️ **React hooks** - `useFetch` on `$query`, `useSubmit` on `$mutation`, file uploads included
|
|
37
|
+
- 📡 **Live event iterators** - Listen to `async function*` procedures over HTTP streams or one WebSocket
|
|
38
|
+
- ⏯️ **Resume where you stopped** - Reconnects send the last `withEventMeta` id, so the server can replay what you missed
|
|
39
39
|
|
|
40
40
|
## 🚀 Quick Start
|
|
41
41
|
|
|
@@ -51,6 +51,8 @@ import type { OrpcSchema } from "@hyper-fetch/orpc";
|
|
|
51
51
|
import type { router } from "./server";
|
|
52
52
|
|
|
53
53
|
const client = createClient({ url: "http://localhost:3000/rpc" }).setAdapter(OrpcAdapter());
|
|
54
|
+
|
|
55
|
+
// camelCaseToKebabCase: false keeps procedure names like findById as they are
|
|
54
56
|
const api = createSdk<typeof client, OrpcSchema<typeof router>>(client, { camelCaseToKebabCase: false });
|
|
55
57
|
|
|
56
58
|
const { data, error } = await api.planet.find.$query.setPayload({ id: 1 }).send();
|
|
@@ -58,9 +60,10 @@ const { data, error } = await api.planet.find.$query.setPayload({ id: 1 }).send(
|
|
|
58
60
|
|
|
59
61
|
## 📚 Documentation
|
|
60
62
|
|
|
61
|
-
- [oRPC Adapter
|
|
62
|
-
- [
|
|
63
|
-
- [
|
|
63
|
+
- **[oRPC Adapter](https://hyperfetch.bettertyped.com/docs/integrations/adapter-orpc/overview)** - Setup, GET queries, errors, serializers and caching
|
|
64
|
+
- **[Event Iterators](https://hyperfetch.bettertyped.com/docs/integrations/adapter-orpc/event-iterators)** - Streams, WebSockets and resume
|
|
65
|
+
- **[SDK](https://hyperfetch.bettertyped.com/docs/core/sdk)** - How `createSdk` turns a schema into requests
|
|
66
|
+
- **[API Reference](https://hyperfetch.bettertyped.com/docs/api/adapter-orpc/Functions/OrpcAdapter)** - Adapters, schemas and types
|
|
64
67
|
|
|
65
68
|
## 💡 Examples
|
|
66
69
|
|
|
@@ -69,19 +72,71 @@ const { data, error } = await api.planet.find.$query.setPayload({ id: 1 }).send(
|
|
|
69
72
|
```ts
|
|
70
73
|
const { data, error } = await api.planet.find.$query.setPayload({ id: 99 }).send();
|
|
71
74
|
|
|
72
|
-
|
|
75
|
+
// `error` also includes the global error of the client, so check for the oRPC shape first
|
|
76
|
+
if (error && "defined" in error && error.defined && error.code === "NOT_FOUND") {
|
|
77
|
+
// error.data has the shape declared in the procedure's .errors()
|
|
73
78
|
console.log(`Planet ${error.data.id} does not exist`);
|
|
74
79
|
}
|
|
75
80
|
```
|
|
76
81
|
|
|
77
|
-
### Upload a file
|
|
82
|
+
### Upload a file from React
|
|
78
83
|
|
|
79
84
|
```tsx
|
|
80
85
|
import { useSubmit } from "@hyper-fetch/react";
|
|
81
86
|
|
|
82
|
-
const {
|
|
87
|
+
const PlanetImage = ({ planetId }: { planetId: number }) => {
|
|
88
|
+
const { submit, submitting } = useSubmit(api.planet.uploadImage.$mutation);
|
|
89
|
+
|
|
90
|
+
return (
|
|
91
|
+
<input
|
|
92
|
+
type="file"
|
|
93
|
+
disabled={submitting}
|
|
94
|
+
onChange={(event) => {
|
|
95
|
+
const image = event.target.files?.[0];
|
|
96
|
+
if (image) submit({ payload: { planetId, image } });
|
|
97
|
+
}}
|
|
98
|
+
/>
|
|
99
|
+
);
|
|
100
|
+
};
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
### Cacheable GET queries
|
|
104
|
+
|
|
105
|
+
```ts
|
|
106
|
+
const client = createClient({ url: "http://localhost:3000/rpc" }).setAdapter(OrpcAdapter({ queryMethod: "GET" }));
|
|
83
107
|
|
|
84
|
-
|
|
108
|
+
// Fall back to POST for one request
|
|
109
|
+
const { data } = await api.planet.list.$query.setOptions({ queryMethod: "POST" }).send();
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
The server accepts GET for procedures declared with `.route({ method: "GET" })`.
|
|
113
|
+
|
|
114
|
+
### Listen to an event iterator
|
|
115
|
+
|
|
116
|
+
```ts
|
|
117
|
+
import { createSocketSdk, Socket } from "@hyper-fetch/sockets";
|
|
118
|
+
import { OrpcStreamAdapter } from "@hyper-fetch/orpc";
|
|
119
|
+
import type { OrpcSocketSchema } from "@hyper-fetch/orpc";
|
|
120
|
+
|
|
121
|
+
// Or OrpcWebsocketAdapter() with the RPCHandler of @orpc/server/ws
|
|
122
|
+
const socket = new Socket({ url: "http://localhost:3000/rpc", adapter: OrpcStreamAdapter() });
|
|
123
|
+
const live = createSocketSdk<typeof socket, OrpcSocketSchema<typeof router>>(socket, { camelCaseToKebabCase: false });
|
|
124
|
+
|
|
125
|
+
const stop = live.planet.onUpdate.$listener.setPayload({ id: 1 }).listen(({ data, extra }) => {
|
|
126
|
+
console.log(data.name, extra.id);
|
|
127
|
+
});
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
### Find the subscription that failed
|
|
131
|
+
|
|
132
|
+
```ts
|
|
133
|
+
import { OrpcSocketError } from "@hyper-fetch/orpc";
|
|
134
|
+
|
|
135
|
+
socket.onError(({ error }) => {
|
|
136
|
+
if (error instanceof OrpcSocketError && error.code === "UNAUTHORIZED") {
|
|
137
|
+
console.log(`${error.topic} was rejected for`, error.payload);
|
|
138
|
+
}
|
|
139
|
+
});
|
|
85
140
|
```
|
|
86
141
|
|
|
87
142
|
### Contract-first APIs
|
|
@@ -96,6 +151,37 @@ const api = createSdk<typeof client, OrpcSchema<ContractRouterClient<typeof cont
|
|
|
96
151
|
});
|
|
97
152
|
```
|
|
98
153
|
|
|
154
|
+
## 🧩 Hyper Fetch Ecosystem
|
|
155
|
+
|
|
156
|
+
One typed client for every backend. Swap the adapter and keep the same `createRequest()` everywhere.
|
|
157
|
+
|
|
158
|
+
<table align="center">
|
|
159
|
+
<tr>
|
|
160
|
+
<td align="center" width="110"><a href="https://github.com/BetterTyped/hyper-fetch/tree/main/packages/core"><img src="https://raw.githubusercontent.com/BetterTyped/hyper-fetch/main/documentation/static/img/integration-hyper-fetch.svg" width="36" height="36" alt="" /><br /><sub><b>Core</b></sub></a></td>
|
|
161
|
+
<td align="center" width="110"><a href="https://github.com/BetterTyped/hyper-fetch/tree/main/packages/react"><img src="https://raw.githubusercontent.com/BetterTyped/hyper-fetch/main/documentation/static/img/integration-react.svg" width="36" height="36" alt="" /><br /><sub><b>React</b></sub></a></td>
|
|
162
|
+
<td align="center" width="110"><a href="https://github.com/BetterTyped/hyper-fetch/tree/main/packages/sockets"><img src="https://raw.githubusercontent.com/BetterTyped/hyper-fetch/main/documentation/static/img/integration-sockets.svg" width="36" height="36" alt="" /><br /><sub><b>Sockets</b></sub></a></td>
|
|
163
|
+
<td align="center" width="110"><a href="https://github.com/BetterTyped/hyper-fetch/tree/main/packages/cli"><img src="https://raw.githubusercontent.com/BetterTyped/hyper-fetch/main/documentation/static/img/integration-openapi.svg" width="36" height="36" alt="" /><br /><sub><b>OpenAPI CLI</b></sub></a></td>
|
|
164
|
+
<td align="center" width="110"><a href="https://github.com/BetterTyped/hyper-fetch/tree/main/packages/adapter-graphql"><img src="https://raw.githubusercontent.com/BetterTyped/hyper-fetch/main/documentation/static/img/integration-graphql.svg" width="36" height="36" alt="" /><br /><sub><b>GraphQL</b></sub></a></td>
|
|
165
|
+
<td align="center" width="110"><a href="https://github.com/BetterTyped/hyper-fetch/tree/main/packages/adapter-trpc"><img src="https://raw.githubusercontent.com/BetterTyped/hyper-fetch/main/documentation/static/img/integration-trpc.svg" width="36" height="36" alt="" /><br /><sub><b>tRPC</b></sub></a></td>
|
|
166
|
+
</tr>
|
|
167
|
+
<tr>
|
|
168
|
+
<td align="center" width="110"><a href="https://github.com/BetterTyped/hyper-fetch/tree/main/packages/adapter-orpc"><picture><source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/BetterTyped/hyper-fetch/main/documentation/static/img/integration-orpc-dark.svg" /><img src="https://raw.githubusercontent.com/BetterTyped/hyper-fetch/main/documentation/static/img/integration-orpc.svg" width="36" height="36" alt="" /></picture><br /><sub><b>oRPC</b></sub></a></td>
|
|
169
|
+
<td align="center" width="110"><a href="https://github.com/BetterTyped/hyper-fetch/tree/main/packages/hono"><img src="https://raw.githubusercontent.com/BetterTyped/hyper-fetch/main/documentation/static/img/integration-hono.svg" width="36" height="36" alt="" /><br /><sub><b>Hono</b></sub></a></td>
|
|
170
|
+
<td align="center" width="110"><a href="https://github.com/BetterTyped/hyper-fetch/tree/main/packages/elysia"><img src="https://raw.githubusercontent.com/BetterTyped/hyper-fetch/main/documentation/static/img/integration-elysia.svg" width="36" height="36" alt="" /><br /><sub><b>Elysia</b></sub></a></td>
|
|
171
|
+
<td align="center" width="110"><a href="https://github.com/BetterTyped/hyper-fetch/tree/main/packages/adapter-firebase"><img src="https://raw.githubusercontent.com/BetterTyped/hyper-fetch/main/documentation/static/img/integration-firebase.svg" width="36" height="36" alt="" /><br /><sub><b>Firebase</b></sub></a></td>
|
|
172
|
+
<td align="center" width="110"><a href="https://github.com/BetterTyped/hyper-fetch/tree/main/packages/adapter-axios"><img src="https://raw.githubusercontent.com/BetterTyped/hyper-fetch/main/documentation/static/img/integration-axios.svg" width="36" height="36" alt="" /><br /><sub><b>Axios</b></sub></a></td>
|
|
173
|
+
<td align="center" width="110"><a href="https://github.com/BetterTyped/hyper-fetch/tree/main/packages/hyper-flow"><img src="https://raw.githubusercontent.com/BetterTyped/hyper-fetch/main/documentation/static/img/hyper-flow.svg" width="36" height="36" alt="" /><br /><sub><b>HyperFlow</b></sub></a></td>
|
|
174
|
+
</tr>
|
|
175
|
+
</table>
|
|
176
|
+
|
|
177
|
+
## 💖 Sponsors
|
|
178
|
+
|
|
179
|
+
<p align="center">
|
|
180
|
+
<a href="https://github.com/sponsors/prc5">
|
|
181
|
+
<img src="https://raw.githubusercontent.com/prc5/sponsors/main/packages/other/sponsorkit/sponsors.svg?raw=true" alt="Sponsors" />
|
|
182
|
+
</a>
|
|
183
|
+
</p>
|
|
184
|
+
|
|
99
185
|
## License
|
|
100
186
|
|
|
101
187
|
[Apache-2.0](https://github.com/BetterTyped/hyper-fetch/blob/main/License.md)
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
import { EventPublisher, ORPCError, os, withEventMeta } from "@orpc/server";
|
|
2
|
+
import { RPCHandler as NodeRPCHandler } from "@orpc/server/node";
|
|
3
|
+
import { RPCHandler as WsRPCHandler } from "@orpc/server/ws";
|
|
4
|
+
import { createServer } from "http";
|
|
5
|
+
import type { AddressInfo } from "net";
|
|
6
|
+
import type { WebSocket as ServerWebSocket } from "ws";
|
|
7
|
+
import { WebSocketServer } from "ws";
|
|
8
|
+
import { z } from "zod";
|
|
9
|
+
|
|
10
|
+
export type Planet = { id: number; name: string };
|
|
11
|
+
|
|
12
|
+
type Context = { authorization?: string };
|
|
13
|
+
|
|
14
|
+
/** One run of an event iterator procedure on the server */
|
|
15
|
+
export type IteratorRun = {
|
|
16
|
+
topic: string;
|
|
17
|
+
input: unknown;
|
|
18
|
+
lastEventId: string | undefined;
|
|
19
|
+
/** `true` once the `finally` block of the generator ran */
|
|
20
|
+
finished: boolean;
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* What the server knows about the subscriptions - which generators run, with which input and last event id,
|
|
25
|
+
* and whether they finished. Tests publish planet updates through it.
|
|
26
|
+
*/
|
|
27
|
+
export const createRealtimeState = () => {
|
|
28
|
+
const publisher = new EventPublisher<Record<string, Planet>>();
|
|
29
|
+
const runs: IteratorRun[] = [];
|
|
30
|
+
|
|
31
|
+
return {
|
|
32
|
+
runs,
|
|
33
|
+
/** Generators that did not finish yet */
|
|
34
|
+
active: () => runs.filter((run) => !run.finished),
|
|
35
|
+
publish: (planet: Planet) => publisher.publish(`planet/${planet.id}`, planet),
|
|
36
|
+
start: (run: Omit<IteratorRun, "finished">): IteratorRun => {
|
|
37
|
+
const entry = { ...run, finished: false };
|
|
38
|
+
runs.push(entry);
|
|
39
|
+
return entry;
|
|
40
|
+
},
|
|
41
|
+
subscribe: (id: number, signal: AbortSignal | undefined) => publisher.subscribe(`planet/${id}`, { signal }),
|
|
42
|
+
};
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
export type RealtimeState = ReturnType<typeof createRealtimeState>;
|
|
46
|
+
|
|
47
|
+
export const createRealtimeRouter = (state: RealtimeState) => {
|
|
48
|
+
const base = os.$context<Context>();
|
|
49
|
+
|
|
50
|
+
const authed = base.middleware(({ context, next }) => {
|
|
51
|
+
if (context.authorization !== "Bearer token") {
|
|
52
|
+
throw new ORPCError("UNAUTHORIZED", { message: "Missing token" });
|
|
53
|
+
}
|
|
54
|
+
return next();
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
return {
|
|
58
|
+
planet: {
|
|
59
|
+
find: base.input(z.object({ id: z.number() })).handler(({ input }): Planet => ({ id: input.id, name: "Earth" })),
|
|
60
|
+
/** Every update of the planet, the event ids continue from `lastEventId` after a reconnect */
|
|
61
|
+
onUpdate: base.input(z.object({ id: z.number() })).handler(async function* onUpdate({
|
|
62
|
+
input,
|
|
63
|
+
lastEventId,
|
|
64
|
+
signal,
|
|
65
|
+
}) {
|
|
66
|
+
const run = state.start({ topic: "planet/onUpdate", input, lastEventId });
|
|
67
|
+
let index = Number(lastEventId ?? 0);
|
|
68
|
+
try {
|
|
69
|
+
for await (const planet of state.subscribe(input.id, signal)) {
|
|
70
|
+
index += 1;
|
|
71
|
+
yield withEventMeta(planet, { id: String(index) });
|
|
72
|
+
}
|
|
73
|
+
} finally {
|
|
74
|
+
run.finished = true;
|
|
75
|
+
}
|
|
76
|
+
}),
|
|
77
|
+
},
|
|
78
|
+
/** A finite iterator with a return value */
|
|
79
|
+
countdown: base.input(z.object({ from: z.number() })).handler(async function* countdown({ input, lastEventId }) {
|
|
80
|
+
const run = state.start({ topic: "countdown", input, lastEventId });
|
|
81
|
+
try {
|
|
82
|
+
for (let value = input.from; value > 0; value -= 1) {
|
|
83
|
+
yield withEventMeta({ value }, { id: String(value) });
|
|
84
|
+
}
|
|
85
|
+
return "liftoff" as const;
|
|
86
|
+
} finally {
|
|
87
|
+
run.finished = true;
|
|
88
|
+
}
|
|
89
|
+
}),
|
|
90
|
+
/** Fails with a defined error after the first event */
|
|
91
|
+
overheat: base
|
|
92
|
+
.errors({ OVERHEATED: { message: "Too hot", data: z.object({ celsius: z.number() }) } })
|
|
93
|
+
.handler(async function* overheat({ errors }) {
|
|
94
|
+
yield withEventMeta({ celsius: 100 }, { id: "1" });
|
|
95
|
+
throw errors.OVERHEATED({ data: { celsius: 900 } });
|
|
96
|
+
}),
|
|
97
|
+
secret: base.use(authed).handler(async function* secret() {
|
|
98
|
+
yield "classified" as const;
|
|
99
|
+
}),
|
|
100
|
+
types: base.input(z.object({ since: z.date() })).handler(async function* types({ input }) {
|
|
101
|
+
yield { since: input.since, total: 10n, scores: new Map([["a", 1]]), tags: new Set(["x"]) };
|
|
102
|
+
}),
|
|
103
|
+
};
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
export type RealtimeRouter = ReturnType<typeof createRealtimeRouter>;
|
|
107
|
+
|
|
108
|
+
/** Real oRPC server with the `RPCHandler` of `@orpc/server/node`, answering with event streams */
|
|
109
|
+
export const createRealtimeHttpServer = (state: RealtimeState) => {
|
|
110
|
+
const handler = new NodeRPCHandler<Context>(createRealtimeRouter(state));
|
|
111
|
+
|
|
112
|
+
const server = createServer(async (req, res) => {
|
|
113
|
+
const { matched } = await handler.handle(req, res, {
|
|
114
|
+
prefix: "/rpc",
|
|
115
|
+
context: { authorization: req.headers.authorization },
|
|
116
|
+
});
|
|
117
|
+
if (!matched) {
|
|
118
|
+
res.statusCode = 404;
|
|
119
|
+
res.end("No procedure matched");
|
|
120
|
+
}
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
const start = () =>
|
|
124
|
+
new Promise<string>((resolve, reject) => {
|
|
125
|
+
server.once("error", reject);
|
|
126
|
+
server.listen(0, "127.0.0.1", () => {
|
|
127
|
+
const { port } = server.address() as AddressInfo;
|
|
128
|
+
resolve(`http://127.0.0.1:${port}/rpc`);
|
|
129
|
+
});
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
const stop = () =>
|
|
133
|
+
new Promise<void>((resolve, reject) => {
|
|
134
|
+
server.close((error) => (error ? reject(error) : resolve()));
|
|
135
|
+
server.closeAllConnections();
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
/** Drops every open connection, like a server restart */
|
|
139
|
+
const dropConnections = () => server.closeAllConnections();
|
|
140
|
+
|
|
141
|
+
return { start, stop, dropConnections };
|
|
142
|
+
};
|
|
143
|
+
|
|
144
|
+
/** Real oRPC server with the `RPCHandler` of `@orpc/server/ws` on a `ws` server */
|
|
145
|
+
export const createRealtimeWsServer = (state: RealtimeState) => {
|
|
146
|
+
const handler = new WsRPCHandler<Context>(createRealtimeRouter(state));
|
|
147
|
+
const wss = new WebSocketServer({ port: 0, host: "127.0.0.1" });
|
|
148
|
+
const connections = new Set<ServerWebSocket>();
|
|
149
|
+
|
|
150
|
+
wss.on("connection", (ws, request) => {
|
|
151
|
+
connections.add(ws);
|
|
152
|
+
ws.on("close", () => connections.delete(ws));
|
|
153
|
+
// Browsers can't set headers of the upgrade request, so the token comes in the query string
|
|
154
|
+
const token = new URL(request.url ?? "/", "http://localhost").searchParams.get("token");
|
|
155
|
+
handler.upgrade(ws, { context: { authorization: token ?? undefined } });
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
const start = () =>
|
|
159
|
+
new Promise<string>((resolve) => {
|
|
160
|
+
if (wss.address()) {
|
|
161
|
+
const { port } = wss.address() as AddressInfo;
|
|
162
|
+
resolve(`ws://127.0.0.1:${port}`);
|
|
163
|
+
return;
|
|
164
|
+
}
|
|
165
|
+
wss.once("listening", () => {
|
|
166
|
+
const { port } = wss.address() as AddressInfo;
|
|
167
|
+
resolve(`ws://127.0.0.1:${port}`);
|
|
168
|
+
});
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
const stop = () =>
|
|
172
|
+
new Promise<void>((resolve, reject) => {
|
|
173
|
+
connections.forEach((ws) => ws.terminate());
|
|
174
|
+
wss.close((error) => (error ? reject(error) : resolve()));
|
|
175
|
+
});
|
|
176
|
+
|
|
177
|
+
/** Drops every open connection without the closing handshake, like a lost network */
|
|
178
|
+
const dropConnections = () => connections.forEach((ws) => ws.terminate());
|
|
179
|
+
|
|
180
|
+
return { start, stop, dropConnections, connections };
|
|
181
|
+
};
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @vitest-environment jsdom
|
|
3
|
+
*/
|
|
4
|
+
import { useListener } from "@hyper-fetch/react";
|
|
5
|
+
import { createSocketSdk, Socket } from "@hyper-fetch/sockets";
|
|
6
|
+
import { cleanup, renderHook, waitFor } from "@testing-library/react";
|
|
7
|
+
import { StrictMode } from "react";
|
|
8
|
+
|
|
9
|
+
import type { OrpcSocketSchema } from "../../src/adapter";
|
|
10
|
+
import { OrpcSocketError } from "../../src/socket";
|
|
11
|
+
import { OrpcStreamAdapter } from "../../src/stream-adapter";
|
|
12
|
+
import { OrpcWebsocketAdapter } from "../../src/websocket-adapter";
|
|
13
|
+
import type { RealtimeRouter, RealtimeState } from "./e2e.orpc-realtime-server";
|
|
14
|
+
import { createRealtimeHttpServer, createRealtimeState, createRealtimeWsServer } from "./e2e.orpc-realtime-server";
|
|
15
|
+
|
|
16
|
+
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
|
|
17
|
+
|
|
18
|
+
/** Hooks re-render only for the fields read during the render */
|
|
19
|
+
const track = <T extends Record<string, any>>(hook: T) => {
|
|
20
|
+
["data", "extra", "connected", "status", "error"].forEach((field) => hook[field]);
|
|
21
|
+
return hook;
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
const transports = [
|
|
25
|
+
{
|
|
26
|
+
name: "OrpcStreamAdapter",
|
|
27
|
+
createServer: createRealtimeHttpServer,
|
|
28
|
+
createSocket: (url: string) => new Socket({ url, adapter: OrpcStreamAdapter() }),
|
|
29
|
+
},
|
|
30
|
+
{
|
|
31
|
+
name: "OrpcWebsocketAdapter",
|
|
32
|
+
createServer: createRealtimeWsServer,
|
|
33
|
+
createSocket: (url: string) => new Socket({ url, adapter: OrpcWebsocketAdapter() }),
|
|
34
|
+
},
|
|
35
|
+
];
|
|
36
|
+
|
|
37
|
+
describe.each(transports)("Orpc Realtime [ React $name ]", ({ createServer, createSocket }) => {
|
|
38
|
+
let state: RealtimeState = createRealtimeState();
|
|
39
|
+
let server = createServer(state);
|
|
40
|
+
let socket: ReturnType<typeof createSocket> | undefined;
|
|
41
|
+
|
|
42
|
+
const createApi = (url: string) => {
|
|
43
|
+
const created = createSocket(url);
|
|
44
|
+
socket = created;
|
|
45
|
+
return createSocketSdk<typeof created, OrpcSocketSchema<RealtimeRouter>>(created, { camelCaseToKebabCase: false });
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
/** Generators of the input that did not finish */
|
|
49
|
+
const activeOf = (id: number) => state.active().filter((run) => (run.input as { id: number }).id === id);
|
|
50
|
+
|
|
51
|
+
beforeEach(async () => {
|
|
52
|
+
state = createRealtimeState();
|
|
53
|
+
server = createServer(state);
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
afterEach(async () => {
|
|
57
|
+
cleanup();
|
|
58
|
+
await socket?.disconnect();
|
|
59
|
+
socket = undefined;
|
|
60
|
+
await server.stop();
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
it("should show the events of the subscription", async () => {
|
|
64
|
+
const sdk = createApi(await server.start());
|
|
65
|
+
|
|
66
|
+
const { result } = renderHook(() => track(useListener(sdk.planet.onUpdate.$listener.setPayload({ id: 1 }))));
|
|
67
|
+
await waitFor(() => expect(activeOf(1)).toHaveLength(1));
|
|
68
|
+
state.publish({ id: 1, name: "Earth" });
|
|
69
|
+
|
|
70
|
+
await waitFor(() => expect(result.current.data).toStrictEqual({ id: 1, name: "Earth" }));
|
|
71
|
+
expect(result.current.extra).toStrictEqual({ id: "1", retry: undefined });
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
it("should subscribe again when the payload changes", async () => {
|
|
75
|
+
const sdk = createApi(await server.start());
|
|
76
|
+
|
|
77
|
+
const { result, rerender } = renderHook(
|
|
78
|
+
({ id }) => track(useListener(sdk.planet.onUpdate.$listener.setPayload({ id }))),
|
|
79
|
+
{ initialProps: { id: 1 } },
|
|
80
|
+
);
|
|
81
|
+
await waitFor(() => expect(activeOf(1)).toHaveLength(1));
|
|
82
|
+
state.publish({ id: 1, name: "Earth" });
|
|
83
|
+
await waitFor(() => expect(result.current.data).toStrictEqual({ id: 1, name: "Earth" }));
|
|
84
|
+
|
|
85
|
+
rerender({ id: 2 });
|
|
86
|
+
|
|
87
|
+
await waitFor(() => expect(activeOf(2)).toHaveLength(1));
|
|
88
|
+
await waitFor(() => expect(activeOf(1)).toHaveLength(0));
|
|
89
|
+
state.publish({ id: 1, name: "Old" });
|
|
90
|
+
state.publish({ id: 2, name: "Mars" });
|
|
91
|
+
await waitFor(() => expect(result.current.data).toStrictEqual({ id: 2, name: "Mars" }));
|
|
92
|
+
expect(state.runs.filter((run) => (run.input as { id: number }).id === 2)).toHaveLength(1);
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
it("should hold one server subscription in StrictMode", async () => {
|
|
96
|
+
const sdk = createApi(await server.start());
|
|
97
|
+
const onEvent = vi.fn();
|
|
98
|
+
|
|
99
|
+
const { result } = renderHook(
|
|
100
|
+
() => {
|
|
101
|
+
const listener = track(useListener(sdk.planet.onUpdate.$listener.setPayload({ id: 1 })));
|
|
102
|
+
listener.onEvent(({ data }) => onEvent(data));
|
|
103
|
+
return listener;
|
|
104
|
+
},
|
|
105
|
+
{ wrapper: StrictMode },
|
|
106
|
+
);
|
|
107
|
+
|
|
108
|
+
// The subscription of the first StrictMode mount is aborted, its generator finishes
|
|
109
|
+
await waitFor(() => expect(activeOf(1)).toHaveLength(1));
|
|
110
|
+
await waitFor(() => expect(state.runs.filter((run) => run.finished)).toHaveLength(state.runs.length - 1));
|
|
111
|
+
state.publish({ id: 1, name: "Earth" });
|
|
112
|
+
|
|
113
|
+
await waitFor(() => expect(result.current.data).toStrictEqual({ id: 1, name: "Earth" }));
|
|
114
|
+
expect(onEvent).toHaveBeenCalledOnce();
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
/** Statuses rendered in order, without repeats - React may render two quick changes at once */
|
|
118
|
+
const renderedStatuses = (statuses: string[]) => statuses.filter((status, index) => status !== statuses[index - 1]);
|
|
119
|
+
|
|
120
|
+
it("should be listening once the server confirms the subscription", async () => {
|
|
121
|
+
const sdk = createApi(await server.start());
|
|
122
|
+
|
|
123
|
+
const { result } = renderHook(() => track(useListener(sdk.planet.onUpdate.$listener.setPayload({ id: 1 }))));
|
|
124
|
+
|
|
125
|
+
expect(result.current.status).toBe("starting");
|
|
126
|
+
await waitFor(() => expect(result.current.status).toBe("listening"));
|
|
127
|
+
expect(activeOf(1)).toHaveLength(1);
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
it("should go from starting to listening to ended for a finite iterator", async () => {
|
|
131
|
+
const sdk = createApi(await server.start());
|
|
132
|
+
const statuses: string[] = [];
|
|
133
|
+
const onStart = vi.fn();
|
|
134
|
+
|
|
135
|
+
const { result } = renderHook(() => {
|
|
136
|
+
const listener = track(useListener(sdk.countdown.$listener.setPayload({ from: 2 })));
|
|
137
|
+
listener.onStart(onStart);
|
|
138
|
+
statuses.push(listener.status);
|
|
139
|
+
return listener;
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
await waitFor(() => expect(result.current.status).toBe("ended"));
|
|
143
|
+
expect(onStart).toHaveBeenCalledOnce();
|
|
144
|
+
expect(result.current.data).toStrictEqual({ value: 1 });
|
|
145
|
+
expect(result.current.error).toBeNull();
|
|
146
|
+
expect(["idle", "starting", "listening", "ended"]).toIncludeAllMembers(renderedStatuses(statuses));
|
|
147
|
+
expect(renderedStatuses(statuses).slice(0, 2)).toStrictEqual(["idle", "starting"]);
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
it("should go to failed with the OrpcSocketError when the iterator fails", async () => {
|
|
151
|
+
const sdk = createApi(await server.start());
|
|
152
|
+
const statuses: string[] = [];
|
|
153
|
+
const onStart = vi.fn();
|
|
154
|
+
|
|
155
|
+
const { result } = renderHook(() => {
|
|
156
|
+
const listener = track(useListener(sdk.overheat.$listener));
|
|
157
|
+
listener.onStart(onStart);
|
|
158
|
+
statuses.push(listener.status);
|
|
159
|
+
return listener;
|
|
160
|
+
});
|
|
161
|
+
|
|
162
|
+
await waitFor(() => expect(result.current.status).toBe("failed"));
|
|
163
|
+
expect(onStart).toHaveBeenCalledOnce();
|
|
164
|
+
expect(result.current.error).toBeInstanceOf(OrpcSocketError);
|
|
165
|
+
expect(result.current.error).toMatchObject({ topic: "overheat", code: "OVERHEATED", defined: true });
|
|
166
|
+
expect(result.current.data).toStrictEqual({ celsius: 100 });
|
|
167
|
+
expect(renderedStatuses(statuses).slice(0, 2)).toStrictEqual(["idle", "starting"]);
|
|
168
|
+
});
|
|
169
|
+
|
|
170
|
+
it("should stop the server subscription on unmount", async () => {
|
|
171
|
+
const sdk = createApi(await server.start());
|
|
172
|
+
|
|
173
|
+
const { unmount } = renderHook(() => track(useListener(sdk.planet.onUpdate.$listener.setPayload({ id: 1 }))));
|
|
174
|
+
await waitFor(() => expect(activeOf(1)).toHaveLength(1));
|
|
175
|
+
|
|
176
|
+
unmount();
|
|
177
|
+
|
|
178
|
+
await waitFor(() => expect(state.active()).toHaveLength(0));
|
|
179
|
+
expect(state.runs.every((run) => run.finished)).toBeTrue();
|
|
180
|
+
});
|
|
181
|
+
});
|