trpc-msw 4.4.0 → 4.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/README.md CHANGED
@@ -5,7 +5,7 @@
5
5
  [![NPM downloads][badge-npm-downloads]][url-npm]
6
6
  [![NPM Unpacked Size (with version)][badge-npm-unpacked-size]][url-npm]
7
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.
8
+ This package connects tRPC to [Mock Service Worker](https://mswjs.io), and tRPC's own handlers answer every client call at the network level. You register a resolver for each procedure, typed from your router.
9
9
 
10
10
  Design notes live in [the specs](https://github.com/Esposter/Esposter/tree/main/openspec/specs/trpc-msw).
11
11
 
@@ -19,10 +19,14 @@ Design notes live in [the specs](https://github.com/Esposter/Esposter/tree/main/
19
19
 
20
20
  ## <a name="getting-started">🚀 Getting Started</a>
21
21
 
22
+ 1. Install the packages.
23
+
22
24
  ```bash
23
25
  pnpm i -D trpc-msw msw @trpc/server
24
26
  ```
25
27
 
28
+ 2. Create a test file from this code. The client receives each answer from its resolver.
29
+
26
30
  ```ts
27
31
  import type { AppRouter } from "./server/router";
28
32
 
@@ -52,17 +56,24 @@ test("reads a post", async () => {
52
56
  });
53
57
  ```
54
58
 
55
- The result is that 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.
59
+ Batching, your transformer, your error formatter, `FormData` input and subscriptions over server-sent events or WebSockets behave exactly as they do against the real server.
56
60
 
57
61
  ## <a name="key-exports">🧩 Key Exports</a>
58
62
 
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 `allowMethodOverride`, `createContext`, `onUnhandledProcedure`, `router` and `webSocketUrl` |
63
- | `UnhandledProcedureAction` | `Error` (default) answers an unregistered procedure with tRPC's `NOT_FOUND`; `Bypass` passes the request on to the next handler |
63
+ | Export | Description |
64
+ | -------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
65
+ | `createTRPCMsw` | The factory. It returns the msw `handlers`, the typed `trpc` registration proxy and `reset`. |
66
+ | `TRPCMswOptions` | The options object. Required: `t` and `endpoint`. Optional: `allowMethodOverride`, `createContext`, `onUnhandledProcedure`, `router` and `webSocketUrl`. |
67
+ | `UnhandledProcedureAction` | `Error` (default) answers an unregistered procedure with tRPC's `NOT_FOUND`. `Bypass` passes the request to the next handler. |
68
+
69
+ Pass your real `router` to check each call against its procedure's input parsers before the resolver runs.
64
70
 
65
- Pass your real `router` and every call is first judged by that procedure's own input parsers (Standard Schema validators, or plain functions), so a client sending what your server would reject gets the same `BAD_REQUEST` instead of a mocked answer; the resolver receives what those parsers return, as it does on the server. 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.
71
+ - The parsers are Standard Schema validators or plain functions.
72
+ - A call with input that your server would reject gets the same `BAD_REQUEST`, not a mocked answer.
73
+ - The resolver receives the values that the parsers return, as it does on the server.
74
+ - A resolver receives `ctx`, `input`, `path` and `signal`, as a real resolver does.
75
+ - A resolver returns the procedure's output before the transformer. The transformer runs on the way out, as it does on the server.
76
+ - A thrown `TRPCError` reaches the client through your error formatter.
66
77
 
67
78
  ## <a name="license">⚖️ License</a>
68
79
 
@@ -0,0 +1,97 @@
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
+ export declare const WEBSOCKET_ROUTER_REPLACED_CLOSE_CODE = 4e3;
7
+ export interface ProcedureResolverOptions<TContext, TInput> {
8
+ batchIndex?: number;
9
+ ctx: TContext;
10
+ input: TInput;
11
+ path: string;
12
+ signal?: AbortSignal;
13
+ }
14
+ /**
15
+ Create a type that represents either the value or the value wrapped in `PromiseLike`.
16
+
17
+ Use-cases:
18
+ - A function accepts a callback that may either return a value synchronously or may return a promised value.
19
+ - This type could be the return type of `Promise#then()`, `Promise#catch()`, and `Promise#finally()` callbacks.
20
+
21
+ Please upvote [this issue](https://github.com/microsoft/TypeScript/issues/31394) if you want to have this type as a built-in in TypeScript.
22
+
23
+ @example
24
+ ```
25
+ import type {Promisable} from 'type-fest';
26
+
27
+ async function logger(getLogEntry: () => Promisable<string>): Promise<void> {
28
+ const entry = await getLogEntry();
29
+ console.log(entry);
30
+ }
31
+
32
+ await logger(() => 'foo');
33
+ await logger(() => Promise.resolve('bar'));
34
+ ```
35
+
36
+ @category Async
37
+ */
38
+ type Promisable<T> = T | PromiseLike<T>;
39
+ export type ProcedureResolver<TContext, TProcedure extends AnyTRPCProcedure> = (options: ProcedureResolverOptions<TContext, inferProcedureInput<TProcedure>>) => Promisable<inferProcedureOutput<TProcedure>>;
40
+ 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; };
41
+ export interface TRPCMsw<TRouter extends AnyTRPCRouter, TContext> {
42
+ handlers: (HttpHandler | WebSocketHandler)[];
43
+ reset: () => void;
44
+ trpc: TRPCMswRouterRecord<TContext, TRouter["_def"]["record"]>;
45
+ }
46
+ export type CreateContextOptions = CreateWSSContextFnOptions | FetchCreateContextFnOptions;
47
+ export interface TRPCMswRoot<TContext extends object> {
48
+ procedure: TRPCRootObject<TContext, object, object>["procedure"];
49
+ router: TRPCRouterBuilder<AnyTRPCRootTypes>;
50
+ }
51
+ export declare enum UnhandledProcedureAction {
52
+ Bypass = "Bypass",
53
+ Error = "Error"
54
+ }
55
+ export interface TRPCMswOptions<TContext extends object> {
56
+ allowMethodOverride?: boolean;
57
+ createContext?: (options: CreateContextOptions) => Promisable<TContext>;
58
+ endpoint: string;
59
+ onUnhandledProcedure?: UnhandledProcedureAction;
60
+ router?: AnyTRPCRouter;
61
+ t: TRPCMswRoot<TContext>;
62
+ webSocketUrl?: string;
63
+ }
64
+ export declare const createTRPCMsw: <TRouter extends AnyTRPCRouter, TContext extends object = object>({ allowMethodOverride, createContext, endpoint, onUnhandledProcedure, router, t, webSocketUrl }: TRPCMswOptions<TContext>) => TRPCMsw<TRouter, TContext>;
65
+ declare class WebSocketClientAdapter extends EventEmitter {
66
+ readonly close: (code?: number, reason?: string) => void;
67
+ readonly CLOSED: number;
68
+ readonly CLOSING: number;
69
+ readonly CONNECTING: number;
70
+ readonly OPEN: number;
71
+ readyState: number;
72
+ readonly send: (data: string) => void;
73
+ readonly terminate: () => void;
74
+ constructor(transport: {
75
+ close: (code?: number, reason?: string) => void;
76
+ send: (data: string) => void;
77
+ terminate: () => void;
78
+ });
79
+ }
80
+ type MswWebSocketClient = WebSocketHandlerConnection["client"];
81
+ export declare class MswWebSocketAdapter extends WebSocketClientAdapter {
82
+ constructor(client: MswWebSocketClient);
83
+ }
84
+ export interface SubscriptionRegistration {
85
+ resolver: (options: ProcedureResolverOptions<unknown, unknown>) => Promisable<AsyncIterable<unknown>>;
86
+ type: "subscription";
87
+ }
88
+ export type ProcedureRegistration = SubscriptionRegistration | {
89
+ resolver: (options: ProcedureResolverOptions<unknown, unknown>) => unknown;
90
+ type: Exclude<TRPCProcedureType, "subscription">;
91
+ };
92
+ export declare const checkIsProcedureType: (value: unknown) => value is TRPCProcedureType;
93
+ export declare const createMockRouter: <TContext extends object>({ procedure: baseProcedure, router }: TRPCMswRoot<TContext>, procedureTypes: ReadonlyMap<string, TRPCProcedureType>, registrations: ReadonlyMap<string, ProcedureRegistration>, inputRouter?: AnyTRPCRouter) => AnyTRPCRouter;
94
+ export declare const getProcedurePaths: (url: string, endpointPathname: string) => string[];
95
+ export declare const toBuffer: (data: WebSocketData) => Buffer;
96
+ export declare const toResolverOptions: ({ batchIndex, ctx, input, path, signal }: ProcedureResolverOptions<unknown, unknown>) => ProcedureResolverOptions<unknown, unknown>;
97
+ export {};
package/dist/index.js ADDED
@@ -0,0 +1,185 @@
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
+ // src/constants.ts
10
+ const WEBSOCKET_ROUTER_REPLACED_CLOSE_CODE = 4e3;
11
+ // src/services/toBuffer.ts
12
+ const toBuffer = (data) => {
13
+ if (typeof data === "string") return Buffer.from(data);
14
+ else if (ArrayBuffer.isView(data)) return Buffer.from(data.buffer, data.byteOffset, data.byteLength);
15
+ else if (data instanceof Blob) throw new TypeError("A WebSocket message sent as a Blob cannot be read in order");
16
+ else return Buffer.from(data);
17
+ };
18
+ // ../trpc-nuxt-module/dist/runtime/server/models/WebSocketClientAdapter.js
19
+ var WebSocketClientAdapter = class extends EventEmitter {
20
+ close;
21
+ CLOSED = WebSocket.CLOSED;
22
+ CLOSING = WebSocket.CLOSING;
23
+ CONNECTING = WebSocket.CONNECTING;
24
+ OPEN = WebSocket.OPEN;
25
+ readyState = WebSocket.OPEN;
26
+ send;
27
+ terminate;
28
+ constructor(transport) {
29
+ super();
30
+ this.close = (code, reason) => {
31
+ this.readyState = WebSocket.CLOSING;
32
+ transport.close(code, reason);
33
+ };
34
+ this.send = (data) => {
35
+ transport.send(data);
36
+ };
37
+ this.terminate = () => {
38
+ this.readyState = WebSocket.CLOSING;
39
+ transport.terminate();
40
+ };
41
+ }
42
+ };
43
+ // src/models/MswWebSocketAdapter.ts
44
+ var MswWebSocketAdapter = class extends WebSocketClientAdapter {
45
+ constructor(client) {
46
+ super({
47
+ close: (code, reason) => {
48
+ client.close(code, reason);
49
+ },
50
+ send: (data) => {
51
+ client.send(data);
52
+ },
53
+ terminate: () => {
54
+ client.close();
55
+ }
56
+ });
57
+ client.addEventListener("message", (event) => {
58
+ this.emit("message", toBuffer(event.data), false);
59
+ });
60
+ client.addEventListener("close", (event) => {
61
+ this.readyState = WebSocket.CLOSED;
62
+ this.emit("close", event.code, event.reason);
63
+ });
64
+ }
65
+ };
66
+ // src/models/UnhandledProcedureAction.ts
67
+ let UnhandledProcedureAction = /* @__PURE__ */ function(UnhandledProcedureAction) {
68
+ UnhandledProcedureAction["Bypass"] = "Bypass";
69
+ UnhandledProcedureAction["Error"] = "Error";
70
+ return UnhandledProcedureAction;
71
+ }({});
72
+ // src/services/checkIsProcedureType.ts
73
+ const PROCEDURE_TYPES = /* @__PURE__ */ new Set([
74
+ "mutation",
75
+ "query",
76
+ "subscription"
77
+ ]);
78
+ const checkIsProcedureType = (value) => PROCEDURE_TYPES.has(value);
79
+ // src/services/toResolverOptions.ts
80
+ const toResolverOptions = ({ batchIndex, ctx, input, path, signal }) => ({
81
+ batchIndex,
82
+ ctx,
83
+ input,
84
+ path,
85
+ signal
86
+ });
87
+ // src/services/createMockRouter.ts
88
+ const createMockRouter = ({ procedure: baseProcedure, router }, procedureTypes, registrations, inputRouter) => router(Object.fromEntries(procedureTypes.entries().map(([path, type]) => {
89
+ const procedure = (inputRouter?._def.procedures[path]?._def.inputs ?? []).reduce((builder, parser) => builder.input(parser), baseProcedure);
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) return registration.resolver(toResolverOptions(options));
99
+ else throw createNotFoundError();
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
+ // src/services/getProcedurePaths.ts
110
+ const getProcedurePaths = (url, endpointPathname) => decodeURIComponent(new URL(url).pathname.slice(endpointPathname.length + 1)).split(",");
111
+ // ../trpc-nuxt-module/dist/runtime/server/models/WebSocketServerAdapter.js
112
+ var WebSocketServerAdapter = class extends EventEmitter {
113
+ clients = /* @__PURE__ */ new Set();
114
+ constructor() {
115
+ super();
116
+ this.on("connection", (client) => {
117
+ this.clients.add(client);
118
+ client.once("close", () => {
119
+ this.clients.delete(client);
120
+ });
121
+ });
122
+ }
123
+ };
124
+ // src/createTRPCMsw.ts
125
+ const createTRPCMsw = ({ allowMethodOverride, createContext, endpoint, onUnhandledProcedure = "Error", router, t, webSocketUrl }) => {
126
+ const registrations = /* @__PURE__ */ new Map();
127
+ const procedureTypes = /* @__PURE__ */ new Map();
128
+ const endpointPathname = new URL(endpoint, "http://localhost").pathname;
129
+ let httpRouter;
130
+ const handlers = [http.all(`${endpoint}/*`, ({ request }) => {
131
+ if (onUnhandledProcedure === "Bypass" && !getProcedurePaths(request.url, endpointPathname).some((path) => registrations.has(path))) return void 0;
132
+ httpRouter ??= createMockRouter(t, procedureTypes, registrations, router);
133
+ return fetchRequestHandler({
134
+ allowMethodOverride,
135
+ createContext,
136
+ endpoint: endpointPathname,
137
+ req: request,
138
+ router: httpRouter
139
+ });
140
+ })];
141
+ const createWebSocketServer = () => {
142
+ const webSocketServer = new WebSocketServerAdapter();
143
+ applyWSSHandler({
144
+ createContext,
145
+ router: createMockRouter(t, new Map(procedureTypes), registrations, router),
146
+ wss: webSocketServer
147
+ });
148
+ return webSocketServer;
149
+ };
150
+ let webSocketServer;
151
+ if (webSocketUrl) handlers.push(ws.link(webSocketUrl).addEventListener("connection", (connection) => {
152
+ const { client } = connection;
153
+ const request = new IncomingMessage(new Socket());
154
+ request.url = `${client.url.pathname}${client.url.search}`;
155
+ webSocketServer ??= createWebSocketServer();
156
+ webSocketServer.emit("connection", new MswWebSocketAdapter(client), request);
157
+ }));
158
+ const register = (path, registration) => {
159
+ registrations.set(path, registration);
160
+ if (procedureTypes.get(path) === registration.type) return;
161
+ procedureTypes.set(path, registration.type);
162
+ httpRouter = void 0;
163
+ if (!webSocketServer) return;
164
+ for (const client of webSocketServer.clients) client.close(WEBSOCKET_ROUTER_REPLACED_CLOSE_CODE);
165
+ webSocketServer = void 0;
166
+ };
167
+ return {
168
+ handlers,
169
+ reset: () => {
170
+ registrations.clear();
171
+ },
172
+ trpc: createTRPCRecursiveProxy(({ args: [resolver], path }) => {
173
+ const type = path.at(-1);
174
+ if (!checkIsProcedureType(type) || typeof resolver !== "function") throw new TypeError(`Expected a resolver registered with query, mutation or subscription at "${path.join(".")}"`);
175
+ register(path.slice(0, -1).join("."), type === "subscription" ? {
176
+ resolver,
177
+ type
178
+ } : {
179
+ resolver,
180
+ type
181
+ });
182
+ })
183
+ };
184
+ };
185
+ export { MswWebSocketAdapter, UnhandledProcedureAction, WEBSOCKET_ROUTER_REPLACED_CLOSE_CODE, checkIsProcedureType, createMockRouter, createTRPCMsw, getProcedurePaths, toBuffer, toResolverOptions };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "trpc-msw",
3
- "version": "4.4.0",
3
+ "version": "4.6.0",
4
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
5
  "keywords": [
6
6
  "batch",
@@ -47,25 +47,25 @@
47
47
  "typecheck": "tsrs --fast"
48
48
  },
49
49
  "dependencies": {
50
- "@esposter/shared": "4.4.0"
50
+ "@esposter/shared": "4.6.0"
51
51
  },
52
52
  "devDependencies": {
53
- "@esposter/configuration": "4.4.0",
53
+ "@esposter/configuration": "4.6.0",
54
54
  "@standard-schema/spec": "^1.1.0",
55
- "@trpc/client": "^11.22.1",
55
+ "@trpc/client": "^11.25.0",
56
56
  "@types/node": "^26.6.6",
57
57
  "superjson": "^2.2.6",
58
- "trpc-nuxt-module": "4.4.0",
59
- "tsdown": "0.23.2",
58
+ "trpc-nuxt-module": "4.6.0",
59
+ "tsdown": "^0.23.7",
60
60
  "type-fest": "^5.10.0",
61
61
  "zod": "^4.6.7"
62
62
  },
63
63
  "peerDependencies": {
64
- "@trpc/server": "^11.22.1",
65
- "msw": "^3.0.3"
64
+ "@trpc/server": "^11.25.0",
65
+ "msw": "^3.0.4"
66
66
  },
67
67
  "inlinedDependencies": {
68
68
  "type-fest": "5.10.0"
69
69
  },
70
- "gitHead": "e1a416c4b91da69cc2aa259b50a4d656f204d272"
70
+ "gitHead": "0ceea3ffbe12ca69413ea5db2d3cfad197a63cba"
71
71
  }