@metamask-previews/json-rpc-engine 10.5.0-preview-4f4c98e → 10.5.0-preview-eb263b0ee
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/CHANGELOG.md +0 -1
- package/dist/JsonRpcEngine.cjs +352 -0
- package/dist/JsonRpcEngine.cjs.map +1 -0
- package/dist/{JsonRpcEngine.d.ts → JsonRpcEngine.d.cts} +3 -3
- package/dist/JsonRpcEngine.d.cts.map +1 -0
- package/dist/JsonRpcEngine.d.mts +132 -0
- package/dist/JsonRpcEngine.d.mts.map +1 -0
- package/dist/{JsonRpcEngine.js → JsonRpcEngine.mjs} +5 -5
- package/dist/JsonRpcEngine.mjs.map +1 -0
- package/dist/asV2Middleware.cjs +57 -0
- package/dist/asV2Middleware.cjs.map +1 -0
- package/dist/{asV2Middleware.d.ts → asV2Middleware.d.cts} +6 -6
- package/dist/asV2Middleware.d.cts.map +1 -0
- package/dist/asV2Middleware.d.mts +20 -0
- package/dist/asV2Middleware.d.mts.map +1 -0
- package/dist/{asV2Middleware.js → asV2Middleware.mjs} +5 -5
- package/dist/asV2Middleware.mjs.map +1 -0
- package/dist/createAsyncMiddleware.cjs +71 -0
- package/dist/createAsyncMiddleware.cjs.map +1 -0
- package/dist/{createAsyncMiddleware.d.ts → createAsyncMiddleware.d.cts} +3 -3
- package/dist/createAsyncMiddleware.d.cts.map +1 -0
- package/dist/createAsyncMiddleware.d.mts +28 -0
- package/dist/createAsyncMiddleware.d.mts.map +1 -0
- package/dist/{createAsyncMiddleware.js → createAsyncMiddleware.mjs} +1 -1
- package/dist/createAsyncMiddleware.mjs.map +1 -0
- package/dist/createMethodMiddleware.cjs +56 -0
- package/dist/createMethodMiddleware.cjs.map +1 -0
- package/dist/{createMethodMiddleware.d.ts → createMethodMiddleware.d.cts} +6 -6
- package/dist/createMethodMiddleware.d.cts.map +1 -0
- package/dist/createMethodMiddleware.d.mts +86 -0
- package/dist/createMethodMiddleware.d.mts.map +1 -0
- package/dist/{createMethodMiddleware.js → createMethodMiddleware.mjs} +3 -3
- package/dist/createMethodMiddleware.mjs.map +1 -0
- package/dist/createOriginMiddleware.cjs +18 -0
- package/dist/createOriginMiddleware.cjs.map +1 -0
- package/dist/{createOriginMiddleware.d.ts → createOriginMiddleware.d.cts} +3 -3
- package/dist/createOriginMiddleware.d.cts.map +1 -0
- package/dist/createOriginMiddleware.d.mts +11 -0
- package/dist/createOriginMiddleware.d.mts.map +1 -0
- package/dist/{createOriginMiddleware.js → createOriginMiddleware.mjs} +1 -1
- package/dist/createOriginMiddleware.mjs.map +1 -0
- package/dist/createScaffoldMiddleware.cjs +31 -0
- package/dist/createScaffoldMiddleware.cjs.map +1 -0
- package/dist/{createScaffoldMiddleware.d.ts → createScaffoldMiddleware.d.cts} +3 -3
- package/dist/createScaffoldMiddleware.d.cts.map +1 -0
- package/dist/createScaffoldMiddleware.d.mts +18 -0
- package/dist/createScaffoldMiddleware.d.mts.map +1 -0
- package/dist/{createScaffoldMiddleware.js → createScaffoldMiddleware.mjs} +1 -1
- package/dist/createScaffoldMiddleware.mjs.map +1 -0
- package/dist/getUniqueId.cjs +20 -0
- package/dist/getUniqueId.cjs.map +1 -0
- package/dist/{getUniqueId.d.ts → getUniqueId.d.cts} +1 -1
- package/dist/getUniqueId.d.cts.map +1 -0
- package/dist/getUniqueId.d.mts +9 -0
- package/dist/getUniqueId.d.mts.map +1 -0
- package/dist/{getUniqueId.js → getUniqueId.mjs} +1 -1
- package/dist/getUniqueId.mjs.map +1 -0
- package/dist/idRemapMiddleware.cjs +29 -0
- package/dist/idRemapMiddleware.cjs.map +1 -0
- package/dist/{idRemapMiddleware.d.ts → idRemapMiddleware.d.cts} +3 -3
- package/dist/idRemapMiddleware.d.cts.map +1 -0
- package/dist/idRemapMiddleware.d.mts +14 -0
- package/dist/idRemapMiddleware.d.mts.map +1 -0
- package/dist/{idRemapMiddleware.js → idRemapMiddleware.mjs} +2 -2
- package/dist/idRemapMiddleware.mjs.map +1 -0
- package/dist/index.cjs +22 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +13 -0
- package/dist/index.d.cts.map +1 -0
- package/dist/index.d.mts +13 -0
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +10 -0
- package/dist/index.mjs.map +1 -0
- package/dist/mergeMiddleware.cjs +18 -0
- package/dist/mergeMiddleware.cjs.map +1 -0
- package/dist/{mergeMiddleware.d.ts → mergeMiddleware.d.cts} +3 -3
- package/dist/mergeMiddleware.d.cts.map +1 -0
- package/dist/mergeMiddleware.d.mts +11 -0
- package/dist/mergeMiddleware.d.mts.map +1 -0
- package/dist/{mergeMiddleware.js → mergeMiddleware.mjs} +2 -2
- package/dist/mergeMiddleware.mjs.map +1 -0
- package/dist/v2/JsonRpcEngineV2.cjs +220 -0
- package/dist/v2/JsonRpcEngineV2.cjs.map +1 -0
- package/dist/v2/{JsonRpcEngineV2.d.ts → JsonRpcEngineV2.d.cts} +5 -5
- package/dist/v2/JsonRpcEngineV2.d.cts.map +1 -0
- package/dist/v2/JsonRpcEngineV2.d.mts +136 -0
- package/dist/v2/JsonRpcEngineV2.d.mts.map +1 -0
- package/dist/v2/{JsonRpcEngineV2.js → JsonRpcEngineV2.mjs} +13 -9
- package/dist/v2/JsonRpcEngineV2.mjs.map +1 -0
- package/dist/v2/JsonRpcServer.cjs +178 -0
- package/dist/v2/JsonRpcServer.cjs.map +1 -0
- package/dist/v2/{JsonRpcServer.d.ts → JsonRpcServer.d.cts} +4 -4
- package/dist/v2/JsonRpcServer.d.cts.map +1 -0
- package/dist/v2/JsonRpcServer.d.mts +104 -0
- package/dist/v2/JsonRpcServer.d.mts.map +1 -0
- package/dist/v2/{JsonRpcServer.js → JsonRpcServer.mjs} +5 -5
- package/dist/v2/JsonRpcServer.mjs.map +1 -0
- package/dist/v2/MiddlewareContext.cjs +108 -0
- package/dist/v2/MiddlewareContext.cjs.map +1 -0
- package/dist/v2/{MiddlewareContext.d.ts → MiddlewareContext.d.cts} +2 -2
- package/dist/v2/MiddlewareContext.d.cts.map +1 -0
- package/dist/v2/MiddlewareContext.d.mts +108 -0
- package/dist/v2/MiddlewareContext.d.mts.map +1 -0
- package/dist/v2/{MiddlewareContext.js → MiddlewareContext.mjs} +2 -2
- package/dist/v2/MiddlewareContext.mjs.map +1 -0
- package/dist/v2/asLegacyMiddleware.cjs +45 -0
- package/dist/v2/asLegacyMiddleware.cjs.map +1 -0
- package/dist/v2/{asLegacyMiddleware.d.ts → asLegacyMiddleware.d.cts} +5 -5
- package/dist/v2/asLegacyMiddleware.d.cts.map +1 -0
- package/dist/v2/asLegacyMiddleware.d.mts +19 -0
- package/dist/v2/asLegacyMiddleware.d.mts.map +1 -0
- package/dist/v2/{asLegacyMiddleware.js → asLegacyMiddleware.mjs} +4 -4
- package/dist/v2/asLegacyMiddleware.mjs.map +1 -0
- package/dist/v2/compatibility-utils.cjs +167 -0
- package/dist/v2/compatibility-utils.cjs.map +1 -0
- package/dist/v2/{compatibility-utils.d.ts → compatibility-utils.d.cts} +5 -5
- package/dist/v2/compatibility-utils.d.cts.map +1 -0
- package/dist/v2/compatibility-utils.d.mts +75 -0
- package/dist/v2/compatibility-utils.d.mts.map +1 -0
- package/dist/v2/{compatibility-utils.js → compatibility-utils.mjs} +6 -6
- package/dist/v2/compatibility-utils.mjs.map +1 -0
- package/dist/v2/createMethodMiddleware.cjs +44 -0
- package/dist/v2/createMethodMiddleware.cjs.map +1 -0
- package/dist/v2/{createMethodMiddleware.d.ts → createMethodMiddleware.d.cts} +5 -5
- package/dist/v2/createMethodMiddleware.d.cts.map +1 -0
- package/dist/v2/createMethodMiddleware.d.mts +71 -0
- package/dist/v2/createMethodMiddleware.d.mts.map +1 -0
- package/dist/v2/{createMethodMiddleware.js → createMethodMiddleware.mjs} +3 -2
- package/dist/v2/createMethodMiddleware.mjs.map +1 -0
- package/dist/v2/createOriginMiddleware.cjs +18 -0
- package/dist/v2/createOriginMiddleware.cjs.map +1 -0
- package/dist/v2/{createOriginMiddleware.d.ts → createOriginMiddleware.d.cts} +4 -4
- package/dist/v2/createOriginMiddleware.d.cts.map +1 -0
- package/dist/v2/createOriginMiddleware.d.mts +13 -0
- package/dist/v2/createOriginMiddleware.d.mts.map +1 -0
- package/dist/v2/{createOriginMiddleware.js → createOriginMiddleware.mjs} +2 -1
- package/dist/v2/createOriginMiddleware.mjs.map +1 -0
- package/dist/v2/createScaffoldMiddleware.cjs +25 -0
- package/dist/v2/createScaffoldMiddleware.cjs.map +1 -0
- package/dist/v2/{createScaffoldMiddleware.d.ts → createScaffoldMiddleware.d.cts} +4 -4
- package/dist/v2/createScaffoldMiddleware.d.cts.map +1 -0
- package/dist/v2/createScaffoldMiddleware.d.mts +30 -0
- package/dist/v2/createScaffoldMiddleware.d.mts.map +1 -0
- package/dist/v2/{createScaffoldMiddleware.js → createScaffoldMiddleware.mjs} +1 -1
- package/dist/v2/createScaffoldMiddleware.mjs.map +1 -0
- package/dist/v2/index.cjs +26 -0
- package/dist/v2/index.cjs.map +1 -0
- package/dist/v2/index.d.cts +14 -0
- package/dist/v2/index.d.cts.map +1 -0
- package/dist/v2/index.d.mts +14 -0
- package/dist/v2/index.d.mts.map +1 -0
- package/dist/v2/index.mjs +10 -0
- package/dist/v2/index.mjs.map +1 -0
- package/dist/v2/utils.cjs +122 -0
- package/dist/v2/utils.cjs.map +1 -0
- package/dist/v2/{utils.d.ts → utils.d.cts} +5 -5
- package/dist/v2/utils.d.cts.map +1 -0
- package/dist/v2/utils.d.mts +85 -0
- package/dist/v2/utils.d.mts.map +1 -0
- package/dist/v2/{utils.js → utils.mjs} +3 -3
- package/dist/v2/utils.mjs.map +1 -0
- package/package.json +25 -15
- package/dist/JsonRpcEngine.d.ts.map +0 -1
- package/dist/JsonRpcEngine.js.map +0 -1
- package/dist/asV2Middleware.d.ts.map +0 -1
- package/dist/asV2Middleware.js.map +0 -1
- package/dist/createAsyncMiddleware.d.ts.map +0 -1
- package/dist/createAsyncMiddleware.js.map +0 -1
- package/dist/createMethodMiddleware.d.ts.map +0 -1
- package/dist/createMethodMiddleware.js.map +0 -1
- package/dist/createOriginMiddleware.d.ts.map +0 -1
- package/dist/createOriginMiddleware.js.map +0 -1
- package/dist/createScaffoldMiddleware.d.ts.map +0 -1
- package/dist/createScaffoldMiddleware.js.map +0 -1
- package/dist/getUniqueId.d.ts.map +0 -1
- package/dist/getUniqueId.js.map +0 -1
- package/dist/idRemapMiddleware.d.ts.map +0 -1
- package/dist/idRemapMiddleware.js.map +0 -1
- package/dist/index.d.ts +0 -13
- package/dist/index.d.ts.map +0 -1
- package/dist/index.js +0 -10
- package/dist/index.js.map +0 -1
- package/dist/mergeMiddleware.d.ts.map +0 -1
- package/dist/mergeMiddleware.js.map +0 -1
- package/dist/v2/JsonRpcEngineV2.d.ts.map +0 -1
- package/dist/v2/JsonRpcEngineV2.js.map +0 -1
- package/dist/v2/JsonRpcServer.d.ts.map +0 -1
- package/dist/v2/JsonRpcServer.js.map +0 -1
- package/dist/v2/MiddlewareContext.d.ts.map +0 -1
- package/dist/v2/MiddlewareContext.js.map +0 -1
- package/dist/v2/asLegacyMiddleware.d.ts.map +0 -1
- package/dist/v2/asLegacyMiddleware.js.map +0 -1
- package/dist/v2/compatibility-utils.d.ts.map +0 -1
- package/dist/v2/compatibility-utils.js.map +0 -1
- package/dist/v2/createMethodMiddleware.d.ts.map +0 -1
- package/dist/v2/createMethodMiddleware.js.map +0 -1
- package/dist/v2/createOriginMiddleware.d.ts.map +0 -1
- package/dist/v2/createOriginMiddleware.js.map +0 -1
- package/dist/v2/createScaffoldMiddleware.d.ts.map +0 -1
- package/dist/v2/createScaffoldMiddleware.js.map +0 -1
- package/dist/v2/index.d.ts +0 -14
- package/dist/v2/index.d.ts.map +0 -1
- package/dist/v2/index.js +0 -10
- package/dist/v2/index.js.map +0 -1
- package/dist/v2/utils.d.ts.map +0 -1
- package/dist/v2/utils.js.map +0 -1
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
|
|
3
|
+
if (kind === "m") throw new TypeError("Private method is not writable");
|
|
4
|
+
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
|
|
5
|
+
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
|
|
6
|
+
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
|
|
7
|
+
};
|
|
8
|
+
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
|
|
9
|
+
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
|
|
10
|
+
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
|
11
|
+
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
12
|
+
};
|
|
13
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
14
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
15
|
+
};
|
|
16
|
+
var _JsonRpcEngineV2_instances, _JsonRpcEngineV2_middleware, _JsonRpcEngineV2_isDestroyed, _JsonRpcEngineV2_handle, _JsonRpcEngineV2_makeNextFactory, _JsonRpcEngineV2_makeMiddlewareIterator, _JsonRpcEngineV2_updateResult, _JsonRpcEngineV2_assertValidNextRequest, _JsonRpcEngineV2_assertIsNotDestroyed;
|
|
17
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
18
|
+
exports.JsonRpcEngineV2 = void 0;
|
|
19
|
+
const utils_1 = require("@metamask/utils");
|
|
20
|
+
const deep_freeze_strict_1 = __importDefault(require("deep-freeze-strict"));
|
|
21
|
+
const compatibility_utils_js_1 = require("./compatibility-utils.cjs");
|
|
22
|
+
const MiddlewareContext_js_1 = require("./MiddlewareContext.cjs");
|
|
23
|
+
const utils_js_1 = require("./utils.cjs");
|
|
24
|
+
const INVALID_ENGINE = Symbol('Invalid engine');
|
|
25
|
+
/**
|
|
26
|
+
* A JSON-RPC request and response processor.
|
|
27
|
+
*
|
|
28
|
+
* Give it a stack of middleware, pass it requests, and get back responses.
|
|
29
|
+
*
|
|
30
|
+
* #### Requests vs. notifications
|
|
31
|
+
*
|
|
32
|
+
* JSON-RPC requests come in two flavors:
|
|
33
|
+
*
|
|
34
|
+
* - [Requests](https://www.jsonrpc.org/specification#request_object), i.e. request objects _with_ an `id`
|
|
35
|
+
* - [Notifications](https://www.jsonrpc.org/specification#notification), i.e. request objects _without_ an `id`
|
|
36
|
+
*
|
|
37
|
+
* For requests, one of the engine's middleware must "end" the request by returning a non-`undefined` result,
|
|
38
|
+
* or {@link handle} will throw an error:
|
|
39
|
+
*
|
|
40
|
+
* For notifications, on the other hand, one of the engine's middleware must return `undefined` to end the request,
|
|
41
|
+
* and any non-`undefined` return values will cause an error:
|
|
42
|
+
*
|
|
43
|
+
* @template Request - The type of request to handle.
|
|
44
|
+
* @template Result - The type of result to return.
|
|
45
|
+
*
|
|
46
|
+
* @example
|
|
47
|
+
* ```ts
|
|
48
|
+
* const engine = JsonRpcEngineV2.create({
|
|
49
|
+
* middleware,
|
|
50
|
+
* });
|
|
51
|
+
*
|
|
52
|
+
* try {
|
|
53
|
+
* const result = await engine.handle(request);
|
|
54
|
+
* // Handle result
|
|
55
|
+
* } catch (error) {
|
|
56
|
+
* // Handle error
|
|
57
|
+
* }
|
|
58
|
+
* ```
|
|
59
|
+
*/
|
|
60
|
+
class JsonRpcEngineV2 {
|
|
61
|
+
// See .create() for why this is private.
|
|
62
|
+
// eslint-disable-next-line no-restricted-syntax
|
|
63
|
+
constructor({ middleware }) {
|
|
64
|
+
_JsonRpcEngineV2_instances.add(this);
|
|
65
|
+
_JsonRpcEngineV2_middleware.set(this, void 0);
|
|
66
|
+
_JsonRpcEngineV2_isDestroyed.set(this, false);
|
|
67
|
+
__classPrivateFieldSet(this, _JsonRpcEngineV2_middleware, [...middleware], "f");
|
|
68
|
+
}
|
|
69
|
+
// We use a static factory method in order to construct a supertype of all middleware contexts,
|
|
70
|
+
// which enables us to instantiate an engine despite different middleware expecting different
|
|
71
|
+
// context types.
|
|
72
|
+
/**
|
|
73
|
+
* Create a new JSON-RPC engine.
|
|
74
|
+
*
|
|
75
|
+
* @throws If the middleware array is empty.
|
|
76
|
+
* @param options - The options for the engine.
|
|
77
|
+
* @param options.middleware - The middleware to use.
|
|
78
|
+
* @returns The JSON-RPC engine.
|
|
79
|
+
*/
|
|
80
|
+
static create({ middleware, }) {
|
|
81
|
+
// We can't use NonEmptyArray for the params because it ruins type inference.
|
|
82
|
+
if (middleware.length === 0) {
|
|
83
|
+
throw new utils_js_1.JsonRpcEngineError('Middleware array cannot be empty');
|
|
84
|
+
}
|
|
85
|
+
const mw = middleware;
|
|
86
|
+
return new JsonRpcEngineV2({
|
|
87
|
+
middleware: mw,
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
async handle(request, { context } = {}) {
|
|
91
|
+
const isReq = (0, utils_js_1.isRequest)(request);
|
|
92
|
+
const { result } = await __classPrivateFieldGet(this, _JsonRpcEngineV2_instances, "m", _JsonRpcEngineV2_handle).call(this, request, context);
|
|
93
|
+
if (isReq && result === undefined) {
|
|
94
|
+
throw new utils_js_1.JsonRpcEngineError(`Nothing ended request: ${(0, utils_js_1.stringify)(request)}`);
|
|
95
|
+
}
|
|
96
|
+
return (0, compatibility_utils_js_1.deepClone)(result);
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Convert the engine into a JSON-RPC middleware.
|
|
100
|
+
*
|
|
101
|
+
* @returns The JSON-RPC middleware.
|
|
102
|
+
*/
|
|
103
|
+
asMiddleware() {
|
|
104
|
+
__classPrivateFieldGet(this, _JsonRpcEngineV2_instances, "m", _JsonRpcEngineV2_assertIsNotDestroyed).call(this);
|
|
105
|
+
return async ({ request, context, next }) => {
|
|
106
|
+
const { result, request: finalRequest } = await __classPrivateFieldGet(this, _JsonRpcEngineV2_instances, "m", _JsonRpcEngineV2_handle).call(this, request, context);
|
|
107
|
+
// We can't use nullish coalescing here because `result` may be `null`.
|
|
108
|
+
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
|
|
109
|
+
return result === undefined ? await next(finalRequest) : result;
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Destroy the engine. Calls the `destroy()` method of any middleware that has
|
|
114
|
+
* one. Attempting to use the engine after destroying it will throw an error.
|
|
115
|
+
*/
|
|
116
|
+
async destroy() {
|
|
117
|
+
if (__classPrivateFieldGet(this, _JsonRpcEngineV2_isDestroyed, "f")) {
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
__classPrivateFieldSet(this, _JsonRpcEngineV2_isDestroyed, true, "f");
|
|
121
|
+
const destructionPromise = Promise.all(__classPrivateFieldGet(this, _JsonRpcEngineV2_middleware, "f").map(async (middleware) => {
|
|
122
|
+
if (
|
|
123
|
+
// Intentionally using `in` to walk the prototype chain.
|
|
124
|
+
'destroy' in middleware &&
|
|
125
|
+
typeof middleware.destroy === 'function') {
|
|
126
|
+
return middleware.destroy();
|
|
127
|
+
}
|
|
128
|
+
return undefined;
|
|
129
|
+
}));
|
|
130
|
+
__classPrivateFieldSet(this, _JsonRpcEngineV2_middleware, [], "f");
|
|
131
|
+
await destructionPromise;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
exports.JsonRpcEngineV2 = JsonRpcEngineV2;
|
|
135
|
+
_JsonRpcEngineV2_middleware = new WeakMap(), _JsonRpcEngineV2_isDestroyed = new WeakMap(), _JsonRpcEngineV2_instances = new WeakSet(), _JsonRpcEngineV2_handle =
|
|
136
|
+
/**
|
|
137
|
+
* Handle a JSON-RPC request. Throws if a middleware performs an invalid
|
|
138
|
+
* operation. Permits returning an `undefined` result.
|
|
139
|
+
*
|
|
140
|
+
* @param originalRequest - The JSON-RPC request to handle.
|
|
141
|
+
* @param rawContext - The context to pass to the middleware.
|
|
142
|
+
* @returns The result from the middleware.
|
|
143
|
+
*/
|
|
144
|
+
async function _JsonRpcEngineV2_handle(originalRequest, rawContext = new MiddlewareContext_js_1.MiddlewareContext()) {
|
|
145
|
+
__classPrivateFieldGet(this, _JsonRpcEngineV2_instances, "m", _JsonRpcEngineV2_assertIsNotDestroyed).call(this);
|
|
146
|
+
(0, deep_freeze_strict_1.default)(originalRequest);
|
|
147
|
+
const state = {
|
|
148
|
+
request: originalRequest,
|
|
149
|
+
result: undefined,
|
|
150
|
+
};
|
|
151
|
+
const middlewareIterator = __classPrivateFieldGet(this, _JsonRpcEngineV2_instances, "m", _JsonRpcEngineV2_makeMiddlewareIterator).call(this);
|
|
152
|
+
const firstMiddleware = middlewareIterator.next().value;
|
|
153
|
+
const context = MiddlewareContext_js_1.MiddlewareContext.isInstance(rawContext)
|
|
154
|
+
? rawContext
|
|
155
|
+
: new MiddlewareContext_js_1.MiddlewareContext(rawContext);
|
|
156
|
+
const makeNext = __classPrivateFieldGet(this, _JsonRpcEngineV2_instances, "m", _JsonRpcEngineV2_makeNextFactory).call(this, middlewareIterator, state, context);
|
|
157
|
+
const result = await firstMiddleware({
|
|
158
|
+
request: originalRequest,
|
|
159
|
+
context,
|
|
160
|
+
next: makeNext(),
|
|
161
|
+
});
|
|
162
|
+
__classPrivateFieldGet(this, _JsonRpcEngineV2_instances, "m", _JsonRpcEngineV2_updateResult).call(this, result, state);
|
|
163
|
+
return state;
|
|
164
|
+
}, _JsonRpcEngineV2_makeNextFactory = function _JsonRpcEngineV2_makeNextFactory(middlewareIterator, state, context) {
|
|
165
|
+
const makeNext = () => {
|
|
166
|
+
let wasCalled = false;
|
|
167
|
+
const next = async (request = state.request) => {
|
|
168
|
+
if (wasCalled) {
|
|
169
|
+
throw new utils_js_1.JsonRpcEngineError(`Middleware attempted to call next() multiple times for request: ${(0, utils_js_1.stringify)(request)}`);
|
|
170
|
+
}
|
|
171
|
+
wasCalled = true;
|
|
172
|
+
if (request !== state.request) {
|
|
173
|
+
__classPrivateFieldGet(this, _JsonRpcEngineV2_instances, "m", _JsonRpcEngineV2_assertValidNextRequest).call(this, state.request, request);
|
|
174
|
+
state.request = (0, deep_freeze_strict_1.default)(request);
|
|
175
|
+
}
|
|
176
|
+
const { value: nextMiddleware, done } = middlewareIterator.next();
|
|
177
|
+
if (done) {
|
|
178
|
+
// This will cause the last middleware to return `undefined`. See the class
|
|
179
|
+
// JSDoc or package README for more details.
|
|
180
|
+
return undefined;
|
|
181
|
+
}
|
|
182
|
+
const result = await nextMiddleware({
|
|
183
|
+
request,
|
|
184
|
+
context,
|
|
185
|
+
next: makeNext(),
|
|
186
|
+
});
|
|
187
|
+
__classPrivateFieldGet(this, _JsonRpcEngineV2_instances, "m", _JsonRpcEngineV2_updateResult).call(this, result, state);
|
|
188
|
+
return state.result;
|
|
189
|
+
};
|
|
190
|
+
return next;
|
|
191
|
+
};
|
|
192
|
+
return makeNext;
|
|
193
|
+
}, _JsonRpcEngineV2_makeMiddlewareIterator = function _JsonRpcEngineV2_makeMiddlewareIterator() {
|
|
194
|
+
return __classPrivateFieldGet(this, _JsonRpcEngineV2_middleware, "f")[Symbol.iterator]();
|
|
195
|
+
}, _JsonRpcEngineV2_updateResult = function _JsonRpcEngineV2_updateResult(result, state) {
|
|
196
|
+
if ((0, utils_js_1.isNotification)(state.request) && result !== undefined) {
|
|
197
|
+
throw new utils_js_1.JsonRpcEngineError(`Result returned for notification: ${(0, utils_js_1.stringify)(state.request)}`);
|
|
198
|
+
}
|
|
199
|
+
if (result !== undefined && result !== state.result) {
|
|
200
|
+
if (typeof result === 'object' && result !== null) {
|
|
201
|
+
(0, deep_freeze_strict_1.default)(result);
|
|
202
|
+
}
|
|
203
|
+
state.result = result;
|
|
204
|
+
}
|
|
205
|
+
}, _JsonRpcEngineV2_assertValidNextRequest = function _JsonRpcEngineV2_assertValidNextRequest(currentRequest, nextRequest) {
|
|
206
|
+
if (nextRequest.jsonrpc !== currentRequest.jsonrpc) {
|
|
207
|
+
throw new utils_js_1.JsonRpcEngineError(`Middleware attempted to modify readonly property "jsonrpc" for request: ${(0, utils_js_1.stringify)(currentRequest)}`);
|
|
208
|
+
}
|
|
209
|
+
if ((0, utils_1.hasProperty)(nextRequest, 'id') !== (0, utils_1.hasProperty)(currentRequest, 'id') ||
|
|
210
|
+
// @ts-expect-error - "id" does not exist on notifications, but we can still
|
|
211
|
+
// check the value of the property at runtime.
|
|
212
|
+
nextRequest.id !== currentRequest.id) {
|
|
213
|
+
throw new utils_js_1.JsonRpcEngineError(`Middleware attempted to modify readonly property "id" for request: ${(0, utils_js_1.stringify)(currentRequest)}`);
|
|
214
|
+
}
|
|
215
|
+
}, _JsonRpcEngineV2_assertIsNotDestroyed = function _JsonRpcEngineV2_assertIsNotDestroyed() {
|
|
216
|
+
if (__classPrivateFieldGet(this, _JsonRpcEngineV2_isDestroyed, "f")) {
|
|
217
|
+
throw new utils_js_1.JsonRpcEngineError('Engine is destroyed');
|
|
218
|
+
}
|
|
219
|
+
};
|
|
220
|
+
//# sourceMappingURL=JsonRpcEngineV2.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"JsonRpcEngineV2.cjs","sourceRoot":"","sources":["../../src/v2/JsonRpcEngineV2.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAAA,2CAA8C;AAO9C,4EAA4C;AAE5C,sEAAqD;AAMrD,kEAA2D;AAC3D,0CAKoB;AAqGpB,MAAM,cAAc,GAAG,MAAM,CAAC,gBAAgB,CAAC,CAAC;AAShD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,MAAa,eAAe;IAY1B,yCAAyC;IACzC,gDAAgD;IAChD,YAAoB,EAAE,UAAU,EAAwC;;QAVxE,8CAIE;QAEF,uCAAe,KAAK,EAAC;QAKnB,uBAAA,IAAI,+BAAe,CAAC,GAAG,UAAU,CAAC,MAAA,CAAC;IACrC,CA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AC,EAAE,CAClG,CAAC;IACJ,CAAC;AACH,CAAC;IAqDC,IAAI,uBAAA,IAAI,oCAAa,EAAE,CAAC;QACtB,MAAM,IAAI,6BAAkB,CAAC,qBAAqB,CAAC,CAAC;IACtD,CAAC;AACH,CAAC","sourcesContent":["import { hasProperty } from '@metamask/utils';\nimport type {\n Json,\n JsonRpcRequest,\n JsonRpcNotification,\n NonEmptyArray,\n} from '@metamask/utils';\nimport deepFreeze from 'deep-freeze-strict';\n\nimport { deepClone } from './compatibility-utils.js';\nimport type {\n ContextConstraint,\n InferKeyValues,\n MergeContexts,\n} from './MiddlewareContext.js';\nimport { MiddlewareContext } from './MiddlewareContext.js';\nimport {\n isNotification,\n isRequest,\n JsonRpcEngineError,\n stringify,\n} from './utils.js';\nimport type { JsonRpcCall } from './utils.js';\n\n// Helper to forbid `id` on notifications\ntype WithoutId<Request extends JsonRpcCall> = Request & { id?: never };\n\n// Helper to enable JsonRpcCall overload of handle()\ntype MixedParam<Request extends JsonRpcCall> = [\n Extract<Request, JsonRpcRequest>,\n] extends [never]\n ? never\n : [Extract<Request, JsonRpcNotification>] extends [never]\n ? never\n :\n | Extract<Request, JsonRpcRequest>\n | WithoutId<Extract<Request, JsonRpcNotification>>;\n\nexport type ResultConstraint<Request extends JsonRpcCall> =\n Request extends JsonRpcRequest ? Json : void;\n\nexport type Next<Request extends JsonRpcCall> = (\n request?: Readonly<Request>,\n) => Promise<Readonly<ResultConstraint<Request>> | undefined>;\n\nexport type MiddlewareParams<\n Request extends JsonRpcCall = JsonRpcCall,\n Context extends ContextConstraint = MiddlewareContext,\n> = {\n request: Readonly<Request>;\n context: Context;\n next: Next<Request>;\n};\n\nexport type JsonRpcMiddleware<\n Request extends JsonRpcCall = JsonRpcCall,\n Result extends ResultConstraint<Request> = ResultConstraint<Request>,\n Context extends ContextConstraint = MiddlewareContext,\n> = (\n params: MiddlewareParams<Request, Context>,\n) => Readonly<Result> | undefined | Promise<Readonly<Result> | undefined>;\n\ntype RequestState<Request extends JsonRpcCall> = {\n request: Request;\n result: Readonly<ResultConstraint<Request>> | undefined;\n};\n\n/**\n * The options for the JSON-RPC request/notification handling operation.\n */\nexport type HandleOptions<Context extends ContextConstraint> = {\n context?: Context | InferKeyValues<Context>;\n};\n\ntype ConstructorOptions<\n Request extends JsonRpcCall,\n Context extends MiddlewareContext,\n> = {\n middleware: NonEmptyArray<\n JsonRpcMiddleware<Request, ResultConstraint<Request>, Context>\n >;\n};\n\n/**\n * The request type of a middleware.\n */\nexport type RequestOf<Middleware> =\n Middleware extends JsonRpcMiddleware<\n infer Request,\n ResultConstraint<infer Request>,\n // Non-polluting `any` constraint.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n any\n >\n ? Request\n : never;\n\ntype ContextOf<Middleware> =\n // Non-polluting `any` constraint.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n Middleware extends JsonRpcMiddleware<any, ResultConstraint<any>, infer C>\n ? C\n : never;\n\n/**\n * A constraint for {@link JsonRpcMiddleware} generic parameters.\n */\n// Non-polluting `any` constraint.\n/* eslint-disable @typescript-eslint/no-explicit-any */\nexport type MiddlewareConstraint = JsonRpcMiddleware<\n any,\n ResultConstraint<any>,\n MiddlewareContext<any>\n>;\n/* eslint-enable @typescript-eslint/no-explicit-any */\n\n/**\n * The context supertype of a middleware type.\n */\nexport type MergedContextOf<Middleware extends MiddlewareConstraint> =\n MergeContexts<ContextOf<Middleware>>;\n\nconst INVALID_ENGINE = Symbol('Invalid engine');\n\n/**\n * An internal type for invalid engines that explains why the engine is invalid.\n *\n * @template Message - The message explaining why the engine is invalid.\n */\ntype InvalidEngine<Message extends string> = { [INVALID_ENGINE]: Message };\n\n/**\n * A JSON-RPC request and response processor.\n *\n * Give it a stack of middleware, pass it requests, and get back responses.\n *\n * #### Requests vs. notifications\n *\n * JSON-RPC requests come in two flavors:\n *\n * - [Requests](https://www.jsonrpc.org/specification#request_object), i.e. request objects _with_ an `id`\n * - [Notifications](https://www.jsonrpc.org/specification#notification), i.e. request objects _without_ an `id`\n *\n * For requests, one of the engine's middleware must \"end\" the request by returning a non-`undefined` result,\n * or {@link handle} will throw an error:\n *\n * For notifications, on the other hand, one of the engine's middleware must return `undefined` to end the request,\n * and any non-`undefined` return values will cause an error:\n *\n * @template Request - The type of request to handle.\n * @template Result - The type of result to return.\n *\n * @example\n * ```ts\n * const engine = JsonRpcEngineV2.create({\n * middleware,\n * });\n *\n * try {\n * const result = await engine.handle(request);\n * // Handle result\n * } catch (error) {\n * // Handle error\n * }\n * ```\n */\nexport class JsonRpcEngineV2<\n Request extends JsonRpcCall = JsonRpcCall,\n Context extends ContextConstraint = MiddlewareContext,\n> {\n #middleware: Readonly<\n NonEmptyArray<\n JsonRpcMiddleware<Request, ResultConstraint<Request>, Context>\n >\n >;\n\n #isDestroyed = false;\n\n // See .create() for why this is private.\n // eslint-disable-next-line no-restricted-syntax\n private constructor({ middleware }: ConstructorOptions<Request, Context>) {\n this.#middleware = [...middleware];\n }\n\n // We use a static factory method in order to construct a supertype of all middleware contexts,\n // which enables us to instantiate an engine despite different middleware expecting different\n // context types.\n /**\n * Create a new JSON-RPC engine.\n *\n * @throws If the middleware array is empty.\n * @param options - The options for the engine.\n * @param options.middleware - The middleware to use.\n * @returns The JSON-RPC engine.\n */\n static create<\n Middleware extends JsonRpcMiddleware<\n // Non-polluting `any` constraint.\n /* eslint-disable @typescript-eslint/no-explicit-any */\n any,\n ResultConstraint<any>,\n any\n /* eslint-enable @typescript-eslint/no-explicit-any */\n > = JsonRpcMiddleware,\n >({\n middleware,\n }: {\n middleware: Middleware[];\n }): MergedContextOf<Middleware> extends never\n ? InvalidEngine<'Some middleware have incompatible context types'>\n : JsonRpcEngineV2<RequestOf<Middleware>, MergedContextOf<Middleware>> {\n // We can't use NonEmptyArray for the params because it ruins type inference.\n if (middleware.length === 0) {\n throw new JsonRpcEngineError('Middleware array cannot be empty');\n }\n\n type MergedContext = MergedContextOf<Middleware>;\n type InputRequest = RequestOf<Middleware>;\n const mw = middleware as unknown as NonEmptyArray<\n JsonRpcMiddleware<\n InputRequest,\n ResultConstraint<InputRequest>,\n MergedContext\n >\n >;\n\n return new JsonRpcEngineV2<InputRequest, MergedContext>({\n middleware: mw,\n }) as MergedContext extends never\n ? InvalidEngine<'Some middleware have incompatible context types'>\n : JsonRpcEngineV2<InputRequest, MergedContext>;\n }\n\n /**\n * Handle a JSON-RPC request.\n *\n * @param request - The JSON-RPC request to handle.\n * @param options - The options for the handle operation.\n * @param options.context - The context to pass to the middleware.\n * @returns The JSON-RPC response.\n */\n async handle(\n request: Extract<Request, JsonRpcRequest> extends never\n ? never\n : Extract<Request, JsonRpcRequest>,\n options?: HandleOptions<Context>,\n ): Promise<\n Extract<Request, JsonRpcRequest> extends never\n ? never\n : ResultConstraint<Request>\n >;\n\n /**\n * Handle a JSON-RPC notification. Notifications do not return a result.\n *\n * @param notification - The JSON-RPC notification to handle.\n * @param options - The options for the handle operation.\n * @param options.context - The context to pass to the middleware.\n */\n async handle(\n notification: Extract<Request, JsonRpcNotification> extends never\n ? never\n : WithoutId<Extract<Request, JsonRpcNotification>>,\n options?: HandleOptions<Context>,\n ): Promise<\n Extract<Request, JsonRpcNotification> extends never\n ? never\n : ResultConstraint<Request>\n >;\n\n /**\n * Handle a JSON-RPC call, i.e. request or notification. Requests return a\n * result, notifications do not.\n *\n * @param call - The JSON-RPC call to handle.\n * @param options - The options for the handle operation.\n * @param options.context - The context to pass to the middleware.\n * @returns The JSON-RPC response, or `undefined` if the call is a notification.\n */\n async handle(\n call: MixedParam<Request>,\n options?: HandleOptions<Context>,\n ): Promise<ResultConstraint<Request> | void>;\n\n async handle(\n request: Request,\n { context }: HandleOptions<Context> = {},\n ): Promise<ResultConstraint<Request> | void> {\n const isReq = isRequest(request);\n const { result } = await this.#handle(request, context);\n\n if (isReq && result === undefined) {\n throw new JsonRpcEngineError(\n `Nothing ended request: ${stringify(request)}`,\n );\n }\n return deepClone(result) as ResultConstraint<Request>;\n }\n\n /**\n * Handle a JSON-RPC request. Throws if a middleware performs an invalid\n * operation. Permits returning an `undefined` result.\n *\n * @param originalRequest - The JSON-RPC request to handle.\n * @param rawContext - The context to pass to the middleware.\n * @returns The result from the middleware.\n */\n async #handle(\n originalRequest: Request,\n rawContext:\n | Context\n | InferKeyValues<Context> = new MiddlewareContext() as Context,\n ): Promise<RequestState<Request>> {\n this.#assertIsNotDestroyed();\n\n deepFreeze(originalRequest);\n\n const state: RequestState<Request> = {\n request: originalRequest,\n result: undefined,\n };\n const middlewareIterator = this.#makeMiddlewareIterator();\n const firstMiddleware = middlewareIterator.next().value;\n const context = MiddlewareContext.isInstance(rawContext)\n ? rawContext\n : (new MiddlewareContext(rawContext) as Context);\n\n const makeNext = this.#makeNextFactory(middlewareIterator, state, context);\n\n const result = await firstMiddleware({\n request: originalRequest,\n context,\n next: makeNext(),\n });\n this.#updateResult(result, state);\n\n return state;\n }\n\n /**\n * Create a factory of `next()` functions for use with a particular request.\n * The factory is recursive, and a new `next()` is created for each middleware\n * invocation.\n *\n * @param middlewareIterator - The iterator of middleware for the current\n * request.\n * @param state - The current values of the request and result.\n * @param context - The context to pass to the middleware.\n * @returns The `next()` function factory.\n */\n #makeNextFactory(\n middlewareIterator: Iterator<\n JsonRpcMiddleware<Request, ResultConstraint<Request>, Context>\n >,\n state: RequestState<Request>,\n context: Context,\n ): () => Next<Request> {\n const makeNext = (): Next<Request> => {\n let wasCalled = false;\n\n const next = async (\n request: Request = state.request,\n ): Promise<Readonly<ResultConstraint<Request>> | undefined> => {\n if (wasCalled) {\n throw new JsonRpcEngineError(\n `Middleware attempted to call next() multiple times for request: ${stringify(request)}`,\n );\n }\n wasCalled = true;\n\n if (request !== state.request) {\n this.#assertValidNextRequest(state.request, request);\n state.request = deepFreeze(request);\n }\n\n const { value: nextMiddleware, done } = middlewareIterator.next();\n if (done) {\n // This will cause the last middleware to return `undefined`. See the class\n // JSDoc or package README for more details.\n return undefined;\n }\n\n const result = await nextMiddleware({\n request,\n context,\n next: makeNext(),\n });\n this.#updateResult(result, state);\n\n return state.result;\n };\n return next;\n };\n\n return makeNext;\n }\n\n #makeMiddlewareIterator(): Iterator<\n JsonRpcMiddleware<Request, ResultConstraint<Request>, Context>\n > {\n return this.#middleware[Symbol.iterator]();\n }\n\n /**\n * Validate the result from a middleware and, if it's a new value, update the\n * current result.\n *\n * @param result - The result from the middleware.\n * @param state - The current values of the request and result.\n */\n #updateResult(\n result:\n | Readonly<ResultConstraint<Request>>\n | ResultConstraint<Request>\n | void,\n state: RequestState<Request>,\n ): void {\n if (isNotification(state.request) && result !== undefined) {\n throw new JsonRpcEngineError(\n `Result returned for notification: ${stringify(state.request)}`,\n );\n }\n\n if (result !== undefined && result !== state.result) {\n if (typeof result === 'object' && result !== null) {\n deepFreeze(result);\n }\n state.result = result;\n }\n }\n\n /**\n * Assert that a request modified by a middleware is valid.\n *\n * @param currentRequest - The current request.\n * @param nextRequest - The next request.\n */\n #assertValidNextRequest(currentRequest: Request, nextRequest: Request): void {\n if (nextRequest.jsonrpc !== currentRequest.jsonrpc) {\n throw new JsonRpcEngineError(\n `Middleware attempted to modify readonly property \"jsonrpc\" for request: ${stringify(currentRequest)}`,\n );\n }\n if (\n hasProperty(nextRequest, 'id') !== hasProperty(currentRequest, 'id') ||\n // @ts-expect-error - \"id\" does not exist on notifications, but we can still\n // check the value of the property at runtime.\n nextRequest.id !== currentRequest.id\n ) {\n throw new JsonRpcEngineError(\n `Middleware attempted to modify readonly property \"id\" for request: ${stringify(currentRequest)}`,\n );\n }\n }\n\n /**\n * Convert the engine into a JSON-RPC middleware.\n *\n * @returns The JSON-RPC middleware.\n */\n asMiddleware(): JsonRpcMiddleware<\n Request,\n ResultConstraint<Request>,\n Context\n > {\n this.#assertIsNotDestroyed();\n\n return async ({ request, context, next }) => {\n const { result, request: finalRequest } = await this.#handle(\n request,\n context,\n );\n\n // We can't use nullish coalescing here because `result` may be `null`.\n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n return result === undefined ? await next(finalRequest) : result;\n };\n }\n\n /**\n * Destroy the engine. Calls the `destroy()` method of any middleware that has\n * one. Attempting to use the engine after destroying it will throw an error.\n */\n async destroy(): Promise<void> {\n if (this.#isDestroyed) {\n return;\n }\n this.#isDestroyed = true;\n\n const destructionPromise = Promise.all(\n this.#middleware.map(async (middleware) => {\n if (\n // Intentionally using `in` to walk the prototype chain.\n 'destroy' in middleware &&\n typeof middleware.destroy === 'function'\n ) {\n return middleware.destroy();\n }\n return undefined;\n }),\n );\n this.#middleware = [] as never;\n await destructionPromise;\n }\n\n #assertIsNotDestroyed(): void {\n if (this.#isDestroyed) {\n throw new JsonRpcEngineError('Engine is destroyed');\n }\n }\n}\n"]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import type { Json, JsonRpcRequest, JsonRpcNotification } from
|
|
2
|
-
import type { ContextConstraint, InferKeyValues, MergeContexts } from
|
|
3
|
-
import { MiddlewareContext } from
|
|
4
|
-
import type { JsonRpcCall } from
|
|
1
|
+
import type { Json, JsonRpcRequest, JsonRpcNotification } from "@metamask/utils";
|
|
2
|
+
import type { ContextConstraint, InferKeyValues, MergeContexts } from "./MiddlewareContext.cjs";
|
|
3
|
+
import { MiddlewareContext } from "./MiddlewareContext.cjs";
|
|
4
|
+
import type { JsonRpcCall } from "./utils.cjs";
|
|
5
5
|
type WithoutId<Request extends JsonRpcCall> = Request & {
|
|
6
6
|
id?: never;
|
|
7
7
|
};
|
|
@@ -133,4 +133,4 @@ export declare class JsonRpcEngineV2<Request extends JsonRpcCall = JsonRpcCall,
|
|
|
133
133
|
destroy(): Promise<void>;
|
|
134
134
|
}
|
|
135
135
|
export {};
|
|
136
|
-
//# sourceMappingURL=JsonRpcEngineV2.d.
|
|
136
|
+
//# sourceMappingURL=JsonRpcEngineV2.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"JsonRpcEngineV2.d.cts","sourceRoot":"","sources":["../../src/v2/JsonRpcEngineV2.ts"],"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,MAAM,CACV,IAAI,EAAE,UAAU,CAAC,OAAO,CAAC,EACzB,OAAO,CAAC,EAAE,aAAa,CAAC,OAAO,CAAC,GAC/B,OAAO,CAAC,gBAAgB,CAAC,OAAO,CAAC,GAAG,IAAI,CAAC;IA6K5C;;;;OAIG;IACH,YAAY,IAAI,iBAAiB,CAC/B,OAAO,EACP,gBAAgB,CAAC,OAAO,CAAC,EACzB,OAAO,CACR;IAeD;;;OAGG;IACG,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;CA2B/B"}
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import type { Json, JsonRpcRequest, JsonRpcNotification } from "@metamask/utils";
|
|
2
|
+
import type { ContextConstraint, InferKeyValues, MergeContexts } from "./MiddlewareContext.mjs";
|
|
3
|
+
import { MiddlewareContext } from "./MiddlewareContext.mjs";
|
|
4
|
+
import type { JsonRpcCall } from "./utils.mjs";
|
|
5
|
+
type WithoutId<Request extends JsonRpcCall> = Request & {
|
|
6
|
+
id?: never;
|
|
7
|
+
};
|
|
8
|
+
type MixedParam<Request extends JsonRpcCall> = [
|
|
9
|
+
Extract<Request, JsonRpcRequest>
|
|
10
|
+
] extends [never] ? never : [Extract<Request, JsonRpcNotification>] extends [never] ? never : Extract<Request, JsonRpcRequest> | WithoutId<Extract<Request, JsonRpcNotification>>;
|
|
11
|
+
export type ResultConstraint<Request extends JsonRpcCall> = Request extends JsonRpcRequest ? Json : void;
|
|
12
|
+
export type Next<Request extends JsonRpcCall> = (request?: Readonly<Request>) => Promise<Readonly<ResultConstraint<Request>> | undefined>;
|
|
13
|
+
export type MiddlewareParams<Request extends JsonRpcCall = JsonRpcCall, Context extends ContextConstraint = MiddlewareContext> = {
|
|
14
|
+
request: Readonly<Request>;
|
|
15
|
+
context: Context;
|
|
16
|
+
next: Next<Request>;
|
|
17
|
+
};
|
|
18
|
+
export type JsonRpcMiddleware<Request extends JsonRpcCall = JsonRpcCall, Result extends ResultConstraint<Request> = ResultConstraint<Request>, Context extends ContextConstraint = MiddlewareContext> = (params: MiddlewareParams<Request, Context>) => Readonly<Result> | undefined | Promise<Readonly<Result> | undefined>;
|
|
19
|
+
/**
|
|
20
|
+
* The options for the JSON-RPC request/notification handling operation.
|
|
21
|
+
*/
|
|
22
|
+
export type HandleOptions<Context extends ContextConstraint> = {
|
|
23
|
+
context?: Context | InferKeyValues<Context>;
|
|
24
|
+
};
|
|
25
|
+
/**
|
|
26
|
+
* The request type of a middleware.
|
|
27
|
+
*/
|
|
28
|
+
export type RequestOf<Middleware> = Middleware extends JsonRpcMiddleware<infer Request, ResultConstraint<infer Request>, any> ? Request : never;
|
|
29
|
+
type ContextOf<Middleware> = Middleware extends JsonRpcMiddleware<any, ResultConstraint<any>, infer C> ? C : never;
|
|
30
|
+
/**
|
|
31
|
+
* A constraint for {@link JsonRpcMiddleware} generic parameters.
|
|
32
|
+
*/
|
|
33
|
+
export type MiddlewareConstraint = JsonRpcMiddleware<any, ResultConstraint<any>, MiddlewareContext<any>>;
|
|
34
|
+
/**
|
|
35
|
+
* The context supertype of a middleware type.
|
|
36
|
+
*/
|
|
37
|
+
export type MergedContextOf<Middleware extends MiddlewareConstraint> = MergeContexts<ContextOf<Middleware>>;
|
|
38
|
+
declare const INVALID_ENGINE: unique symbol;
|
|
39
|
+
/**
|
|
40
|
+
* An internal type for invalid engines that explains why the engine is invalid.
|
|
41
|
+
*
|
|
42
|
+
* @template Message - The message explaining why the engine is invalid.
|
|
43
|
+
*/
|
|
44
|
+
type InvalidEngine<Message extends string> = {
|
|
45
|
+
[INVALID_ENGINE]: Message;
|
|
46
|
+
};
|
|
47
|
+
/**
|
|
48
|
+
* A JSON-RPC request and response processor.
|
|
49
|
+
*
|
|
50
|
+
* Give it a stack of middleware, pass it requests, and get back responses.
|
|
51
|
+
*
|
|
52
|
+
* #### Requests vs. notifications
|
|
53
|
+
*
|
|
54
|
+
* JSON-RPC requests come in two flavors:
|
|
55
|
+
*
|
|
56
|
+
* - [Requests](https://www.jsonrpc.org/specification#request_object), i.e. request objects _with_ an `id`
|
|
57
|
+
* - [Notifications](https://www.jsonrpc.org/specification#notification), i.e. request objects _without_ an `id`
|
|
58
|
+
*
|
|
59
|
+
* For requests, one of the engine's middleware must "end" the request by returning a non-`undefined` result,
|
|
60
|
+
* or {@link handle} will throw an error:
|
|
61
|
+
*
|
|
62
|
+
* For notifications, on the other hand, one of the engine's middleware must return `undefined` to end the request,
|
|
63
|
+
* and any non-`undefined` return values will cause an error:
|
|
64
|
+
*
|
|
65
|
+
* @template Request - The type of request to handle.
|
|
66
|
+
* @template Result - The type of result to return.
|
|
67
|
+
*
|
|
68
|
+
* @example
|
|
69
|
+
* ```ts
|
|
70
|
+
* const engine = JsonRpcEngineV2.create({
|
|
71
|
+
* middleware,
|
|
72
|
+
* });
|
|
73
|
+
*
|
|
74
|
+
* try {
|
|
75
|
+
* const result = await engine.handle(request);
|
|
76
|
+
* // Handle result
|
|
77
|
+
* } catch (error) {
|
|
78
|
+
* // Handle error
|
|
79
|
+
* }
|
|
80
|
+
* ```
|
|
81
|
+
*/
|
|
82
|
+
export declare class JsonRpcEngineV2<Request extends JsonRpcCall = JsonRpcCall, Context extends ContextConstraint = MiddlewareContext> {
|
|
83
|
+
#private;
|
|
84
|
+
private constructor();
|
|
85
|
+
/**
|
|
86
|
+
* Create a new JSON-RPC engine.
|
|
87
|
+
*
|
|
88
|
+
* @throws If the middleware array is empty.
|
|
89
|
+
* @param options - The options for the engine.
|
|
90
|
+
* @param options.middleware - The middleware to use.
|
|
91
|
+
* @returns The JSON-RPC engine.
|
|
92
|
+
*/
|
|
93
|
+
static create<Middleware extends JsonRpcMiddleware<any, ResultConstraint<any>, any> = JsonRpcMiddleware>({ middleware, }: {
|
|
94
|
+
middleware: Middleware[];
|
|
95
|
+
}): MergedContextOf<Middleware> extends never ? InvalidEngine<'Some middleware have incompatible context types'> : JsonRpcEngineV2<RequestOf<Middleware>, MergedContextOf<Middleware>>;
|
|
96
|
+
/**
|
|
97
|
+
* Handle a JSON-RPC request.
|
|
98
|
+
*
|
|
99
|
+
* @param request - The JSON-RPC request to handle.
|
|
100
|
+
* @param options - The options for the handle operation.
|
|
101
|
+
* @param options.context - The context to pass to the middleware.
|
|
102
|
+
* @returns The JSON-RPC response.
|
|
103
|
+
*/
|
|
104
|
+
handle(request: Extract<Request, JsonRpcRequest> extends never ? never : Extract<Request, JsonRpcRequest>, options?: HandleOptions<Context>): Promise<Extract<Request, JsonRpcRequest> extends never ? never : ResultConstraint<Request>>;
|
|
105
|
+
/**
|
|
106
|
+
* Handle a JSON-RPC notification. Notifications do not return a result.
|
|
107
|
+
*
|
|
108
|
+
* @param notification - The JSON-RPC notification to handle.
|
|
109
|
+
* @param options - The options for the handle operation.
|
|
110
|
+
* @param options.context - The context to pass to the middleware.
|
|
111
|
+
*/
|
|
112
|
+
handle(notification: Extract<Request, JsonRpcNotification> extends never ? never : WithoutId<Extract<Request, JsonRpcNotification>>, options?: HandleOptions<Context>): Promise<Extract<Request, JsonRpcNotification> extends never ? never : ResultConstraint<Request>>;
|
|
113
|
+
/**
|
|
114
|
+
* Handle a JSON-RPC call, i.e. request or notification. Requests return a
|
|
115
|
+
* result, notifications do not.
|
|
116
|
+
*
|
|
117
|
+
* @param call - The JSON-RPC call to handle.
|
|
118
|
+
* @param options - The options for the handle operation.
|
|
119
|
+
* @param options.context - The context to pass to the middleware.
|
|
120
|
+
* @returns The JSON-RPC response, or `undefined` if the call is a notification.
|
|
121
|
+
*/
|
|
122
|
+
handle(call: MixedParam<Request>, options?: HandleOptions<Context>): Promise<ResultConstraint<Request> | void>;
|
|
123
|
+
/**
|
|
124
|
+
* Convert the engine into a JSON-RPC middleware.
|
|
125
|
+
*
|
|
126
|
+
* @returns The JSON-RPC middleware.
|
|
127
|
+
*/
|
|
128
|
+
asMiddleware(): JsonRpcMiddleware<Request, ResultConstraint<Request>, Context>;
|
|
129
|
+
/**
|
|
130
|
+
* Destroy the engine. Calls the `destroy()` method of any middleware that has
|
|
131
|
+
* one. Attempting to use the engine after destroying it will throw an error.
|
|
132
|
+
*/
|
|
133
|
+
destroy(): Promise<void>;
|
|
134
|
+
}
|
|
135
|
+
export {};
|
|
136
|
+
//# sourceMappingURL=JsonRpcEngineV2.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"JsonRpcEngineV2.d.mts","sourceRoot":"","sources":["../../src/v2/JsonRpcEngineV2.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,IAAI,EACJ,cAAc,EACd,mBAAmB,EAEpB,wBAAwB;AAIzB,OAAO,KAAK,EACV,iBAAiB,EACjB,cAAc,EACd,aAAa,EACd,gCAA+B;AAChC,OAAO,EAAE,iBAAiB,EAAE,gCAA+B;AAO3D,OAAO,KAAK,EAAE,WAAW,EAAE,oBAAmB;AAG9C,KAAK,SAAS,CAAC,OAAO,SAAS,WAAW,IAAI,OAAO,GAAG;IAAE,EAAE,CAAC,EAAE,KAAK,CAAA;CAAE,CAAC;AAGvE,KAAK,UAAU,CAAC,OAAO,SAAS,WAAW,IAAI;IAC7C,OAAO,CAAC,OAAO,EAAE,cAAc,CAAC;CACjC,SAAS,CAAC,KAAK,CAAC,GACb,KAAK,GACL,CAAC,OAAO,CAAC,OAAO,EAAE,mBAAmB,CAAC,CAAC,SAAS,CAAC,KAAK,CAAC,GACrD,KAAK,GAED,OAAO,CAAC,OAAO,EAAE,cAAc,CAAC,GAChC,SAAS,CAAC,OAAO,CAAC,OAAO,EAAE,mBAAmB,CAAC,CAAC,CAAC;AAE3D,MAAM,MAAM,gBAAgB,CAAC,OAAO,SAAS,WAAW,IACtD,OAAO,SAAS,cAAc,GAAG,IAAI,GAAG,IAAI,CAAC;AAE/C,MAAM,MAAM,IAAI,CAAC,OAAO,SAAS,WAAW,IAAI,CAC9C,OAAO,CAAC,EAAE,QAAQ,CAAC,OAAO,CAAC,KACxB,OAAO,CAAC,QAAQ,CAAC,gBAAgB,CAAC,OAAO,CAAC,CAAC,GAAG,SAAS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GAC7D,KAAK,GACL,SAAS,CAAC,OAAO,CAAC,OAAO,EAAE,mBAAmB,CAAC,CAAC,EACpD,OAAO,CAAC,EAAE,aAAa,CAAC,OAAO,CAAC,GAC/B,OAAO,CACR,OAAO,CAAC,OAAO,EAAE,mBAAmB,CAAC,SAAS,KAAK,GAC/C,KAAK,GACL,gBAAgB,CAAC,OAAO,CAAC,CAC9B;IAED;;;;;;;;OAQG;IACG,MAAM,CACV,IAAI,EAAE,UAAU,CAAC,OAAO,CAAC,EACzB,OAAO,CAAC,EAAE,aAAa,CAAC,OAAO,CAAC,GAC/B,OAAO,CAAC,gBAAgB,CAAC,OAAO,CAAC,GAAG,IAAI,CAAC;IA6K5C;;;;OAIG;IACH,YAAY,IAAI,iBAAiB,CAC/B,OAAO,EACP,gBAAgB,CAAC,OAAO,CAAC,EACzB,OAAO,CACR;IAeD;;;OAGG;IACG,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;CA2B/B"}
|
|
@@ -10,11 +10,18 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
|
|
|
10
10
|
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
11
11
|
};
|
|
12
12
|
var _JsonRpcEngineV2_instances, _JsonRpcEngineV2_middleware, _JsonRpcEngineV2_isDestroyed, _JsonRpcEngineV2_handle, _JsonRpcEngineV2_makeNextFactory, _JsonRpcEngineV2_makeMiddlewareIterator, _JsonRpcEngineV2_updateResult, _JsonRpcEngineV2_assertValidNextRequest, _JsonRpcEngineV2_assertIsNotDestroyed;
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
13
|
+
function $importDefault(module) {
|
|
14
|
+
if (module?.__esModule) {
|
|
15
|
+
return module.default;
|
|
16
|
+
}
|
|
17
|
+
return module;
|
|
18
|
+
}
|
|
19
|
+
import { hasProperty } from "@metamask/utils";
|
|
20
|
+
import $deepFreeze from "deep-freeze-strict";
|
|
21
|
+
const deepFreeze = $importDefault($deepFreeze);
|
|
22
|
+
import { deepClone } from "./compatibility-utils.mjs";
|
|
23
|
+
import { MiddlewareContext } from "./MiddlewareContext.mjs";
|
|
24
|
+
import { isNotification, isRequest, JsonRpcEngineError, stringify } from "./utils.mjs";
|
|
18
25
|
const INVALID_ENGINE = Symbol('Invalid engine');
|
|
19
26
|
/**
|
|
20
27
|
* A JSON-RPC request and response processor.
|
|
@@ -82,9 +89,6 @@ export class JsonRpcEngineV2 {
|
|
|
82
89
|
});
|
|
83
90
|
}
|
|
84
91
|
async handle(request, { context } = {}) {
|
|
85
|
-
// This error appeared when upgrading to TypeScript 7.
|
|
86
|
-
// @ts-expect-error: TS2345: Argument of type 'JsonRpcCall' is not assignable
|
|
87
|
-
// to parameter of type 'JsonRpcCall<Record<string, Json>> | Readonly<JsonRpcCall<Record<string, Json>>>'.
|
|
88
92
|
const isReq = isRequest(request);
|
|
89
93
|
const { result } = await __classPrivateFieldGet(this, _JsonRpcEngineV2_instances, "m", _JsonRpcEngineV2_handle).call(this, request, context);
|
|
90
94
|
if (isReq && result === undefined) {
|
|
@@ -213,4 +217,4 @@ async function _JsonRpcEngineV2_handle(originalRequest, rawContext = new Middlew
|
|
|
213
217
|
throw new JsonRpcEngineError('Engine is destroyed');
|
|
214
218
|
}
|
|
215
219
|
};
|
|
216
|
-
//# sourceMappingURL=JsonRpcEngineV2.
|
|
220
|
+
//# sourceMappingURL=JsonRpcEngineV2.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"JsonRpcEngineV2.mjs","sourceRoot":"","sources":["../../src/v2/JsonRpcEngineV2.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAAA,OAAO,EAAE,WAAW,EAAE,wBAAwB;AAO9C,OAAO,WAAU,2BAA2B;;AAE5C,OAAO,EAAE,SAAS,EAAE,kCAAiC;AAMrD,OAAO,EAAE,iBAAiB,EAAE,gCAA+B;AAC3D,OAAO,EACL,cAAc,EAC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,CAAC;IACD,IACE,WAAW,CAAC,WAAW,EAAE,IAAI,CAAC,KAAK,WAAW,CAAC,cAAc,EAAE,IAAI,CAAC;QACpE,4EAA4E;QAC5E,8CAA8C;QAC9C,WAAW,CAAC,EAAE,KAAK,cAAc,CAAC,EAAE,EACpC,CAAC;QACD,MAAM,IAAI,kBAAkB,CAC1B,sEAAsE,SAAS,CAAC,cAAc,CAAC,EAAE,CAClG,CAAC;IACJ,CAAC;AACH,CAAC;IAqDC,IAAI,uBAAA,IAAI,oCAAa,EAAE,CAAC;QACtB,MAAM,IAAI,kBAAkB,CAAC,qBAAqB,CAAC,CAAC;IACtD,CAAC;AACH,CAAC","sourcesContent":["import { hasProperty } from '@metamask/utils';\nimport type {\n Json,\n JsonRpcRequest,\n JsonRpcNotification,\n NonEmptyArray,\n} from '@metamask/utils';\nimport deepFreeze from 'deep-freeze-strict';\n\nimport { deepClone } from './compatibility-utils.js';\nimport type {\n ContextConstraint,\n InferKeyValues,\n MergeContexts,\n} from './MiddlewareContext.js';\nimport { MiddlewareContext } from './MiddlewareContext.js';\nimport {\n isNotification,\n isRequest,\n JsonRpcEngineError,\n stringify,\n} from './utils.js';\nimport type { JsonRpcCall } from './utils.js';\n\n// Helper to forbid `id` on notifications\ntype WithoutId<Request extends JsonRpcCall> = Request & { id?: never };\n\n// Helper to enable JsonRpcCall overload of handle()\ntype MixedParam<Request extends JsonRpcCall> = [\n Extract<Request, JsonRpcRequest>,\n] extends [never]\n ? never\n : [Extract<Request, JsonRpcNotification>] extends [never]\n ? never\n :\n | Extract<Request, JsonRpcRequest>\n | WithoutId<Extract<Request, JsonRpcNotification>>;\n\nexport type ResultConstraint<Request extends JsonRpcCall> =\n Request extends JsonRpcRequest ? Json : void;\n\nexport type Next<Request extends JsonRpcCall> = (\n request?: Readonly<Request>,\n) => Promise<Readonly<ResultConstraint<Request>> | undefined>;\n\nexport type MiddlewareParams<\n Request extends JsonRpcCall = JsonRpcCall,\n Context extends ContextConstraint = MiddlewareContext,\n> = {\n request: Readonly<Request>;\n context: Context;\n next: Next<Request>;\n};\n\nexport type JsonRpcMiddleware<\n Request extends JsonRpcCall = JsonRpcCall,\n Result extends ResultConstraint<Request> = ResultConstraint<Request>,\n Context extends ContextConstraint = MiddlewareContext,\n> = (\n params: MiddlewareParams<Request, Context>,\n) => Readonly<Result> | undefined | Promise<Readonly<Result> | undefined>;\n\ntype RequestState<Request extends JsonRpcCall> = {\n request: Request;\n result: Readonly<ResultConstraint<Request>> | undefined;\n};\n\n/**\n * The options for the JSON-RPC request/notification handling operation.\n */\nexport type HandleOptions<Context extends ContextConstraint> = {\n context?: Context | InferKeyValues<Context>;\n};\n\ntype ConstructorOptions<\n Request extends JsonRpcCall,\n Context extends MiddlewareContext,\n> = {\n middleware: NonEmptyArray<\n JsonRpcMiddleware<Request, ResultConstraint<Request>, Context>\n >;\n};\n\n/**\n * The request type of a middleware.\n */\nexport type RequestOf<Middleware> =\n Middleware extends JsonRpcMiddleware<\n infer Request,\n ResultConstraint<infer Request>,\n // Non-polluting `any` constraint.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n any\n >\n ? Request\n : never;\n\ntype ContextOf<Middleware> =\n // Non-polluting `any` constraint.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n Middleware extends JsonRpcMiddleware<any, ResultConstraint<any>, infer C>\n ? C\n : never;\n\n/**\n * A constraint for {@link JsonRpcMiddleware} generic parameters.\n */\n// Non-polluting `any` constraint.\n/* eslint-disable @typescript-eslint/no-explicit-any */\nexport type MiddlewareConstraint = JsonRpcMiddleware<\n any,\n ResultConstraint<any>,\n MiddlewareContext<any>\n>;\n/* eslint-enable @typescript-eslint/no-explicit-any */\n\n/**\n * The context supertype of a middleware type.\n */\nexport type MergedContextOf<Middleware extends MiddlewareConstraint> =\n MergeContexts<ContextOf<Middleware>>;\n\nconst INVALID_ENGINE = Symbol('Invalid engine');\n\n/**\n * An internal type for invalid engines that explains why the engine is invalid.\n *\n * @template Message - The message explaining why the engine is invalid.\n */\ntype InvalidEngine<Message extends string> = { [INVALID_ENGINE]: Message };\n\n/**\n * A JSON-RPC request and response processor.\n *\n * Give it a stack of middleware, pass it requests, and get back responses.\n *\n * #### Requests vs. notifications\n *\n * JSON-RPC requests come in two flavors:\n *\n * - [Requests](https://www.jsonrpc.org/specification#request_object), i.e. request objects _with_ an `id`\n * - [Notifications](https://www.jsonrpc.org/specification#notification), i.e. request objects _without_ an `id`\n *\n * For requests, one of the engine's middleware must \"end\" the request by returning a non-`undefined` result,\n * or {@link handle} will throw an error:\n *\n * For notifications, on the other hand, one of the engine's middleware must return `undefined` to end the request,\n * and any non-`undefined` return values will cause an error:\n *\n * @template Request - The type of request to handle.\n * @template Result - The type of result to return.\n *\n * @example\n * ```ts\n * const engine = JsonRpcEngineV2.create({\n * middleware,\n * });\n *\n * try {\n * const result = await engine.handle(request);\n * // Handle result\n * } catch (error) {\n * // Handle error\n * }\n * ```\n */\nexport class JsonRpcEngineV2<\n Request extends JsonRpcCall = JsonRpcCall,\n Context extends ContextConstraint = MiddlewareContext,\n> {\n #middleware: Readonly<\n NonEmptyArray<\n JsonRpcMiddleware<Request, ResultConstraint<Request>, Context>\n >\n >;\n\n #isDestroyed = false;\n\n // See .create() for why this is private.\n // eslint-disable-next-line no-restricted-syntax\n private constructor({ middleware }: ConstructorOptions<Request, Context>) {\n this.#middleware = [...middleware];\n }\n\n // We use a static factory method in order to construct a supertype of all middleware contexts,\n // which enables us to instantiate an engine despite different middleware expecting different\n // context types.\n /**\n * Create a new JSON-RPC engine.\n *\n * @throws If the middleware array is empty.\n * @param options - The options for the engine.\n * @param options.middleware - The middleware to use.\n * @returns The JSON-RPC engine.\n */\n static create<\n Middleware extends JsonRpcMiddleware<\n // Non-polluting `any` constraint.\n /* eslint-disable @typescript-eslint/no-explicit-any */\n any,\n ResultConstraint<any>,\n any\n /* eslint-enable @typescript-eslint/no-explicit-any */\n > = JsonRpcMiddleware,\n >({\n middleware,\n }: {\n middleware: Middleware[];\n }): MergedContextOf<Middleware> extends never\n ? InvalidEngine<'Some middleware have incompatible context types'>\n : JsonRpcEngineV2<RequestOf<Middleware>, MergedContextOf<Middleware>> {\n // We can't use NonEmptyArray for the params because it ruins type inference.\n if (middleware.length === 0) {\n throw new JsonRpcEngineError('Middleware array cannot be empty');\n }\n\n type MergedContext = MergedContextOf<Middleware>;\n type InputRequest = RequestOf<Middleware>;\n const mw = middleware as unknown as NonEmptyArray<\n JsonRpcMiddleware<\n InputRequest,\n ResultConstraint<InputRequest>,\n MergedContext\n >\n >;\n\n return new JsonRpcEngineV2<InputRequest, MergedContext>({\n middleware: mw,\n }) as MergedContext extends never\n ? InvalidEngine<'Some middleware have incompatible context types'>\n : JsonRpcEngineV2<InputRequest, MergedContext>;\n }\n\n /**\n * Handle a JSON-RPC request.\n *\n * @param request - The JSON-RPC request to handle.\n * @param options - The options for the handle operation.\n * @param options.context - The context to pass to the middleware.\n * @returns The JSON-RPC response.\n */\n async handle(\n request: Extract<Request, JsonRpcRequest> extends never\n ? never\n : Extract<Request, JsonRpcRequest>,\n options?: HandleOptions<Context>,\n ): Promise<\n Extract<Request, JsonRpcRequest> extends never\n ? never\n : ResultConstraint<Request>\n >;\n\n /**\n * Handle a JSON-RPC notification. Notifications do not return a result.\n *\n * @param notification - The JSON-RPC notification to handle.\n * @param options - The options for the handle operation.\n * @param options.context - The context to pass to the middleware.\n */\n async handle(\n notification: Extract<Request, JsonRpcNotification> extends never\n ? never\n : WithoutId<Extract<Request, JsonRpcNotification>>,\n options?: HandleOptions<Context>,\n ): Promise<\n Extract<Request, JsonRpcNotification> extends never\n ? never\n : ResultConstraint<Request>\n >;\n\n /**\n * Handle a JSON-RPC call, i.e. request or notification. Requests return a\n * result, notifications do not.\n *\n * @param call - The JSON-RPC call to handle.\n * @param options - The options for the handle operation.\n * @param options.context - The context to pass to the middleware.\n * @returns The JSON-RPC response, or `undefined` if the call is a notification.\n */\n async handle(\n call: MixedParam<Request>,\n options?: HandleOptions<Context>,\n ): Promise<ResultConstraint<Request> | void>;\n\n async handle(\n request: Request,\n { context }: HandleOptions<Context> = {},\n ): Promise<ResultConstraint<Request> | void> {\n const isReq = isRequest(request);\n const { result } = await this.#handle(request, context);\n\n if (isReq && result === undefined) {\n throw new JsonRpcEngineError(\n `Nothing ended request: ${stringify(request)}`,\n );\n }\n return deepClone(result) as ResultConstraint<Request>;\n }\n\n /**\n * Handle a JSON-RPC request. Throws if a middleware performs an invalid\n * operation. Permits returning an `undefined` result.\n *\n * @param originalRequest - The JSON-RPC request to handle.\n * @param rawContext - The context to pass to the middleware.\n * @returns The result from the middleware.\n */\n async #handle(\n originalRequest: Request,\n rawContext:\n | Context\n | InferKeyValues<Context> = new MiddlewareContext() as Context,\n ): Promise<RequestState<Request>> {\n this.#assertIsNotDestroyed();\n\n deepFreeze(originalRequest);\n\n const state: RequestState<Request> = {\n request: originalRequest,\n result: undefined,\n };\n const middlewareIterator = this.#makeMiddlewareIterator();\n const firstMiddleware = middlewareIterator.next().value;\n const context = MiddlewareContext.isInstance(rawContext)\n ? rawContext\n : (new MiddlewareContext(rawContext) as Context);\n\n const makeNext = this.#makeNextFactory(middlewareIterator, state, context);\n\n const result = await firstMiddleware({\n request: originalRequest,\n context,\n next: makeNext(),\n });\n this.#updateResult(result, state);\n\n return state;\n }\n\n /**\n * Create a factory of `next()` functions for use with a particular request.\n * The factory is recursive, and a new `next()` is created for each middleware\n * invocation.\n *\n * @param middlewareIterator - The iterator of middleware for the current\n * request.\n * @param state - The current values of the request and result.\n * @param context - The context to pass to the middleware.\n * @returns The `next()` function factory.\n */\n #makeNextFactory(\n middlewareIterator: Iterator<\n JsonRpcMiddleware<Request, ResultConstraint<Request>, Context>\n >,\n state: RequestState<Request>,\n context: Context,\n ): () => Next<Request> {\n const makeNext = (): Next<Request> => {\n let wasCalled = false;\n\n const next = async (\n request: Request = state.request,\n ): Promise<Readonly<ResultConstraint<Request>> | undefined> => {\n if (wasCalled) {\n throw new JsonRpcEngineError(\n `Middleware attempted to call next() multiple times for request: ${stringify(request)}`,\n );\n }\n wasCalled = true;\n\n if (request !== state.request) {\n this.#assertValidNextRequest(state.request, request);\n state.request = deepFreeze(request);\n }\n\n const { value: nextMiddleware, done } = middlewareIterator.next();\n if (done) {\n // This will cause the last middleware to return `undefined`. See the class\n // JSDoc or package README for more details.\n return undefined;\n }\n\n const result = await nextMiddleware({\n request,\n context,\n next: makeNext(),\n });\n this.#updateResult(result, state);\n\n return state.result;\n };\n return next;\n };\n\n return makeNext;\n }\n\n #makeMiddlewareIterator(): Iterator<\n JsonRpcMiddleware<Request, ResultConstraint<Request>, Context>\n > {\n return this.#middleware[Symbol.iterator]();\n }\n\n /**\n * Validate the result from a middleware and, if it's a new value, update the\n * current result.\n *\n * @param result - The result from the middleware.\n * @param state - The current values of the request and result.\n */\n #updateResult(\n result:\n | Readonly<ResultConstraint<Request>>\n | ResultConstraint<Request>\n | void,\n state: RequestState<Request>,\n ): void {\n if (isNotification(state.request) && result !== undefined) {\n throw new JsonRpcEngineError(\n `Result returned for notification: ${stringify(state.request)}`,\n );\n }\n\n if (result !== undefined && result !== state.result) {\n if (typeof result === 'object' && result !== null) {\n deepFreeze(result);\n }\n state.result = result;\n }\n }\n\n /**\n * Assert that a request modified by a middleware is valid.\n *\n * @param currentRequest - The current request.\n * @param nextRequest - The next request.\n */\n #assertValidNextRequest(currentRequest: Request, nextRequest: Request): void {\n if (nextRequest.jsonrpc !== currentRequest.jsonrpc) {\n throw new JsonRpcEngineError(\n `Middleware attempted to modify readonly property \"jsonrpc\" for request: ${stringify(currentRequest)}`,\n );\n }\n if (\n hasProperty(nextRequest, 'id') !== hasProperty(currentRequest, 'id') ||\n // @ts-expect-error - \"id\" does not exist on notifications, but we can still\n // check the value of the property at runtime.\n nextRequest.id !== currentRequest.id\n ) {\n throw new JsonRpcEngineError(\n `Middleware attempted to modify readonly property \"id\" for request: ${stringify(currentRequest)}`,\n );\n }\n }\n\n /**\n * Convert the engine into a JSON-RPC middleware.\n *\n * @returns The JSON-RPC middleware.\n */\n asMiddleware(): JsonRpcMiddleware<\n Request,\n ResultConstraint<Request>,\n Context\n > {\n this.#assertIsNotDestroyed();\n\n return async ({ request, context, next }) => {\n const { result, request: finalRequest } = await this.#handle(\n request,\n context,\n );\n\n // We can't use nullish coalescing here because `result` may be `null`.\n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n return result === undefined ? await next(finalRequest) : result;\n };\n }\n\n /**\n * Destroy the engine. Calls the `destroy()` method of any middleware that has\n * one. Attempting to use the engine after destroying it will throw an error.\n */\n async destroy(): Promise<void> {\n if (this.#isDestroyed) {\n return;\n }\n this.#isDestroyed = true;\n\n const destructionPromise = Promise.all(\n this.#middleware.map(async (middleware) => {\n if (\n // Intentionally using `in` to walk the prototype chain.\n 'destroy' in middleware &&\n typeof middleware.destroy === 'function'\n ) {\n return middleware.destroy();\n }\n return undefined;\n }),\n );\n this.#middleware = [] as never;\n await destructionPromise;\n }\n\n #assertIsNotDestroyed(): void {\n if (this.#isDestroyed) {\n throw new JsonRpcEngineError('Engine is destroyed');\n }\n }\n}\n"]}
|