@hyper-fetch/orpc 10.0.0 โ†’ 10.1.1

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
@@ -1,46 +1,41 @@
1
- # ๐Ÿ›ธ Hyper Fetch oRPC
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>oRPC adapter for HyperFetch. Typed procedures with caching, queueing and React hooks.</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
- <img src="https://img.shields.io/github/stars/BetterTyped/hyper-fetch?logo=github&color=118ab2" />
10
- </a>
11
- <a href="https://www.npmjs.com/package/@hyper-fetch/orpc">
12
- <img src="https://img.shields.io/npm/v/@hyper-fetch/orpc.svg?logo=npm&color=e76f51" />
13
- </a>
14
- <a href="https://www.npmjs.com/package/@hyper-fetch/orpc">
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
- This adapter connects HyperFetch to an oRPC server through the oRPC RPC protocol. Procedures become regular HyperFetch
30
- requests, with inputs, outputs and defined errors inferred from your router through `createSdk`, and event iterators
31
- become typed socket listeners.
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.
32
28
 
33
29
  ## ๐ŸŽฏ Key Capabilities
34
30
 
35
- - ๐Ÿ”ฎ **End-to-end types** - Inputs, outputs and `.errors()` maps inferred from your router or contract
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
36
33
  - ๐Ÿ“… **Rich types on the wire** - `Date`, `BigInt`, `Map`, `Set`, `URL` and files, encoded by the oRPC serializer
37
34
  - ๐Ÿ’พ **Cache per input** - `{ id: 1 }` and `{ id: 2 }` are cached, deduplicated and queued separately
38
- - โš›๏ธ **React-ready** - Use `useFetch` and `useSubmit` with your procedures
39
- - ๐ŸŒ **GET when you want it** - Opt into cacheable `GET` queries for the procedures your server allows
40
- - ๐Ÿ“ก **Live event iterators** - Listen to `async function*` procedures over HTTP streams or one WebSocket with
41
- `useListener`
42
- - ๐Ÿ” **Resume where you stopped** - Reconnects send the last `withEventMeta` id, so the server can replay what you
43
- missed
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
44
39
 
45
40
  ## ๐Ÿš€ Quick Start
46
41
 
@@ -56,6 +51,8 @@ import type { OrpcSchema } from "@hyper-fetch/orpc";
56
51
  import type { router } from "./server";
57
52
 
58
53
  const client = createClient({ url: "http://localhost:3000/rpc" }).setAdapter(OrpcAdapter());
54
+
55
+ // camelCaseToKebabCase: false keeps procedure names like findById as they are
59
56
  const api = createSdk<typeof client, OrpcSchema<typeof router>>(client, { camelCaseToKebabCase: false });
60
57
 
61
58
  const { data, error } = await api.planet.find.$query.setPayload({ id: 1 }).send();
@@ -63,10 +60,10 @@ const { data, error } = await api.planet.find.$query.setPayload({ id: 1 }).send(
63
60
 
64
61
  ## ๐Ÿ“š Documentation
65
62
 
66
- - [oRPC Adapter Docs](https://hyperfetch.bettertyped.com/docs/integrations/adapter-orpc/overview)
67
- - [Event Iterators](https://hyperfetch.bettertyped.com/docs/integrations/adapter-orpc/event-iterators)
68
- - [Getting Started](https://hyperfetch.bettertyped.com/docs/getting-started/quick-start)
69
- - [API Reference](https://hyperfetch.bettertyped.com/api/)
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
70
67
 
71
68
  ## ๐Ÿ’ก Examples
72
69
 
@@ -75,21 +72,45 @@ const { data, error } = await api.planet.find.$query.setPayload({ id: 1 }).send(
75
72
  ```ts
76
73
  const { data, error } = await api.planet.find.$query.setPayload({ id: 99 }).send();
77
74
 
78
- if (error?.defined && error.code === "NOT_FOUND") {
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()
79
78
  console.log(`Planet ${error.data.id} does not exist`);
80
79
  }
81
80
  ```
82
81
 
83
- ### Upload a file
82
+ ### Upload a file from React
84
83
 
85
84
  ```tsx
86
85
  import { useSubmit } from "@hyper-fetch/react";
87
86
 
88
- const { submit, submitting } = useSubmit(api.planet.uploadImage.$mutation);
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" }));
89
107
 
90
- await submit({ payload: { planetId: 1, image: file } });
108
+ // Fall back to POST for one request
109
+ const { data } = await api.planet.list.$query.setOptions({ queryMethod: "POST" }).send();
91
110
  ```
92
111
 
112
+ The server accepts GET for procedures declared with `.route({ method: "GET" })`.
113
+
93
114
  ### Listen to an event iterator
94
115
 
95
116
  ```ts
@@ -130,6 +151,37 @@ const api = createSdk<typeof client, OrpcSchema<ContractRouterClient<typeof cont
130
151
  });
131
152
  ```
132
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
+
133
185
  ## License
134
186
 
135
187
  [Apache-2.0](https://github.com/BetterTyped/hyper-fetch/blob/main/License.md)
@@ -177,6 +177,29 @@ describe("Orpc Adapter [ Lifecycle ]", () => {
177
177
 
178
178
  expect(onUploadProgress).toHaveBeenCalledWith(expect.objectContaining({ loaded: size, total: size }));
179
179
  });
180
+
181
+ it("should report the finished upload only once the server has the body", async () => {
182
+ let serverHasBody = false;
183
+ server.use(
184
+ http.post(`${url}/user/create`, async ({ request }) => {
185
+ await request.text();
186
+ serverHasBody = true;
187
+ return HttpResponse.json({ json: null });
188
+ }),
189
+ );
190
+ const progress: { loaded: number; total: number; serverHasBody: boolean }[] = [];
191
+ const payload = { name: "John" };
192
+ const size = new Blob([JSON.stringify({ json: payload })]).size;
193
+
194
+ await createMutation()
195
+ .setPayload(payload)
196
+ .send({ onUploadProgress: ({ loaded, total }) => progress.push({ loaded, total, serverHasBody }) });
197
+
198
+ // Fetch has no upload events, so only the response can finish the upload
199
+ expect(progress.filter(({ loaded, total }) => loaded === total)).toStrictEqual([
200
+ { loaded: size, total: size, serverHasBody: true },
201
+ ]);
202
+ });
180
203
  });
181
204
 
182
205
  describe("when retrying", () => {
@@ -113,6 +113,25 @@ describe("Orpc Adapter [ Schema ]", () => {
113
113
  expectTypeOf(read).toBeFunction();
114
114
  });
115
115
 
116
+ it("should narrow the error of send, which includes the global error of the client", () => {
117
+ // The example of the docs - the client has the default global error, so `error` is a union with `Error`
118
+ const read = async () => {
119
+ const { error } = await api.user.byId.$query.setPayload({ id: 999 }).send();
120
+
121
+ if (error && "defined" in error) {
122
+ expectTypeOf(error.defined).toEqualTypeOf<boolean>();
123
+ expectTypeOf(error.status).toEqualTypeOf<number>();
124
+ if (error.defined && error.code === "NOT_FOUND") {
125
+ expectTypeOf(error.data).toEqualTypeOf<{ id: number }>();
126
+ }
127
+ }
128
+ // @ts-expect-error the global error of the client has no `defined` flag
129
+ return error?.defined;
130
+ };
131
+
132
+ expectTypeOf(read).toBeFunction();
133
+ });
134
+
116
135
  it("should type procedures without defined errors", () => {
117
136
  expectTypeOf<ExtractLocalErrorType<Health>>().toEqualTypeOf<OrpcErrorType & { defined: false }>();
118
137
  expectTypeOf<OrpcErrorType["status"]>().toEqualTypeOf<number>();
@@ -288,15 +288,18 @@ describe("Orpc Stream Adapter [ Lifecycle ]", () => {
288
288
  expect(server.active()).toHaveLength(0);
289
289
  });
290
290
 
291
- it("should stop after the reconnect attempts of the socket", async () => {
291
+ it("should not be refused by the reconnect attempts of the socket", async () => {
292
292
  await recreate({ reconnect: 0 });
293
+ await subscribe();
293
294
  const failed = vi.fn();
294
295
  setup.socket.events.onReconnectingFailed(failed);
295
296
 
296
297
  await setup.socket.reconnect();
298
+ await flushPromises();
297
299
 
298
- expect(failed).toHaveBeenCalledOnce();
299
- expect(setup.socket.adapter.connected).toBeFalse();
300
+ expect(failed).not.toHaveBeenCalled();
301
+ expect(setup.socket.adapter.connected).toBeTrue();
302
+ expect(server.active()).toHaveLength(1);
300
303
  });
301
304
  });
302
305
 
@@ -438,13 +441,16 @@ describe("Orpc Stream Adapter [ Lifecycle ]", () => {
438
441
  server.calls[0].fail();
439
442
  await flushPromises();
440
443
 
444
+ // Going offline aborts the running stream and the wait of the failed one, online starts both again
445
+ setup.socket.appManager.setOnline(false);
441
446
  setup.socket.appManager.setOnline(true);
442
447
  await flushPromises();
443
- expect(server.calls).toHaveLength(3);
448
+ expect(server.calls).toHaveLength(4);
449
+ expect(server.active().map((call) => call.body)).toStrictEqual([{ json: { id: 1 } }, { json: { id: 2 } }]);
444
450
 
445
451
  // The cleared delay does not start it once more
446
452
  await advance(5000);
447
- expect(server.calls).toHaveLength(3);
453
+ expect(server.calls).toHaveLength(4);
448
454
  });
449
455
 
450
456
  it("should not start a stream that waits when its last listener unsubscribes", async () => {
@@ -496,6 +502,49 @@ describe("Orpc Stream Adapter [ Lifecycle ]", () => {
496
502
  expect(server.last().url).toBe(`${streamUrl}/planet/onUpdate`);
497
503
  });
498
504
 
505
+ it("should abort every stream offline and start them again with the last event id online", async () => {
506
+ const { callback } = await subscribe();
507
+ const first = server.last();
508
+ first.open();
509
+ first.send({ data: serialize({ id: 1, name: "a" }), id: "6" });
510
+ await flushPromises();
511
+
512
+ setup.socket.appManager.setOnline(false);
513
+ await flushPromises();
514
+ first.send({ data: serialize({ id: 1, name: "late" }) });
515
+ await advance(60_000);
516
+
517
+ expect(first.aborted).toBeTrue();
518
+ expect(setup.socket.adapter.connected).toBeFalse();
519
+ expect(server.calls).toHaveLength(1);
520
+
521
+ setup.socket.appManager.setOnline(true);
522
+ await flushPromises();
523
+ server.last().open();
524
+ server.last().send({ data: serialize({ id: 1, name: "b" }) });
525
+ await flushPromises();
526
+
527
+ expect(setup.socket.adapter.connected).toBeTrue();
528
+ expect(server.calls).toHaveLength(2);
529
+ expect(server.last().headers["last-event-id"]).toBe("6");
530
+ expect(callback.mock.calls.map(([data]) => data.name)).toStrictEqual(["a", "b"]);
531
+ });
532
+
533
+ it("should connect a socket connected by hand without autoConnect again", async () => {
534
+ await recreate({ adapterOptions: { autoConnect: false } });
535
+ await subscribe();
536
+ await setup.socket.connect();
537
+ await flushPromises();
538
+
539
+ setup.socket.appManager.setOnline(false);
540
+ setup.socket.appManager.setOnline(true);
541
+ await flushPromises();
542
+
543
+ expect(setup.socket.adapter.connected).toBeTrue();
544
+ expect(server.calls).toHaveLength(2);
545
+ expect(server.active()).toHaveLength(1);
546
+ });
547
+
499
548
  it("should not connect a socket without autoConnect", async () => {
500
549
  await recreate({ adapterOptions: { autoConnect: false } });
501
550
 
@@ -23,6 +23,8 @@ describe("Orpc Websocket Adapter [ Environment ]", () => {
23
23
 
24
24
  beforeEach(async () => {
25
25
  vi.useFakeTimers();
26
+ // The reconnect delay is jittered - the lowest one is exactly the reconnect time
27
+ vi.spyOn(Math, "random").mockReturnValue(0);
26
28
  Controlled = installControlledWebSocket();
27
29
  setup = createWebsocketSocket({ adapterOptions: { autoConnect: false } });
28
30
  await flushPromises();
@@ -32,6 +34,7 @@ describe("Orpc Websocket Adapter [ Environment ]", () => {
32
34
  await setup.socket.disconnect();
33
35
  vi.useRealTimers();
34
36
  vi.unstubAllGlobals();
37
+ vi.restoreAllMocks();
35
38
  });
36
39
 
37
40
  describe("when the server answers slowly", () => {
@@ -51,6 +54,9 @@ describe("Orpc Websocket Adapter [ Environment ]", () => {
51
54
  const created = Controlled.instances.length;
52
55
 
53
56
  await advance(100);
57
+ expect(Controlled.instances).toHaveLength(created);
58
+ // The connection timeout is followed by the reconnect delay
59
+ await advance(10_000);
54
60
  expect(Controlled.instances).toHaveLength(created + 1);
55
61
  Controlled.last.serverOpen();
56
62
  await flushPromises();
@@ -13,6 +13,8 @@ describe("Orpc Websocket Adapter [ Handshake error without close ]", () => {
13
13
 
14
14
  beforeEach(() => {
15
15
  vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
16
+ // The reconnect delay is jittered - the lowest one is exactly the reconnect time
17
+ vi.spyOn(Math, "random").mockReturnValue(0);
16
18
  installControlledWebSocket();
17
19
  socket = new Socket({
18
20
  url: "ws://refused",
@@ -27,6 +29,7 @@ describe("Orpc Websocket Adapter [ Handshake error without close ]", () => {
27
29
  vi.clearAllTimers();
28
30
  vi.useRealTimers();
29
31
  vi.unstubAllGlobals();
32
+ vi.restoreAllMocks();
30
33
  });
31
34
 
32
35
  it("should start the next attempt after the reconnect delay", async () => {
@@ -35,6 +35,8 @@ describe("Orpc Websocket Adapter [ Lifecycle ]", () => {
35
35
 
36
36
  beforeEach(async () => {
37
37
  vi.useFakeTimers();
38
+ // The reconnect delay is jittered - the lowest one is exactly the reconnect time
39
+ vi.spyOn(Math, "random").mockReturnValue(0);
38
40
  Controlled = installControlledWebSocket();
39
41
  setup = createWebsocketSocket();
40
42
  await flushPromises();
@@ -44,6 +46,7 @@ describe("Orpc Websocket Adapter [ Lifecycle ]", () => {
44
46
  await setup.socket.disconnect();
45
47
  vi.useRealTimers();
46
48
  vi.unstubAllGlobals();
49
+ vi.restoreAllMocks();
47
50
  });
48
51
 
49
52
  describe("when connecting", () => {
@@ -67,6 +70,18 @@ describe("Orpc Websocket Adapter [ Lifecycle ]", () => {
67
70
  expect(ws.requests.map(({ p }) => p?.b)).toStrictEqual([{ json: { id: 1 } }, { json: { id: 2 } }]);
68
71
  });
69
72
 
73
+ it("should not send the requests when an onConnected callback disconnects", async () => {
74
+ subscribe({ id: 1 });
75
+ setup.socket.onConnected(() => {
76
+ setup.socket.disconnect();
77
+ });
78
+
79
+ const ws = await open();
80
+
81
+ expect(ws.sent).toStrictEqual([]);
82
+ expect(setup.socket.adapter.connected).toBeFalse();
83
+ });
84
+
70
85
  it("should send the request of a listener added by an onConnected callback once", async () => {
71
86
  subscribe({ id: 1 });
72
87
  setup.socket.onConnected(() => {
@@ -145,6 +160,9 @@ describe("Orpc Websocket Adapter [ Lifecycle ]", () => {
145
160
  subscribe();
146
161
 
147
162
  await advance(5000);
163
+ expect(Controlled.instances).toHaveLength(1);
164
+ // The next attempt waits for the reconnect delay
165
+ await advance(1000);
148
166
  const ws = await open();
149
167
 
150
168
  expect(Controlled.instances).toHaveLength(2);
@@ -217,6 +235,35 @@ describe("Orpc Websocket Adapter [ Lifecycle ]", () => {
217
235
  expect(Controlled.instances).toHaveLength(1);
218
236
  });
219
237
 
238
+ it("should report the disconnect before the error that explains it", async () => {
239
+ const ws = await open();
240
+ const events: string[] = [];
241
+ setup.socket.events.onDisconnected(() => events.push("disconnected"));
242
+ setup.socket.events.onError(() => events.push("error"));
243
+ setup.socket.events.onReconnecting(({ attempts }) => events.push(`reconnecting:${attempts}`));
244
+
245
+ ws.serverClose({ code: 1006 });
246
+ await advance(1000);
247
+
248
+ expect(events).toStrictEqual(["disconnected", "error", "reconnecting:0"]);
249
+ });
250
+
251
+ it("should report the disconnect before the error of the connection timeout", async () => {
252
+ const events: string[] = [];
253
+ setup.socket.events.onDisconnected(() => events.push("disconnected"));
254
+ setup.socket.events.onError(() => events.push("error"));
255
+ setup.socket.events.onReconnecting(({ attempts }) => events.push(`reconnecting:${attempts}`));
256
+
257
+ await advance(5000);
258
+ expect(events).toStrictEqual(["disconnected", "error"]);
259
+ expect(setup.errors.map(({ message }) => message)).toStrictEqual([
260
+ "Connection timeout - no connection within 5000ms",
261
+ ]);
262
+
263
+ await advance(1000);
264
+ expect(events.at(-1)).toBe("reconnecting:0");
265
+ });
266
+
220
267
  it("should ignore the frames of a closed connection", async () => {
221
268
  const { callback } = subscribe();
222
269
  const ws = await open();
@@ -229,7 +276,65 @@ describe("Orpc Websocket Adapter [ Lifecycle ]", () => {
229
276
  });
230
277
  });
231
278
 
279
+ describe("when the network changes", () => {
280
+ it("should close the connection offline and start the subscriptions again with the last event ids online", async () => {
281
+ const { callback } = subscribe();
282
+ const first = await open();
283
+ first.serverStartIterator("1");
284
+ first.serverEvent("1", { data: serialize({ id: 1, name: "a" }), meta: { id: "7" } });
285
+
286
+ setup.socket.appManager.setOnline(false);
287
+ await advance(60_000);
288
+
289
+ expect(first.readyState).toBe(Controlled.CLOSED);
290
+ expect(setup.socket.adapter.connected).toBeFalse();
291
+ expect(Controlled.instances).toHaveLength(1);
292
+
293
+ setup.socket.appManager.setOnline(true);
294
+ await flushPromises();
295
+ const second = await open();
296
+ second.serverStartIterator("2");
297
+ second.serverEvent("2", { data: serialize({ id: 1, name: "b" }) });
298
+
299
+ expect(second.requests.map(({ i, p }) => [i, p?.h])).toStrictEqual([["2", { "last-event-id": "7" }]]);
300
+ expect(callback.mock.calls.map(([data]) => data.name)).toStrictEqual(["a", "b"]);
301
+ });
302
+
303
+ it("should recover a socket connected by hand without autoConnect", async () => {
304
+ await recreate({ adapterOptions: { autoConnect: false } });
305
+ subscribe();
306
+ const connecting = setup.socket.adapter.connect();
307
+ await flushPromises();
308
+ await open();
309
+ await connecting;
310
+
311
+ setup.socket.appManager.setOnline(false);
312
+ setup.socket.appManager.setOnline(true);
313
+ await flushPromises();
314
+ const ws = await open();
315
+
316
+ expect(setup.socket.adapter.connected).toBeTrue();
317
+ expect(ws.requests).toHaveLength(1);
318
+ });
319
+ });
320
+
232
321
  describe("when disconnecting", () => {
322
+ it("should finish disconnecting when closing the transport throws", async () => {
323
+ const ws = await open();
324
+ // Some runtimes throw when closing a transport that never connected
325
+ vi.spyOn(ws, "close").mockImplementation(() => {
326
+ throw new Error("WebSocket was closed before the connection was established");
327
+ });
328
+
329
+ await setup.socket.disconnect();
330
+ await advance(60_000);
331
+
332
+ expect(setup.socket.adapter.connected).toBeFalse();
333
+ expect(setup.socket.adapter.forceClosed).toBeTrue();
334
+ expect(Controlled.instances).toHaveLength(1);
335
+ expect(setup.errors).toStrictEqual([]);
336
+ });
337
+
233
338
  it("should close the connection and keep the listeners", async () => {
234
339
  subscribe();
235
340
  const ws = await open();
@@ -310,6 +415,23 @@ describe("Orpc Websocket Adapter [ Lifecycle ]", () => {
310
415
  expect(setup.socket.adapter.connected).toBeTrue();
311
416
  });
312
417
 
418
+ it("should not be refused by the reconnect attempts of the socket", async () => {
419
+ await recreate({ reconnect: 0 });
420
+ subscribe();
421
+ await open();
422
+ const failed = vi.fn();
423
+ setup.socket.events.onReconnectingFailed(failed);
424
+
425
+ const reconnecting = setup.socket.reconnect();
426
+ await flushPromises();
427
+ const ws = await open();
428
+ await reconnecting;
429
+
430
+ expect(failed).not.toHaveBeenCalled();
431
+ expect(setup.socket.adapter.connected).toBeTrue();
432
+ expect(ws.requests).toHaveLength(1);
433
+ });
434
+
313
435
  it("should let disconnect called while reconnecting win", async () => {
314
436
  await open();
315
437
 
@@ -1 +1 @@
1
- {"version":3,"file":"adapter.fetch.d.ts","sourceRoot":"","sources":["../../src/adapter/adapter.fetch.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAEV,sBAAsB,EACtB,eAAe,EAGhB,MAAM,iBAAiB,CAAC;AAyDzB,eAAO,MAAM,cAAc,GAAI,8DAG5B,sBAA2B,KAAG,eA4JhC,CAAC"}
1
+ {"version":3,"file":"adapter.fetch.d.ts","sourceRoot":"","sources":["../../src/adapter/adapter.fetch.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAEV,sBAAsB,EACtB,eAAe,EAGhB,MAAM,iBAAiB,CAAC;AAyDzB,eAAO,MAAM,cAAc,GAAI,8DAG5B,sBAA2B,KAAG,eA6JhC,CAAC"}