trpc-msw 3.6.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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2020-present Jimmy Chen
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,87 @@
1
+ # trpc-msw
2
+
3
+ [![Apache-2.0 licensed][badge-license]][url-license]
4
+ [![NPM version][badge-npm-version]][url-npm]
5
+ [![NPM downloads][badge-npm-downloads]][url-npm]
6
+ [![NPM Unpacked Size (with version)][badge-npm-unpacked-size]][url-npm]
7
+
8
+ tRPC for [Mock Service Worker](https://mswjs.io). Register a resolver per procedure, typed off your router, and every call your client makes is answered at the network by tRPC's own handlers — so batching, your transformer, your error formatter, `FormData` input and subscriptions over server-sent events or WebSockets all behave exactly as they do against the real server.
9
+
10
+ ## Table of Contents
11
+
12
+ - 🚀 [Getting Started](#getting-started)
13
+ - 📖 [Documentation](#documentation)
14
+ - ⚖️ [License](#license)
15
+
16
+ ---
17
+
18
+ ## <a name="getting-started">🚀 Getting Started</a>
19
+
20
+ ```bash
21
+ pnpm i -D trpc-msw msw @trpc/server
22
+ ```
23
+
24
+ ```ts
25
+ import type { AppRouter } from "./server/router";
26
+
27
+ import { initTRPC } from "@trpc/server";
28
+ import { setupServer } from "msw/node";
29
+ import superjson from "superjson";
30
+ import { createTRPCMsw } from "trpc-msw";
31
+
32
+ const { handlers, reset, trpc } = createTRPCMsw<AppRouter>({
33
+ endpoint: "http://localhost:3000/api/trpc",
34
+ // The same options your server's initTRPC.create takes, so mocked answers are shaped like real ones
35
+ t: initTRPC.create({ transformer: superjson }),
36
+ webSocketUrl: "ws://localhost:3000/api/trpc",
37
+ });
38
+ const server = setupServer(...handlers);
39
+
40
+ beforeAll(() => server.listen());
41
+ afterEach(() => reset());
42
+ afterAll(() => server.close());
43
+
44
+ test("reads a post", async () => {
45
+ trpc.post.byId.query(({ input }) => ({ id: input.id, title: "" }));
46
+ trpc.post.onAdd.subscription(async function* () {
47
+ yield { id: "", title: "" };
48
+ });
49
+ // ...drive your client
50
+ });
51
+ ```
52
+
53
+ ## <a name="documentation">📖 Documentation</a>
54
+
55
+ We highly recommend you take a look at the [documentation](https://esposter.com/docs/api/modules/trpc-msw.html) to level up. How it works and every upstream `msw-trpc` issue it answers are on the [trpc-msw docs page](https://esposter.com/docs/trpc-msw).
56
+
57
+ ### Key exports
58
+
59
+ | Export | Description |
60
+ | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------- |
61
+ | `createTRPCMsw` | The factory — returns the msw `handlers`, the typed `trpc` registration proxy and `reset` |
62
+ | `TRPCMswOptions` | `t`, `endpoint`, and optionally `webSocketUrl`, `createContext`, `allowMethodOverride` and `onUnhandledProcedure` |
63
+ | `UnhandledProcedureAction` | `Error` (default) answers an unregistered procedure with tRPC's `NOT_FOUND`; `Bypass` passes the request on to the next handler |
64
+
65
+ A resolver receives what a real one does — `ctx`, `input`, `path`, `signal` — and returns the procedure's output before the transformer, which runs on the way out as it does on the server. A thrown `TRPCError` reaches the client through your error formatter.
66
+
67
+ ### Commands
68
+
69
+ Run from `packages/trpc-msw/`:
70
+
71
+ ```bash
72
+ pnpm build # compile to dist/
73
+ pnpm test # vitest watch mode (coverage is run from the repo root)
74
+ pnpm lint:fix # auto-fix lint
75
+ pnpm typecheck # type check
76
+ ```
77
+
78
+ ## <a name="license">⚖️ License</a>
79
+
80
+ This project is licensed under the [Apache-2.0 license](https://github.com/Esposter/Esposter/blob/main/LICENSE).
81
+
82
+ [badge-license]: https://img.shields.io/github/license/Esposter/Esposter.svg?color=blue
83
+ [url-license]: https://github.com/Esposter/Esposter/blob/main/LICENSE
84
+ [badge-npm-version]: https://img.shields.io/npm/v/trpc-msw/latest?color=brightgreen
85
+ [url-npm]: https://www.npmjs.com/package/trpc-msw/v/latest
86
+ [badge-npm-unpacked-size]: https://img.shields.io/npm/unpacked-size/trpc-msw/latest?label=npm
87
+ [badge-npm-downloads]: https://img.shields.io/npm/dm/trpc-msw.svg
@@ -0,0 +1,134 @@
1
+ import { EventEmitter } from "node:events";
2
+ import { AnyTRPCProcedure, AnyTRPCRootTypes, AnyTRPCRouter, TRPCProcedureType, TRPCRootObject, TRPCRouterBuilder, TRPCRouterRecord, inferProcedureInput, inferProcedureOutput } from "@trpc/server";
3
+ import { FetchCreateContextFnOptions } from "@trpc/server/adapters/fetch";
4
+ import { CreateWSSContextFnOptions } from "@trpc/server/adapters/ws";
5
+ import { HttpHandler, WebSocketData, WebSocketHandler, WebSocketHandlerConnection } from "msw";
6
+ import { IncomingMessage } from "node:http";
7
+ //#region src/constants.d.ts
8
+ export declare const WEBSOCKET_ROUTER_REPLACED_CLOSE_CODE = 4e3;
9
+ //#endregion
10
+ //#region src/models/ProcedureResolverOptions.d.ts
11
+ export interface ProcedureResolverOptions<TContext, TInput> {
12
+ batchIndex?: number;
13
+ ctx: TContext;
14
+ input: TInput;
15
+ path: string;
16
+ signal?: AbortSignal;
17
+ }
18
+ //#endregion
19
+ //#region ../../node_modules/.pnpm/type-fest@5.10.0/node_modules/type-fest/source/promisable.d.ts
20
+ /**
21
+ Create a type that represents either the value or the value wrapped in `PromiseLike`.
22
+
23
+ Use-cases:
24
+ - A function accepts a callback that may either return a value synchronously or may return a promised value.
25
+ - This type could be the return type of `Promise#then()`, `Promise#catch()`, and `Promise#finally()` callbacks.
26
+
27
+ Please upvote [this issue](https://github.com/microsoft/TypeScript/issues/31394) if you want to have this type as a built-in in TypeScript.
28
+
29
+ @example
30
+ ```
31
+ import type {Promisable} from 'type-fest';
32
+
33
+ async function logger(getLogEntry: () => Promisable<string>): Promise<void> {
34
+ const entry = await getLogEntry();
35
+ console.log(entry);
36
+ }
37
+
38
+ await logger(() => 'foo');
39
+ await logger(() => Promise.resolve('bar'));
40
+ ```
41
+
42
+ @category Async
43
+ */
44
+ type Promisable<T> = T | PromiseLike<T>;
45
+ //#endregion
46
+ //#region src/models/ProcedureResolver.d.ts
47
+ export type ProcedureResolver<TContext, TProcedure extends AnyTRPCProcedure> = (options: ProcedureResolverOptions<TContext, inferProcedureInput<TProcedure>>) => Promisable<inferProcedureOutput<TProcedure>>;
48
+ //#endregion
49
+ //#region src/models/TRPCMswRouterRecord.d.ts
50
+ export type TRPCMswRouterRecord<TContext, TRecord extends TRPCRouterRecord> = { readonly [TKey in keyof TRecord]: TRecord[TKey] extends AnyTRPCProcedure ? Readonly<Record<TRecord[TKey]["_def"]["type"], (resolver: ProcedureResolver<TContext, TRecord[TKey]>) => void>> : TRecord[TKey] extends TRPCRouterRecord ? TRPCMswRouterRecord<TContext, TRecord[TKey]> : never; };
51
+ //#endregion
52
+ //#region src/models/TRPCMsw.d.ts
53
+ export interface TRPCMsw<TRouter extends AnyTRPCRouter, TContext> {
54
+ handlers: (HttpHandler | WebSocketHandler)[];
55
+ reset: () => void;
56
+ trpc: TRPCMswRouterRecord<TContext, TRouter["_def"]["record"]>;
57
+ }
58
+ //#endregion
59
+ //#region src/models/CreateContextOptions.d.ts
60
+ export type CreateContextOptions = CreateWSSContextFnOptions | FetchCreateContextFnOptions;
61
+ //#endregion
62
+ //#region src/models/TRPCMswRoot.d.ts
63
+ export interface TRPCMswRoot<TContext extends object> {
64
+ procedure: TRPCRootObject<TContext, object, object>["procedure"];
65
+ router: TRPCRouterBuilder<AnyTRPCRootTypes>;
66
+ }
67
+ //#endregion
68
+ //#region src/models/UnhandledProcedureAction.d.ts
69
+ export declare enum UnhandledProcedureAction {
70
+ Bypass = "Bypass",
71
+ Error = "Error"
72
+ }
73
+ //#endregion
74
+ //#region src/models/TRPCMswOptions.d.ts
75
+ export interface TRPCMswOptions<TContext extends object> {
76
+ allowMethodOverride?: boolean;
77
+ createContext?: (options: CreateContextOptions) => Promisable<TContext>;
78
+ endpoint: string;
79
+ onUnhandledProcedure?: UnhandledProcedureAction;
80
+ t: TRPCMswRoot<TContext>;
81
+ webSocketUrl?: string;
82
+ }
83
+ //#endregion
84
+ //#region src/createTRPCMsw.d.ts
85
+ export declare const createTRPCMsw: <TRouter extends AnyTRPCRouter, TContext extends object = object>({ allowMethodOverride, createContext, endpoint, onUnhandledProcedure, t, webSocketUrl }: TRPCMswOptions<TContext>) => TRPCMsw<TRouter, TContext>;
86
+ //#endregion
87
+ //#region src/models/MswWebSocketAdapter.d.ts
88
+ type MswWebSocketClient = WebSocketHandlerConnection["client"];
89
+ export declare class MswWebSocketAdapter extends EventEmitter {
90
+ #private;
91
+ readonly CLOSED: number;
92
+ readonly CLOSING: number;
93
+ readonly CONNECTING: number;
94
+ readonly OPEN: number;
95
+ readyState: number;
96
+ constructor(client: MswWebSocketClient);
97
+ close(code?: number, reason?: string): void;
98
+ send(data: string): void;
99
+ terminate(): void;
100
+ }
101
+ //#endregion
102
+ //#region src/models/SubscriptionRegistration.d.ts
103
+ export interface SubscriptionRegistration {
104
+ resolver: (options: ProcedureResolverOptions<unknown, unknown>) => Promisable<AsyncIterable<unknown>>;
105
+ type: "subscription";
106
+ }
107
+ //#endregion
108
+ //#region src/models/ProcedureRegistration.d.ts
109
+ export type ProcedureRegistration = SubscriptionRegistration | {
110
+ resolver: (options: ProcedureResolverOptions<unknown, unknown>) => unknown;
111
+ type: Exclude<TRPCProcedureType, "subscription">;
112
+ };
113
+ //#endregion
114
+ //#region src/models/WebSocketServerAdapter.d.ts
115
+ export declare class WebSocketServerAdapter<TClient extends EventEmitter> extends EventEmitter {
116
+ readonly clients: Set<TClient>;
117
+ addConnection(client: TClient, request: IncomingMessage): void;
118
+ }
119
+ //#endregion
120
+ //#region src/services/checkIsProcedureType.d.ts
121
+ export declare const checkIsProcedureType: (value: unknown) => value is TRPCProcedureType;
122
+ //#endregion
123
+ //#region src/services/createMockRouter.d.ts
124
+ export declare const createMockRouter: <TContext extends object>({ procedure: baseProcedure, router }: TRPCMswRoot<TContext>, procedureTypes: ReadonlyMap<string, TRPCProcedureType>, registrations: ReadonlyMap<string, ProcedureRegistration>) => AnyTRPCRouter;
125
+ //#endregion
126
+ //#region src/services/getProcedurePaths.d.ts
127
+ export declare const getProcedurePaths: (url: string, endpointPathname: string) => string[];
128
+ //#endregion
129
+ //#region src/services/toBuffer.d.ts
130
+ export declare const toBuffer: (data: WebSocketData) => Buffer;
131
+ //#endregion
132
+ //#region src/services/toResolverOptions.d.ts
133
+ export declare const toResolverOptions: ({ batchIndex, ctx, input, path, signal }: ProcedureResolverOptions<unknown, unknown>) => ProcedureResolverOptions<unknown, unknown>;
134
+ //#endregion
package/dist/index.js ADDED
@@ -0,0 +1,172 @@
1
+ import { EventEmitter } from "node:events";
2
+ import { exhaustiveGuard } from "@esposter/shared";
3
+ import { TRPCError, createTRPCRecursiveProxy } from "@trpc/server";
4
+ import { fetchRequestHandler } from "@trpc/server/adapters/fetch";
5
+ import { applyWSSHandler } from "@trpc/server/adapters/ws";
6
+ import { http, ws } from "msw";
7
+ import { IncomingMessage } from "node:http";
8
+ import { Socket } from "node:net";
9
+ //#region src/constants.ts
10
+ const WEBSOCKET_ROUTER_REPLACED_CLOSE_CODE = 4e3;
11
+ //#endregion
12
+ //#region src/services/toBuffer.ts
13
+ const toBuffer = (data) => {
14
+ if (typeof data === "string") return Buffer.from(data);
15
+ else if (ArrayBuffer.isView(data)) return Buffer.from(data.buffer, data.byteOffset, data.byteLength);
16
+ else if (data instanceof Blob) throw new TypeError("A WebSocket message sent as a Blob cannot be read in order");
17
+ return Buffer.from(data);
18
+ };
19
+ //#endregion
20
+ //#region src/models/MswWebSocketAdapter.ts
21
+ var MswWebSocketAdapter = class extends EventEmitter {
22
+ CLOSED = WebSocket.CLOSED;
23
+ CLOSING = WebSocket.CLOSING;
24
+ CONNECTING = WebSocket.CONNECTING;
25
+ OPEN = WebSocket.OPEN;
26
+ readyState = WebSocket.OPEN;
27
+ #client;
28
+ constructor(client) {
29
+ super();
30
+ this.#client = client;
31
+ client.addEventListener("message", (event) => {
32
+ this.emit("message", toBuffer(event.data), false);
33
+ });
34
+ client.addEventListener("close", (event) => {
35
+ this.readyState = WebSocket.CLOSED;
36
+ this.emit("close", event.code, event.reason);
37
+ });
38
+ }
39
+ close(code, reason) {
40
+ this.readyState = WebSocket.CLOSING;
41
+ this.#client.close(code, reason);
42
+ }
43
+ send(data) {
44
+ this.#client.send(data);
45
+ }
46
+ terminate() {
47
+ this.close();
48
+ }
49
+ };
50
+ //#endregion
51
+ //#region src/models/UnhandledProcedureAction.ts
52
+ let UnhandledProcedureAction = /* @__PURE__ */ function(UnhandledProcedureAction) {
53
+ UnhandledProcedureAction["Bypass"] = "Bypass";
54
+ UnhandledProcedureAction["Error"] = "Error";
55
+ return UnhandledProcedureAction;
56
+ }({});
57
+ //#endregion
58
+ //#region src/models/WebSocketServerAdapter.ts
59
+ var WebSocketServerAdapter = class extends EventEmitter {
60
+ clients = /* @__PURE__ */ new Set();
61
+ addConnection(client, request) {
62
+ this.clients.add(client);
63
+ client.once("close", () => {
64
+ this.clients.delete(client);
65
+ });
66
+ this.emit("connection", client, request);
67
+ }
68
+ };
69
+ //#endregion
70
+ //#region src/services/checkIsProcedureType.ts
71
+ const ProcedureTypes = /* @__PURE__ */ new Set([
72
+ "mutation",
73
+ "query",
74
+ "subscription"
75
+ ]);
76
+ const checkIsProcedureType = (value) => ProcedureTypes.has(value);
77
+ //#endregion
78
+ //#region src/services/toResolverOptions.ts
79
+ const toResolverOptions = ({ batchIndex, ctx, input, path, signal }) => ({
80
+ batchIndex,
81
+ ctx,
82
+ input,
83
+ path,
84
+ signal
85
+ });
86
+ //#endregion
87
+ //#region src/services/createMockRouter.ts
88
+ const createMockRouter = ({ procedure: baseProcedure, router }, procedureTypes, registrations) => router(Object.fromEntries(procedureTypes.entries().map(([path, type]) => {
89
+ const procedure = baseProcedure.input((value) => value);
90
+ const createNotFoundError = () => new TRPCError({
91
+ code: "NOT_FOUND",
92
+ message: `No "${type}"-procedure on path "${path}"`
93
+ });
94
+ switch (type) {
95
+ case "mutation":
96
+ case "query": return [path, procedure[type]((options) => {
97
+ const registration = registrations.get(path);
98
+ if (registration?.type !== type) throw createNotFoundError();
99
+ return registration.resolver(toResolverOptions(options));
100
+ })];
101
+ case "subscription": return [path, procedure.subscription(async function* (options) {
102
+ const registration = registrations.get(path);
103
+ if (registration?.type !== type) throw createNotFoundError();
104
+ yield* await registration.resolver(toResolverOptions(options));
105
+ })];
106
+ default: return exhaustiveGuard(type);
107
+ }
108
+ })));
109
+ //#endregion
110
+ //#region src/services/getProcedurePaths.ts
111
+ const getProcedurePaths = (url, endpointPathname) => decodeURIComponent(new URL(url).pathname.slice(endpointPathname.length + 1)).split(",");
112
+ //#endregion
113
+ //#region src/createTRPCMsw.ts
114
+ const createTRPCMsw = ({ allowMethodOverride, createContext, endpoint, onUnhandledProcedure = "Error", t, webSocketUrl }) => {
115
+ const registrations = /* @__PURE__ */ new Map();
116
+ const procedureTypes = /* @__PURE__ */ new Map();
117
+ const endpointPathname = new URL(endpoint, "http://localhost").pathname;
118
+ const handlers = [http.all(`${endpoint}/*`, ({ request }) => {
119
+ if (onUnhandledProcedure === "Bypass" && !getProcedurePaths(request.url, endpointPathname).some((path) => registrations.has(path))) return void 0;
120
+ return fetchRequestHandler({
121
+ allowMethodOverride,
122
+ createContext,
123
+ endpoint: endpointPathname,
124
+ req: request,
125
+ router: createMockRouter(t, procedureTypes, registrations)
126
+ });
127
+ })];
128
+ const createWebSocketServer = () => {
129
+ const webSocketServer = new WebSocketServerAdapter();
130
+ applyWSSHandler({
131
+ createContext,
132
+ router: createMockRouter(t, new Map(procedureTypes), registrations),
133
+ wss: webSocketServer
134
+ });
135
+ return webSocketServer;
136
+ };
137
+ let webSocketServer;
138
+ if (webSocketUrl) handlers.push(ws.link(webSocketUrl).addEventListener("connection", (connection) => {
139
+ const { client } = connection;
140
+ const request = new IncomingMessage(new Socket());
141
+ request.url = `${client.url.pathname}${client.url.search}`;
142
+ webSocketServer ??= createWebSocketServer();
143
+ webSocketServer.addConnection(new MswWebSocketAdapter(client), request);
144
+ }));
145
+ const register = (path, registration) => {
146
+ registrations.set(path, registration);
147
+ if (procedureTypes.get(path) === registration.type) return;
148
+ procedureTypes.set(path, registration.type);
149
+ if (!webSocketServer) return;
150
+ for (const client of webSocketServer.clients) client.close(WEBSOCKET_ROUTER_REPLACED_CLOSE_CODE);
151
+ webSocketServer = void 0;
152
+ };
153
+ return {
154
+ handlers,
155
+ reset: () => {
156
+ registrations.clear();
157
+ },
158
+ trpc: createTRPCRecursiveProxy(({ args: [resolver], path }) => {
159
+ const type = path.at(-1);
160
+ if (!checkIsProcedureType(type) || typeof resolver !== "function") throw new TypeError(`Expected a resolver registered with query, mutation or subscription at "${path.join(".")}"`);
161
+ register(path.slice(0, -1).join("."), type === "subscription" ? {
162
+ resolver,
163
+ type
164
+ } : {
165
+ resolver,
166
+ type
167
+ });
168
+ })
169
+ };
170
+ };
171
+ //#endregion
172
+ export { MswWebSocketAdapter, UnhandledProcedureAction, WEBSOCKET_ROUTER_REPLACED_CLOSE_CODE, WebSocketServerAdapter, checkIsProcedureType, createMockRouter, createTRPCMsw, getProcedurePaths, toBuffer, toResolverOptions };
package/package.json ADDED
@@ -0,0 +1,74 @@
1
+ {
2
+ "name": "trpc-msw",
3
+ "version": "3.6.0",
4
+ "description": "tRPC for Mock Service Worker — answers queries, mutations and subscriptions over HTTP, batching, SSE and WebSockets with tRPC's own handlers, typed off your router.",
5
+ "keywords": [
6
+ "batch",
7
+ "mock",
8
+ "msw",
9
+ "sse",
10
+ "subscriptions",
11
+ "testing",
12
+ "trpc",
13
+ "typescript",
14
+ "websocket"
15
+ ],
16
+ "homepage": "https://github.com/Esposter/Esposter/blob/main/packages/trpc-msw#readme",
17
+ "bugs": {
18
+ "url": "https://github.com/Esposter/Esposter/issues"
19
+ },
20
+ "license": "Apache-2.0",
21
+ "author": "Jimmy Chen",
22
+ "repository": {
23
+ "type": "git",
24
+ "url": "git+https://github.com/Esposter/Esposter.git"
25
+ },
26
+ "files": [
27
+ "dist"
28
+ ],
29
+ "type": "module",
30
+ "sideEffects": false,
31
+ "types": "dist/index.d.ts",
32
+ "imports": {
33
+ "#src/*": "./src/*.ts"
34
+ },
35
+ "exports": {
36
+ ".": "./dist/index.js",
37
+ "./package.json": "./package.json"
38
+ },
39
+ "publishConfig": {
40
+ "access": "public"
41
+ },
42
+ "scripts": {
43
+ "build": "tsdown",
44
+ "format": "oxfmt",
45
+ "format:check": "oxfmt --check",
46
+ "lint": "eslint .",
47
+ "lint:fix": "eslint --fix .",
48
+ "test": "vitest",
49
+ "typecheck": "tsc"
50
+ },
51
+ "dependencies": {
52
+ "@esposter/shared": "3.6.0"
53
+ },
54
+ "devDependencies": {
55
+ "@arethetypeswrong/core": "^0.18.5",
56
+ "@esposter/configuration": "3.6.0",
57
+ "@trpc/client": "^11.19.0",
58
+ "@types/node": "^26.6.3",
59
+ "publint": "^0.3.24",
60
+ "superjson": "^2.2.6",
61
+ "tsdown": "^0.23.0",
62
+ "type-fest": "^5.10.0",
63
+ "vitest": "^5.0.2",
64
+ "zod": "^4.6.5"
65
+ },
66
+ "peerDependencies": {
67
+ "@trpc/server": "^11.19.0",
68
+ "msw": "^3.0.0"
69
+ },
70
+ "inlinedDependencies": {
71
+ "type-fest": "5.10.0"
72
+ },
73
+ "gitHead": "07f63a48503626e6f02f64e778a2e8e4838b55e2"
74
+ }