trpc-msw 4.2.0 → 4.3.3
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 +1 -1
- package/dist/index.d.ts +91 -0
- package/dist/index.js +165 -0
- package/package.json +5 -10
package/README.md
CHANGED
|
@@ -52,7 +52,7 @@ test("reads a post", async () => {
|
|
|
52
52
|
|
|
53
53
|
## <a name="documentation">📖 Documentation</a>
|
|
54
54
|
|
|
55
|
-
We highly recommend you take a look at the [documentation](https://
|
|
55
|
+
We highly recommend you take a look at the [documentation](https://github.com/Esposter/Esposter/tree/main/openspec/specs/trpc-msw) to level up. It covers the design and the upstream `msw-trpc` issues this package answers.
|
|
56
56
|
|
|
57
57
|
### Key exports
|
|
58
58
|
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
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
|
+
type MswWebSocketClient = WebSocketHandlerConnection["client"];
|
|
66
|
+
export declare class MswWebSocketAdapter extends EventEmitter {
|
|
67
|
+
#private;
|
|
68
|
+
readonly CLOSED: number;
|
|
69
|
+
readonly CLOSING: number;
|
|
70
|
+
readonly CONNECTING: number;
|
|
71
|
+
readonly OPEN: number;
|
|
72
|
+
readyState: number;
|
|
73
|
+
constructor(client: MswWebSocketClient);
|
|
74
|
+
close(code?: number, reason?: string): void;
|
|
75
|
+
send(data: string): void;
|
|
76
|
+
terminate(): void;
|
|
77
|
+
}
|
|
78
|
+
export interface SubscriptionRegistration {
|
|
79
|
+
resolver: (options: ProcedureResolverOptions<unknown, unknown>) => Promisable<AsyncIterable<unknown>>;
|
|
80
|
+
type: "subscription";
|
|
81
|
+
}
|
|
82
|
+
export type ProcedureRegistration = SubscriptionRegistration | {
|
|
83
|
+
resolver: (options: ProcedureResolverOptions<unknown, unknown>) => unknown;
|
|
84
|
+
type: Exclude<TRPCProcedureType, "subscription">;
|
|
85
|
+
};
|
|
86
|
+
export declare const checkIsProcedureType: (value: unknown) => value is TRPCProcedureType;
|
|
87
|
+
export declare const createMockRouter: <TContext extends object>({ procedure: baseProcedure, router }: TRPCMswRoot<TContext>, procedureTypes: ReadonlyMap<string, TRPCProcedureType>, registrations: ReadonlyMap<string, ProcedureRegistration>, inputRouter?: AnyTRPCRouter) => AnyTRPCRouter;
|
|
88
|
+
export declare const getProcedurePaths: (url: string, endpointPathname: string) => string[];
|
|
89
|
+
export declare const toBuffer: (data: WebSocketData) => Buffer;
|
|
90
|
+
export declare const toResolverOptions: ({ batchIndex, ctx, input, path, signal }: ProcedureResolverOptions<unknown, unknown>) => ProcedureResolverOptions<unknown, unknown>;
|
|
91
|
+
export {};
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
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
|
+
// src/models/MswWebSocketAdapter.ts
|
|
19
|
+
var MswWebSocketAdapter = class extends EventEmitter {
|
|
20
|
+
CLOSED = WebSocket.CLOSED;
|
|
21
|
+
CLOSING = WebSocket.CLOSING;
|
|
22
|
+
CONNECTING = WebSocket.CONNECTING;
|
|
23
|
+
OPEN = WebSocket.OPEN;
|
|
24
|
+
readyState = WebSocket.OPEN;
|
|
25
|
+
#client;
|
|
26
|
+
constructor(client) {
|
|
27
|
+
super();
|
|
28
|
+
this.#client = client;
|
|
29
|
+
client.addEventListener("message", (event) => {
|
|
30
|
+
this.emit("message", toBuffer(event.data), false);
|
|
31
|
+
});
|
|
32
|
+
client.addEventListener("close", (event) => {
|
|
33
|
+
this.readyState = WebSocket.CLOSED;
|
|
34
|
+
this.emit("close", event.code, event.reason);
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
close(code, reason) {
|
|
38
|
+
this.readyState = WebSocket.CLOSING;
|
|
39
|
+
this.#client.close(code, reason);
|
|
40
|
+
}
|
|
41
|
+
send(data) {
|
|
42
|
+
this.#client.send(data);
|
|
43
|
+
}
|
|
44
|
+
terminate() {
|
|
45
|
+
this.close();
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
// src/models/UnhandledProcedureAction.ts
|
|
49
|
+
let UnhandledProcedureAction = /* @__PURE__ */ function(UnhandledProcedureAction) {
|
|
50
|
+
UnhandledProcedureAction["Bypass"] = "Bypass";
|
|
51
|
+
UnhandledProcedureAction["Error"] = "Error";
|
|
52
|
+
return UnhandledProcedureAction;
|
|
53
|
+
}({});
|
|
54
|
+
// src/services/checkIsProcedureType.ts
|
|
55
|
+
const PROCEDURE_TYPES = /* @__PURE__ */ new Set([
|
|
56
|
+
"mutation",
|
|
57
|
+
"query",
|
|
58
|
+
"subscription"
|
|
59
|
+
]);
|
|
60
|
+
const checkIsProcedureType = (value) => PROCEDURE_TYPES.has(value);
|
|
61
|
+
// src/services/toResolverOptions.ts
|
|
62
|
+
const toResolverOptions = ({ batchIndex, ctx, input, path, signal }) => ({
|
|
63
|
+
batchIndex,
|
|
64
|
+
ctx,
|
|
65
|
+
input,
|
|
66
|
+
path,
|
|
67
|
+
signal
|
|
68
|
+
});
|
|
69
|
+
// src/services/createMockRouter.ts
|
|
70
|
+
const createMockRouter = ({ procedure: baseProcedure, router }, procedureTypes, registrations, inputRouter) => router(Object.fromEntries(procedureTypes.entries().map(([path, type]) => {
|
|
71
|
+
const procedure = (inputRouter?._def.procedures[path]?._def.inputs ?? []).reduce((builder, parser) => builder.input(parser), baseProcedure);
|
|
72
|
+
const createNotFoundError = () => new TRPCError({
|
|
73
|
+
code: "NOT_FOUND",
|
|
74
|
+
message: `No "${type}"-procedure on path "${path}"`
|
|
75
|
+
});
|
|
76
|
+
switch (type) {
|
|
77
|
+
case "mutation":
|
|
78
|
+
case "query": return [path, procedure[type]((options) => {
|
|
79
|
+
const registration = registrations.get(path);
|
|
80
|
+
if (registration?.type === type) return registration.resolver(toResolverOptions(options));
|
|
81
|
+
else throw createNotFoundError();
|
|
82
|
+
})];
|
|
83
|
+
case "subscription": return [path, procedure.subscription(async function* (options) {
|
|
84
|
+
const registration = registrations.get(path);
|
|
85
|
+
if (registration?.type !== type) throw createNotFoundError();
|
|
86
|
+
yield* await registration.resolver(toResolverOptions(options));
|
|
87
|
+
})];
|
|
88
|
+
default: return exhaustiveGuard(type);
|
|
89
|
+
}
|
|
90
|
+
})));
|
|
91
|
+
// src/services/getProcedurePaths.ts
|
|
92
|
+
const getProcedurePaths = (url, endpointPathname) => decodeURIComponent(new URL(url).pathname.slice(endpointPathname.length + 1)).split(",");
|
|
93
|
+
// ../trpc-nuxt-module/dist/runtime/server/models/WebSocketServerAdapter.js
|
|
94
|
+
var WebSocketServerAdapter = class extends EventEmitter {
|
|
95
|
+
clients = /* @__PURE__ */ new Set();
|
|
96
|
+
addConnection(client, request) {
|
|
97
|
+
this.clients.add(client);
|
|
98
|
+
client.once("close", () => {
|
|
99
|
+
this.clients.delete(client);
|
|
100
|
+
});
|
|
101
|
+
this.emit("connection", client, request);
|
|
102
|
+
}
|
|
103
|
+
};
|
|
104
|
+
// src/createTRPCMsw.ts
|
|
105
|
+
const createTRPCMsw = ({ allowMethodOverride, createContext, endpoint, onUnhandledProcedure = "Error", router, t, webSocketUrl }) => {
|
|
106
|
+
const registrations = /* @__PURE__ */ new Map();
|
|
107
|
+
const procedureTypes = /* @__PURE__ */ new Map();
|
|
108
|
+
const endpointPathname = new URL(endpoint, "http://localhost").pathname;
|
|
109
|
+
let httpRouter;
|
|
110
|
+
const handlers = [http.all(`${endpoint}/*`, ({ request }) => {
|
|
111
|
+
if (onUnhandledProcedure === "Bypass" && !getProcedurePaths(request.url, endpointPathname).some((path) => registrations.has(path))) return void 0;
|
|
112
|
+
httpRouter ??= createMockRouter(t, procedureTypes, registrations, router);
|
|
113
|
+
return fetchRequestHandler({
|
|
114
|
+
allowMethodOverride,
|
|
115
|
+
createContext,
|
|
116
|
+
endpoint: endpointPathname,
|
|
117
|
+
req: request,
|
|
118
|
+
router: httpRouter
|
|
119
|
+
});
|
|
120
|
+
})];
|
|
121
|
+
const createWebSocketServer = () => {
|
|
122
|
+
const webSocketServer = new WebSocketServerAdapter();
|
|
123
|
+
applyWSSHandler({
|
|
124
|
+
createContext,
|
|
125
|
+
router: createMockRouter(t, new Map(procedureTypes), registrations, router),
|
|
126
|
+
wss: webSocketServer
|
|
127
|
+
});
|
|
128
|
+
return webSocketServer;
|
|
129
|
+
};
|
|
130
|
+
let webSocketServer;
|
|
131
|
+
if (webSocketUrl) handlers.push(ws.link(webSocketUrl).addEventListener("connection", (connection) => {
|
|
132
|
+
const { client } = connection;
|
|
133
|
+
const request = new IncomingMessage(new Socket());
|
|
134
|
+
request.url = `${client.url.pathname}${client.url.search}`;
|
|
135
|
+
webSocketServer ??= createWebSocketServer();
|
|
136
|
+
webSocketServer.addConnection(new MswWebSocketAdapter(client), request);
|
|
137
|
+
}));
|
|
138
|
+
const register = (path, registration) => {
|
|
139
|
+
registrations.set(path, registration);
|
|
140
|
+
if (procedureTypes.get(path) === registration.type) return;
|
|
141
|
+
procedureTypes.set(path, registration.type);
|
|
142
|
+
httpRouter = void 0;
|
|
143
|
+
if (!webSocketServer) return;
|
|
144
|
+
for (const client of webSocketServer.clients) client.close(WEBSOCKET_ROUTER_REPLACED_CLOSE_CODE);
|
|
145
|
+
webSocketServer = void 0;
|
|
146
|
+
};
|
|
147
|
+
return {
|
|
148
|
+
handlers,
|
|
149
|
+
reset: () => {
|
|
150
|
+
registrations.clear();
|
|
151
|
+
},
|
|
152
|
+
trpc: createTRPCRecursiveProxy(({ args: [resolver], path }) => {
|
|
153
|
+
const type = path.at(-1);
|
|
154
|
+
if (!checkIsProcedureType(type) || typeof resolver !== "function") throw new TypeError(`Expected a resolver registered with query, mutation or subscription at "${path.join(".")}"`);
|
|
155
|
+
register(path.slice(0, -1).join("."), type === "subscription" ? {
|
|
156
|
+
resolver,
|
|
157
|
+
type
|
|
158
|
+
} : {
|
|
159
|
+
resolver,
|
|
160
|
+
type
|
|
161
|
+
});
|
|
162
|
+
})
|
|
163
|
+
};
|
|
164
|
+
};
|
|
165
|
+
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.
|
|
3
|
+
"version": "4.3.3",
|
|
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",
|
|
@@ -41,28 +41,23 @@
|
|
|
41
41
|
},
|
|
42
42
|
"scripts": {
|
|
43
43
|
"build": "tsdown",
|
|
44
|
-
"format": "oxfmt",
|
|
45
|
-
"format:check": "oxfmt --check",
|
|
46
44
|
"lint": "eslint .",
|
|
47
45
|
"lint:fix": "eslint --fix .",
|
|
48
46
|
"test": "vitest",
|
|
49
47
|
"typecheck": "tsc"
|
|
50
48
|
},
|
|
51
49
|
"dependencies": {
|
|
52
|
-
"@esposter/shared": "4.
|
|
50
|
+
"@esposter/shared": "4.3.3"
|
|
53
51
|
},
|
|
54
52
|
"devDependencies": {
|
|
55
|
-
"@
|
|
56
|
-
"@esposter/configuration": "4.2.0",
|
|
53
|
+
"@esposter/configuration": "4.3.3",
|
|
57
54
|
"@standard-schema/spec": "^1.1.0",
|
|
58
55
|
"@trpc/client": "^11.19.0",
|
|
59
56
|
"@types/node": "^26.6.5",
|
|
60
|
-
"publint": "^0.3.25",
|
|
61
57
|
"superjson": "^2.2.6",
|
|
62
|
-
"trpc-nuxt-module": "4.
|
|
58
|
+
"trpc-nuxt-module": "4.3.3",
|
|
63
59
|
"tsdown": "^0.23.1",
|
|
64
60
|
"type-fest": "^5.10.0",
|
|
65
|
-
"vitest": "^5.0.4",
|
|
66
61
|
"zod": "^4.6.7"
|
|
67
62
|
},
|
|
68
63
|
"peerDependencies": {
|
|
@@ -72,5 +67,5 @@
|
|
|
72
67
|
"inlinedDependencies": {
|
|
73
68
|
"type-fest": "5.10.0"
|
|
74
69
|
},
|
|
75
|
-
"gitHead": "
|
|
70
|
+
"gitHead": "955bbc130ad9b28877fd4ae8efc73a045141ce01"
|
|
76
71
|
}
|