trpc-msw 4.6.0 → 4.8.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.
Files changed (34) hide show
  1. package/dist/constants.d.ts +1 -0
  2. package/dist/constants.js +3 -0
  3. package/dist/createTRPCMsw.d.ts +4 -0
  4. package/dist/createTRPCMsw.js +75 -0
  5. package/dist/index.d.ts +19 -97
  6. package/dist/index.js +9 -184
  7. package/dist/models/CreateContextOptions.d.ts +3 -0
  8. package/dist/models/MswWebSocketAdapter.d.ts +7 -0
  9. package/dist/models/MswWebSocketAdapter.js +26 -0
  10. package/dist/models/ProcedureRegistration.d.ts +7 -0
  11. package/dist/models/ProcedureResolver.d.ts +4 -0
  12. package/dist/models/ProcedureResolverOptions.d.ts +7 -0
  13. package/dist/models/SubscriptionRegistration.d.ts +6 -0
  14. package/dist/models/TRPCMsw.d.ts +8 -0
  15. package/dist/models/TRPCMswOptions.d.ts +14 -0
  16. package/dist/models/TRPCMswRoot.d.ts +5 -0
  17. package/dist/models/TRPCMswRouterRecord.d.ts +3 -0
  18. package/dist/models/UnhandledProcedureAction.d.ts +4 -0
  19. package/dist/models/UnhandledProcedureAction.js +7 -0
  20. package/dist/packages/trpc-nuxt-module/dist/runtime/server/models/WebSocketClientAdapter.d.ts +16 -0
  21. package/dist/packages/trpc-nuxt-module/dist/runtime/server/models/WebSocketClientAdapter.js +27 -0
  22. package/dist/packages/trpc-nuxt-module/dist/runtime/server/models/WebSocketServerAdapter.js +15 -0
  23. package/dist/services/checkIsProcedureType.d.ts +2 -0
  24. package/dist/services/checkIsProcedureType.js +8 -0
  25. package/dist/services/createMockRouter.d.ts +4 -0
  26. package/dist/services/createMockRouter.js +26 -0
  27. package/dist/services/getProcedurePaths.d.ts +1 -0
  28. package/dist/services/getProcedurePaths.js +3 -0
  29. package/dist/services/toBuffer.d.ts +2 -0
  30. package/dist/services/toBuffer.js +8 -0
  31. package/dist/services/toResolverOptions.d.ts +2 -0
  32. package/dist/services/toResolverOptions.js +9 -0
  33. package/dist/vendor/pnpm/type-fest@5.10.0/vendor/type-fest/source/promisable.d.ts +25 -0
  34. package/package.json +7 -7
@@ -0,0 +1 @@
1
+ export declare const WEBSOCKET_ROUTER_REPLACED_CLOSE_CODE = 4e3;
@@ -0,0 +1,3 @@
1
+ // src/constants.ts
2
+ const WEBSOCKET_ROUTER_REPLACED_CLOSE_CODE = 4e3;
3
+ export { WEBSOCKET_ROUTER_REPLACED_CLOSE_CODE };
@@ -0,0 +1,4 @@
1
+ import { TRPCMsw } from "./models/TRPCMsw.js";
2
+ import { TRPCMswOptions } from "./models/TRPCMswOptions.js";
3
+ import { AnyTRPCRouter } from "@trpc/server";
4
+ export declare const createTRPCMsw: <TRouter extends AnyTRPCRouter, TContext extends object = object>({ allowMethodOverride, createContext, endpoint, onUnhandledProcedure, router, t, webSocketUrl }: TRPCMswOptions<TContext>) => TRPCMsw<TRouter, TContext>;
@@ -0,0 +1,75 @@
1
+ import { WEBSOCKET_ROUTER_REPLACED_CLOSE_CODE } from "./constants.js";
2
+ import { MswWebSocketAdapter } from "./models/MswWebSocketAdapter.js";
3
+ import "./models/UnhandledProcedureAction.js";
4
+ import { checkIsProcedureType } from "./services/checkIsProcedureType.js";
5
+ import { createMockRouter } from "./services/createMockRouter.js";
6
+ import { getProcedurePaths } from "./services/getProcedurePaths.js";
7
+ import { WebSocketServerAdapter } from "./packages/trpc-nuxt-module/dist/runtime/server/models/WebSocketServerAdapter.js";
8
+ import { createTRPCRecursiveProxy } from "@trpc/server";
9
+ import { fetchRequestHandler } from "@trpc/server/adapters/fetch";
10
+ import { applyWSSHandler } from "@trpc/server/adapters/ws";
11
+ import { http, ws } from "msw";
12
+ import { IncomingMessage } from "node:http";
13
+ import { Socket } from "node:net";
14
+ // src/createTRPCMsw.ts
15
+ const createTRPCMsw = ({ allowMethodOverride, createContext, endpoint, onUnhandledProcedure = "Error", router, t, webSocketUrl }) => {
16
+ const registrations = /* @__PURE__ */ new Map();
17
+ const procedureTypes = /* @__PURE__ */ new Map();
18
+ const endpointPathname = new URL(endpoint, "http://localhost").pathname;
19
+ let httpRouter;
20
+ const handlers = [http.all(`${endpoint}/*`, ({ request }) => {
21
+ if (onUnhandledProcedure === "Bypass" && !getProcedurePaths(request.url, endpointPathname).some((path) => registrations.has(path))) return void 0;
22
+ httpRouter ??= createMockRouter(t, procedureTypes, registrations, router);
23
+ return fetchRequestHandler({
24
+ allowMethodOverride,
25
+ createContext,
26
+ endpoint: endpointPathname,
27
+ req: request,
28
+ router: httpRouter
29
+ });
30
+ })];
31
+ const createWebSocketServer = () => {
32
+ const webSocketServer = new WebSocketServerAdapter();
33
+ applyWSSHandler({
34
+ createContext,
35
+ router: createMockRouter(t, new Map(procedureTypes), registrations, router),
36
+ wss: webSocketServer
37
+ });
38
+ return webSocketServer;
39
+ };
40
+ let webSocketServer;
41
+ if (webSocketUrl) handlers.push(ws.link(webSocketUrl).addEventListener("connection", (connection) => {
42
+ const { client } = connection;
43
+ const request = new IncomingMessage(new Socket());
44
+ request.url = `${client.url.pathname}${client.url.search}`;
45
+ webSocketServer ??= createWebSocketServer();
46
+ webSocketServer.emit("connection", new MswWebSocketAdapter(client), request);
47
+ }));
48
+ const register = (path, registration) => {
49
+ registrations.set(path, registration);
50
+ if (procedureTypes.get(path) === registration.type) return;
51
+ procedureTypes.set(path, registration.type);
52
+ httpRouter = void 0;
53
+ if (!webSocketServer) return;
54
+ for (const client of webSocketServer.clients) client.close(WEBSOCKET_ROUTER_REPLACED_CLOSE_CODE);
55
+ webSocketServer = void 0;
56
+ };
57
+ return {
58
+ handlers,
59
+ reset: () => {
60
+ registrations.clear();
61
+ },
62
+ trpc: createTRPCRecursiveProxy(({ args: [resolver], path }) => {
63
+ const type = path.at(-1);
64
+ if (!checkIsProcedureType(type) || typeof resolver !== "function") throw new TypeError(`Expected a resolver registered with query, mutation or subscription at "${path.join(".")}"`);
65
+ register(path.slice(0, -1).join("."), type === "subscription" ? {
66
+ resolver,
67
+ type
68
+ } : {
69
+ resolver,
70
+ type
71
+ });
72
+ })
73
+ };
74
+ };
75
+ export { createTRPCMsw };
package/dist/index.d.ts CHANGED
@@ -1,97 +1,19 @@
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 {};
1
+ import { WEBSOCKET_ROUTER_REPLACED_CLOSE_CODE } from "./constants.js";
2
+ import { createTRPCMsw } from "./createTRPCMsw.js";
3
+ import { CreateContextOptions } from "./models/CreateContextOptions.js";
4
+ import { MswWebSocketAdapter } from "./models/MswWebSocketAdapter.js";
5
+ import { ProcedureRegistration } from "./models/ProcedureRegistration.js";
6
+ import { ProcedureResolver } from "./models/ProcedureResolver.js";
7
+ import { ProcedureResolverOptions } from "./models/ProcedureResolverOptions.js";
8
+ import { SubscriptionRegistration } from "./models/SubscriptionRegistration.js";
9
+ import { TRPCMsw } from "./models/TRPCMsw.js";
10
+ import { TRPCMswOptions } from "./models/TRPCMswOptions.js";
11
+ import { TRPCMswRoot } from "./models/TRPCMswRoot.js";
12
+ import { TRPCMswRouterRecord } from "./models/TRPCMswRouterRecord.js";
13
+ import { UnhandledProcedureAction } from "./models/UnhandledProcedureAction.js";
14
+ import { checkIsProcedureType } from "./services/checkIsProcedureType.js";
15
+ import { createMockRouter } from "./services/createMockRouter.js";
16
+ import { getProcedurePaths } from "./services/getProcedurePaths.js";
17
+ import { toBuffer } from "./services/toBuffer.js";
18
+ import { toResolverOptions } from "./services/toResolverOptions.js";
19
+ export { CreateContextOptions, MswWebSocketAdapter, ProcedureRegistration, ProcedureResolver, ProcedureResolverOptions, SubscriptionRegistration, TRPCMsw, TRPCMswOptions, TRPCMswRoot, TRPCMswRouterRecord, UnhandledProcedureAction, WEBSOCKET_ROUTER_REPLACED_CLOSE_CODE, checkIsProcedureType, createMockRouter, createTRPCMsw, getProcedurePaths, toBuffer, toResolverOptions };
package/dist/index.js CHANGED
@@ -1,185 +1,10 @@
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
- };
1
+ import { WEBSOCKET_ROUTER_REPLACED_CLOSE_CODE } from "./constants.js";
2
+ import { createTRPCMsw } from "./createTRPCMsw.js";
3
+ import { MswWebSocketAdapter } from "./models/MswWebSocketAdapter.js";
4
+ import { UnhandledProcedureAction } from "./models/UnhandledProcedureAction.js";
5
+ import { checkIsProcedureType } from "./services/checkIsProcedureType.js";
6
+ import { createMockRouter } from "./services/createMockRouter.js";
7
+ import { getProcedurePaths } from "./services/getProcedurePaths.js";
8
+ import { toBuffer } from "./services/toBuffer.js";
9
+ import { toResolverOptions } from "./services/toResolverOptions.js";
185
10
  export { MswWebSocketAdapter, UnhandledProcedureAction, WEBSOCKET_ROUTER_REPLACED_CLOSE_CODE, checkIsProcedureType, createMockRouter, createTRPCMsw, getProcedurePaths, toBuffer, toResolverOptions };
@@ -0,0 +1,3 @@
1
+ import { FetchCreateContextFnOptions } from "@trpc/server/adapters/fetch";
2
+ import { CreateWSSContextFnOptions } from "@trpc/server/adapters/ws";
3
+ export type CreateContextOptions = CreateWSSContextFnOptions | FetchCreateContextFnOptions;
@@ -0,0 +1,7 @@
1
+ import { WebSocketClientAdapter } from "../packages/trpc-nuxt-module/dist/runtime/server/models/WebSocketClientAdapter.js";
2
+ import { WebSocketHandlerConnection } from "msw";
3
+ type MswWebSocketClient = WebSocketHandlerConnection["client"];
4
+ export declare class MswWebSocketAdapter extends WebSocketClientAdapter {
5
+ constructor(client: MswWebSocketClient);
6
+ }
7
+ export {};
@@ -0,0 +1,26 @@
1
+ import { toBuffer } from "../services/toBuffer.js";
2
+ import { WebSocketClientAdapter } from "../packages/trpc-nuxt-module/dist/runtime/server/models/WebSocketClientAdapter.js";
3
+ // src/models/MswWebSocketAdapter.ts
4
+ var MswWebSocketAdapter = class extends WebSocketClientAdapter {
5
+ constructor(client) {
6
+ super({
7
+ close: (code, reason) => {
8
+ client.close(code, reason);
9
+ },
10
+ send: (data) => {
11
+ client.send(data);
12
+ },
13
+ terminate: () => {
14
+ client.close();
15
+ }
16
+ });
17
+ client.addEventListener("message", (event) => {
18
+ this.emit("message", toBuffer(event.data), false);
19
+ });
20
+ client.addEventListener("close", (event) => {
21
+ this.readyState = WebSocket.CLOSED;
22
+ this.emit("close", event.code, event.reason);
23
+ });
24
+ }
25
+ };
26
+ export { MswWebSocketAdapter };
@@ -0,0 +1,7 @@
1
+ import { ProcedureResolverOptions } from "./ProcedureResolverOptions.js";
2
+ import { SubscriptionRegistration } from "./SubscriptionRegistration.js";
3
+ import { TRPCProcedureType } from "@trpc/server";
4
+ export type ProcedureRegistration = SubscriptionRegistration | {
5
+ resolver: (options: ProcedureResolverOptions<unknown, unknown>) => unknown;
6
+ type: Exclude<TRPCProcedureType, "subscription">;
7
+ };
@@ -0,0 +1,4 @@
1
+ import { ProcedureResolverOptions } from "./ProcedureResolverOptions.js";
2
+ import { Promisable } from "../vendor/pnpm/type-fest@5.10.0/vendor/type-fest/source/promisable.js";
3
+ import { AnyTRPCProcedure, inferProcedureInput, inferProcedureOutput } from "@trpc/server";
4
+ export type ProcedureResolver<TContext, TProcedure extends AnyTRPCProcedure> = (options: ProcedureResolverOptions<TContext, inferProcedureInput<TProcedure>>) => Promisable<inferProcedureOutput<TProcedure>>;
@@ -0,0 +1,7 @@
1
+ export interface ProcedureResolverOptions<TContext, TInput> {
2
+ batchIndex?: number;
3
+ ctx: TContext;
4
+ input: TInput;
5
+ path: string;
6
+ signal?: AbortSignal;
7
+ }
@@ -0,0 +1,6 @@
1
+ import { ProcedureResolverOptions } from "./ProcedureResolverOptions.js";
2
+ import { Promisable } from "../vendor/pnpm/type-fest@5.10.0/vendor/type-fest/source/promisable.js";
3
+ export interface SubscriptionRegistration {
4
+ resolver: (options: ProcedureResolverOptions<unknown, unknown>) => Promisable<AsyncIterable<unknown>>;
5
+ type: "subscription";
6
+ }
@@ -0,0 +1,8 @@
1
+ import { TRPCMswRouterRecord } from "./TRPCMswRouterRecord.js";
2
+ import { AnyTRPCRouter } from "@trpc/server";
3
+ import { HttpHandler, WebSocketHandler } from "msw";
4
+ export interface TRPCMsw<TRouter extends AnyTRPCRouter, TContext> {
5
+ handlers: (HttpHandler | WebSocketHandler)[];
6
+ reset: () => void;
7
+ trpc: TRPCMswRouterRecord<TContext, TRouter["_def"]["record"]>;
8
+ }
@@ -0,0 +1,14 @@
1
+ import { CreateContextOptions } from "./CreateContextOptions.js";
2
+ import { TRPCMswRoot } from "./TRPCMswRoot.js";
3
+ import { UnhandledProcedureAction } from "./UnhandledProcedureAction.js";
4
+ import { Promisable } from "../vendor/pnpm/type-fest@5.10.0/vendor/type-fest/source/promisable.js";
5
+ import { AnyTRPCRouter } from "@trpc/server";
6
+ export interface TRPCMswOptions<TContext extends object> {
7
+ allowMethodOverride?: boolean;
8
+ createContext?: (options: CreateContextOptions) => Promisable<TContext>;
9
+ endpoint: string;
10
+ onUnhandledProcedure?: UnhandledProcedureAction;
11
+ router?: AnyTRPCRouter;
12
+ t: TRPCMswRoot<TContext>;
13
+ webSocketUrl?: string;
14
+ }
@@ -0,0 +1,5 @@
1
+ import { AnyTRPCRootTypes, TRPCRootObject, TRPCRouterBuilder } from "@trpc/server";
2
+ export interface TRPCMswRoot<TContext extends object> {
3
+ procedure: TRPCRootObject<TContext, object, object>["procedure"];
4
+ router: TRPCRouterBuilder<AnyTRPCRootTypes>;
5
+ }
@@ -0,0 +1,3 @@
1
+ import { ProcedureResolver } from "./ProcedureResolver.js";
2
+ import { AnyTRPCProcedure, TRPCRouterRecord } from "@trpc/server";
3
+ 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; };
@@ -0,0 +1,4 @@
1
+ export declare enum UnhandledProcedureAction {
2
+ Bypass = "Bypass",
3
+ Error = "Error"
4
+ }
@@ -0,0 +1,7 @@
1
+ // src/models/UnhandledProcedureAction.ts
2
+ let UnhandledProcedureAction = /* @__PURE__ */ function(UnhandledProcedureAction) {
3
+ UnhandledProcedureAction["Bypass"] = "Bypass";
4
+ UnhandledProcedureAction["Error"] = "Error";
5
+ return UnhandledProcedureAction;
6
+ }({});
7
+ export { UnhandledProcedureAction };
@@ -0,0 +1,16 @@
1
+ import { EventEmitter } from "node:events";
2
+ export declare class WebSocketClientAdapter extends EventEmitter {
3
+ readonly close: (code?: number, reason?: string) => void;
4
+ readonly CLOSED: number;
5
+ readonly CLOSING: number;
6
+ readonly CONNECTING: number;
7
+ readonly OPEN: number;
8
+ readyState: number;
9
+ readonly send: (data: string) => void;
10
+ readonly terminate: () => void;
11
+ constructor(transport: {
12
+ close: (code?: number, reason?: string) => void;
13
+ send: (data: string) => void;
14
+ terminate: () => void;
15
+ });
16
+ }
@@ -0,0 +1,27 @@
1
+ import { EventEmitter } from "node:events";
2
+ // ../trpc-nuxt-module/dist/runtime/server/models/WebSocketClientAdapter.js
3
+ var WebSocketClientAdapter = class extends EventEmitter {
4
+ close;
5
+ CLOSED = WebSocket.CLOSED;
6
+ CLOSING = WebSocket.CLOSING;
7
+ CONNECTING = WebSocket.CONNECTING;
8
+ OPEN = WebSocket.OPEN;
9
+ readyState = WebSocket.OPEN;
10
+ send;
11
+ terminate;
12
+ constructor(transport) {
13
+ super();
14
+ this.close = (code, reason) => {
15
+ this.readyState = WebSocket.CLOSING;
16
+ transport.close(code, reason);
17
+ };
18
+ this.send = (data) => {
19
+ transport.send(data);
20
+ };
21
+ this.terminate = () => {
22
+ this.readyState = WebSocket.CLOSING;
23
+ transport.terminate();
24
+ };
25
+ }
26
+ };
27
+ export { WebSocketClientAdapter };
@@ -0,0 +1,15 @@
1
+ import { EventEmitter } from "node:events";
2
+ // ../trpc-nuxt-module/dist/runtime/server/models/WebSocketServerAdapter.js
3
+ var WebSocketServerAdapter = class extends EventEmitter {
4
+ clients = /* @__PURE__ */ new Set();
5
+ constructor() {
6
+ super();
7
+ this.on("connection", (client) => {
8
+ this.clients.add(client);
9
+ client.once("close", () => {
10
+ this.clients.delete(client);
11
+ });
12
+ });
13
+ }
14
+ };
15
+ export { WebSocketServerAdapter };
@@ -0,0 +1,2 @@
1
+ import { TRPCProcedureType } from "@trpc/server";
2
+ export declare const checkIsProcedureType: (value: unknown) => value is TRPCProcedureType;
@@ -0,0 +1,8 @@
1
+ // src/services/checkIsProcedureType.ts
2
+ const PROCEDURE_TYPES = /* @__PURE__ */ new Set([
3
+ "mutation",
4
+ "query",
5
+ "subscription"
6
+ ]);
7
+ const checkIsProcedureType = (value) => PROCEDURE_TYPES.has(value);
8
+ export { checkIsProcedureType };
@@ -0,0 +1,4 @@
1
+ import { ProcedureRegistration } from "../models/ProcedureRegistration.js";
2
+ import { TRPCMswRoot } from "../models/TRPCMswRoot.js";
3
+ import { AnyTRPCRouter, TRPCProcedureType } from "@trpc/server";
4
+ export declare const createMockRouter: <TContext extends object>({ procedure: baseProcedure, router }: TRPCMswRoot<TContext>, procedureTypes: ReadonlyMap<string, TRPCProcedureType>, registrations: ReadonlyMap<string, ProcedureRegistration>, inputRouter?: AnyTRPCRouter) => AnyTRPCRouter;
@@ -0,0 +1,26 @@
1
+ import { toResolverOptions } from "./toResolverOptions.js";
2
+ import { exhaustiveGuard } from "@esposter/shared";
3
+ import { TRPCError } from "@trpc/server";
4
+ // src/services/createMockRouter.ts
5
+ const createMockRouter = ({ procedure: baseProcedure, router }, procedureTypes, registrations, inputRouter) => router(Object.fromEntries(procedureTypes.entries().map(([path, type]) => {
6
+ const procedure = (inputRouter?._def.procedures[path]?._def.inputs ?? []).reduce((builder, parser) => builder.input(parser), baseProcedure);
7
+ const createNotFoundError = () => new TRPCError({
8
+ code: "NOT_FOUND",
9
+ message: `No "${type}"-procedure on path "${path}"`
10
+ });
11
+ switch (type) {
12
+ case "mutation":
13
+ case "query": return [path, procedure[type]((options) => {
14
+ const registration = registrations.get(path);
15
+ if (registration?.type === type) return registration.resolver(toResolverOptions(options));
16
+ else throw createNotFoundError();
17
+ })];
18
+ case "subscription": return [path, procedure.subscription(async function* (options) {
19
+ const registration = registrations.get(path);
20
+ if (registration?.type !== type) throw createNotFoundError();
21
+ yield* await registration.resolver(toResolverOptions(options));
22
+ })];
23
+ default: return exhaustiveGuard(type);
24
+ }
25
+ })));
26
+ export { createMockRouter };
@@ -0,0 +1 @@
1
+ export declare const getProcedurePaths: (url: string, endpointPathname: string) => string[];
@@ -0,0 +1,3 @@
1
+ // src/services/getProcedurePaths.ts
2
+ const getProcedurePaths = (url, endpointPathname) => decodeURIComponent(new URL(url).pathname.slice(endpointPathname.length + 1)).split(",");
3
+ export { getProcedurePaths };
@@ -0,0 +1,2 @@
1
+ import { WebSocketData } from "msw";
2
+ export declare const toBuffer: (data: WebSocketData) => Buffer;
@@ -0,0 +1,8 @@
1
+ // src/services/toBuffer.ts
2
+ const toBuffer = (data) => {
3
+ if (typeof data === "string") return Buffer.from(data);
4
+ else if (ArrayBuffer.isView(data)) return Buffer.from(data.buffer, data.byteOffset, data.byteLength);
5
+ else if (data instanceof Blob) throw new TypeError("A WebSocket message sent as a Blob cannot be read in order");
6
+ else return Buffer.from(data);
7
+ };
8
+ export { toBuffer };
@@ -0,0 +1,2 @@
1
+ import { ProcedureResolverOptions } from "../models/ProcedureResolverOptions.js";
2
+ export declare const toResolverOptions: ({ batchIndex, ctx, input, path, signal }: ProcedureResolverOptions<unknown, unknown>) => ProcedureResolverOptions<unknown, unknown>;
@@ -0,0 +1,9 @@
1
+ // src/services/toResolverOptions.ts
2
+ const toResolverOptions = ({ batchIndex, ctx, input, path, signal }) => ({
3
+ batchIndex,
4
+ ctx,
5
+ input,
6
+ path,
7
+ signal
8
+ });
9
+ export { toResolverOptions };
@@ -0,0 +1,25 @@
1
+ /**
2
+ Create a type that represents either the value or the value wrapped in `PromiseLike`.
3
+
4
+ Use-cases:
5
+ - A function accepts a callback that may either return a value synchronously or may return a promised value.
6
+ - This type could be the return type of `Promise#then()`, `Promise#catch()`, and `Promise#finally()` callbacks.
7
+
8
+ Please upvote [this issue](https://github.com/microsoft/TypeScript/issues/31394) if you want to have this type as a built-in in TypeScript.
9
+
10
+ @example
11
+ ```
12
+ import type {Promisable} from 'type-fest';
13
+
14
+ async function logger(getLogEntry: () => Promisable<string>): Promise<void> {
15
+ const entry = await getLogEntry();
16
+ console.log(entry);
17
+ }
18
+
19
+ await logger(() => 'foo');
20
+ await logger(() => Promise.resolve('bar'));
21
+ ```
22
+
23
+ @category Async
24
+ */
25
+ export type Promisable<T> = T | PromiseLike<T>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "trpc-msw",
3
- "version": "4.6.0",
3
+ "version": "4.8.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.6.0"
50
+ "@esposter/shared": "4.8.0"
51
51
  },
52
52
  "devDependencies": {
53
- "@esposter/configuration": "4.6.0",
53
+ "@esposter/configuration": "4.8.0",
54
54
  "@standard-schema/spec": "^1.1.0",
55
- "@trpc/client": "^11.25.0",
55
+ "@trpc/client": "^11.25.2",
56
56
  "@types/node": "^26.6.6",
57
57
  "superjson": "^2.2.6",
58
- "trpc-nuxt-module": "4.6.0",
58
+ "trpc-nuxt-module": "4.8.0",
59
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.25.0",
64
+ "@trpc/server": "^11.25.2",
65
65
  "msw": "^3.0.4"
66
66
  },
67
67
  "inlinedDependencies": {
68
68
  "type-fest": "5.10.0"
69
69
  },
70
- "gitHead": "0ceea3ffbe12ca69413ea5db2d3cfad197a63cba"
70
+ "gitHead": "a76179895911c8c93401873a6bd5895658977592"
71
71
  }