@metamask-previews/json-rpc-engine 10.1.1-preview-eee46d4b → 10.1.1-preview-ac95634

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 CHANGED
@@ -9,7 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
9
9
 
10
10
  ### Added
11
11
 
12
- - `JsonRpcEngineV2` ([#6176](https://github.com/MetaMask/core/pull/6176), [#6971](https://github.com/MetaMask/core/pull/6971), [#6975](https://github.com/MetaMask/core/pull/6975), [#6990](https://github.com/MetaMask/core/pull/6990))
12
+ - `JsonRpcEngineV2` ([#6176](https://github.com/MetaMask/core/pull/6176), [#6971](https://github.com/MetaMask/core/pull/6971), [#6975](https://github.com/MetaMask/core/pull/6975), [#6990](https://github.com/MetaMask/core/pull/6990), [#6991](https://github.com/MetaMask/core/pull/6991), [#7032](https://github.com/MetaMask/core/pull/7032))
13
13
  - This is a complete rewrite of `JsonRpcEngine`, intended to replace the original implementation.
14
14
  See the readme for details.
15
15
 
package/README.md CHANGED
@@ -81,8 +81,15 @@ await server.handle(notification);
81
81
 
82
82
  ### Legacy compatibility
83
83
 
84
- Use the `asLegacyMiddleware` function to use a `JsonRpcEngineV2` as a
85
- middleware in a legacy `JsonRpcEngine`:
84
+ Use `asLegacyMiddleware()` to convert a `JsonRpcEngineV2` or one or more V2 middleware into a legacy middleware.
85
+
86
+ #### Context propagation
87
+
88
+ In keeping with the conventions of the legacy engine, non-JSON-RPC string properties of the `context` will be
89
+ copied over to the request once the V2 engine is done with the request. _Note that **only `string` keys** of
90
+ the `context` will be copied over._
91
+
92
+ #### Converting a V2 engine
86
93
 
87
94
  ```ts
88
95
  import {
@@ -102,9 +109,31 @@ const v2Engine = JsonRpcEngineV2.create({
102
109
  legacyEngine.push(asLegacyMiddleware(v2Engine));
103
110
  ```
104
111
 
105
- In keeping with the conventions of the legacy engine, non-JSON-RPC string properties of the `context` will be
106
- copied over to the request once the V2 engine is done with the request. _Note that **only `string` keys** of
107
- the `context` will be copied over._
112
+ #### Converting V2 middleware
113
+
114
+ ```ts
115
+ import {
116
+ asLegacyMiddleware,
117
+ type JsonRpcMiddleware,
118
+ } from '@metamask/json-rpc-engine/v2';
119
+ import { JsonRpcEngine } from '@metamask/json-rpc-engine';
120
+
121
+ // Convert a single V2 middleware
122
+ const middleware1: JsonRpcMiddleware<JsonRpcRequest> = ({ request }) => {
123
+ /* ... */
124
+ };
125
+
126
+ const legacyEngine = new JsonRpcEngine();
127
+ legacyEngine.push(asLegacyMiddleware(middleware1));
128
+
129
+ // Convert multiple V2 middlewares at once
130
+ const middleware2: JsonRpcMiddleware<JsonRpcRequest> = ({ context, next }) => {
131
+ /* ... */
132
+ };
133
+
134
+ const legacyEngine2 = new JsonRpcEngine();
135
+ legacyEngine2.push(asLegacyMiddleware(middleware1, middleware2));
136
+ ```
108
137
 
109
138
  ### Middleware
110
139
 
@@ -3,15 +3,19 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.asV2Middleware = void 0;
4
4
  const rpc_errors_1 = require("@metamask/rpc-errors");
5
5
  const utils_1 = require("@metamask/utils");
6
+ const mergeMiddleware_1 = require("./mergeMiddleware.cjs");
6
7
  const compatibility_utils_1 = require("./v2/compatibility-utils.cjs");
7
8
  /**
8
- * Convert a legacy {@link JsonRpcEngine} into a {@link JsonRpcEngineV2} middleware.
9
+ * The asV2Middleware implementation.
9
10
  *
10
- * @param engine - The legacy engine to convert.
11
+ * @param engineOrMiddleware - A legacy engine or legacy middleware.
12
+ * @param rest - Any additional legacy middleware when the first argument is a middleware.
11
13
  * @returns The {@link JsonRpcEngineV2} middleware.
12
14
  */
13
- function asV2Middleware(engine) {
14
- const middleware = engine.asMiddleware();
15
+ function asV2Middleware(engineOrMiddleware, ...rest) {
16
+ const legacyMiddleware = typeof engineOrMiddleware === 'function'
17
+ ? (0, mergeMiddleware_1.mergeMiddleware)([engineOrMiddleware, ...rest])
18
+ : engineOrMiddleware.asMiddleware();
15
19
  return async ({ request, context, next }) => {
16
20
  const req = (0, compatibility_utils_1.deepClone)(request);
17
21
  (0, compatibility_utils_1.propagateToRequest)(req, context);
@@ -32,7 +36,7 @@ function asV2Middleware(engine) {
32
36
  // legacyNext will always be passed a callback, so cb can never be
33
37
  // undefined.
34
38
  const legacyNext = ((cb) => cb(end));
35
- middleware(req, res, legacyNext, end);
39
+ legacyMiddleware(req, res, legacyNext, end);
36
40
  });
37
41
  (0, compatibility_utils_1.propagateToContext)(req, context);
38
42
  if ((0, utils_1.hasProperty)(response, 'error')) {
@@ -1 +1 @@
1
- {"version":3,"file":"asV2Middleware.cjs","sourceRoot":"","sources":["../src/asV2Middleware.ts"],"names":[],"mappings":";;;AAAA,qDAAsD;AAEtD,2CAIyB;AAOzB,sEAMkC;AASlC;;;;;GAKG;AACH,SAAgB,cAAc,CAG5B,MAAqB;IACrB,MAAM,UAAU,GAAG,MAAM,CAAC,YAAY,EAAE,CAAC;IACzC,OAAO,KAAK,EAAE,EAAE,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,EAAE,EAAE;QAC1C,MAAM,GAAG,GAAG,IAAA,+BAAS,EAAC,OAAO,CAA2B,CAAC;QACzD,IAAA,wCAAkB,EAAC,GAAG,EAAE,OAAO,CAAC,CAAC;QAEjC,MAAM,QAAQ,GAAG,MAAM,IAAI,OAAO,CAAkB,CAAC,OAAO,EAAE,EAAE;YAC9D,gEAAgE;YAChE,cAAc;YACd,MAAM,GAAG,GAAG;gBACV,OAAO,EAAE,KAAc;gBACvB,EAAE,EAAE,GAAG,CAAC,EAAE;aACQ,CAAC;YAErB,MAAM,GAAG,GAA6B,CAAC,KAAK,EAAE,EAAE;gBAC9C,IAAI,KAAK,KAAK,SAAS,EAAE;oBACtB,GAAsB,CAAC,KAAK,GAAG,IAAA,2BAAc,EAAC,KAAK,CAAC,CAAC;iBACvD;gBACD,OAAO,CAAC,GAAG,CAAC,CAAC;YACf,CAAC,CAAC;YAEF,uEAAuE;YACvE,kEAAkE;YAClE,aAAa;YACb,MAAM,UAAU,GAAG,CAAC,CAAC,EAA4B,EAAE,EAAE,CACnD,EAAE,CAAC,GAAG,CAAC,CAA8B,CAAC;YAExC,UAAU,CAAC,GAAG,EAAE,GAAG,EAAE,UAAU,EAAE,GAAG,CAAC,CAAC;QACxC,CAAC,CAAC,CAAC;QACH,IAAA,wCAAkB,EAAC,GAAG,EAAE,OAAO,CAAC,CAAC;QAEjC,IAAI,IAAA,mBAAW,EAAC,QAAQ,EAAE,OAAO,CAAC,EAAE;YAClC,MAAM,IAAA,sCAAgB,EAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;SACxC;aAAM,IAAI,IAAA,mBAAW,EAAC,QAAQ,EAAE,QAAQ,CAAC,EAAE;YAC1C,OAAO,QAAQ,CAAC,MAAmC,CAAC;SACrD;QACD,OAAO,IAAI,CAAC,IAAA,uCAAiB,EAAC,GAAc,CAAC,CAAC,CAAC;IACjD,CAAC,CAAC;AACJ,CAAC;AAzCD,wCAyCC","sourcesContent":["import { serializeError } from '@metamask/rpc-errors';\nimport type { JsonRpcFailure, JsonRpcResponse } from '@metamask/utils';\nimport {\n hasProperty,\n type JsonRpcParams,\n type JsonRpcRequest,\n} from '@metamask/utils';\n\nimport type {\n JsonRpcEngine,\n JsonRpcEngineEndCallback,\n JsonRpcEngineNextCallback,\n} from './JsonRpcEngine';\nimport {\n deepClone,\n fromLegacyRequest,\n propagateToContext,\n propagateToRequest,\n unserializeError,\n} from './v2/compatibility-utils';\nimport type {\n // JsonRpcEngineV2 is used in docs.\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n JsonRpcEngineV2,\n JsonRpcMiddleware,\n ResultConstraint,\n} from './v2/JsonRpcEngineV2';\n\n/**\n * Convert a legacy {@link JsonRpcEngine} into a {@link JsonRpcEngineV2} middleware.\n *\n * @param engine - The legacy engine to convert.\n * @returns The {@link JsonRpcEngineV2} middleware.\n */\nexport function asV2Middleware<\n Params extends JsonRpcParams,\n Request extends JsonRpcRequest<Params>,\n>(engine: JsonRpcEngine): JsonRpcMiddleware<Request> {\n const middleware = engine.asMiddleware();\n return async ({ request, context, next }) => {\n const req = deepClone(request) as JsonRpcRequest<Params>;\n propagateToRequest(req, context);\n\n const response = await new Promise<JsonRpcResponse>((resolve) => {\n // The result or error property will be set by the legacy engine\n // middleware.\n const res = {\n jsonrpc: '2.0' as const,\n id: req.id,\n } as JsonRpcResponse;\n\n const end: JsonRpcEngineEndCallback = (error) => {\n if (error !== undefined) {\n (res as JsonRpcFailure).error = serializeError(error);\n }\n resolve(res);\n };\n\n // We know from the implementation of JsonRpcEngine.asMiddleware() that\n // legacyNext will always be passed a callback, so cb can never be\n // undefined.\n const legacyNext = ((cb: JsonRpcEngineEndCallback) =>\n cb(end)) as JsonRpcEngineNextCallback;\n\n middleware(req, res, legacyNext, end);\n });\n propagateToContext(req, context);\n\n if (hasProperty(response, 'error')) {\n throw unserializeError(response.error);\n } else if (hasProperty(response, 'result')) {\n return response.result as ResultConstraint<Request>;\n }\n return next(fromLegacyRequest(req as Request));\n };\n}\n"]}
1
+ {"version":3,"file":"asV2Middleware.cjs","sourceRoot":"","sources":["../src/asV2Middleware.ts"],"names":[],"mappings":";;;AAAA,qDAAsD;AAEtD,2CAKyB;AAQzB,2DAAoD;AACpD,sEAMkC;AAiClC;;;;;;GAMG;AACH,SAAgB,cAAc,CAI5B,kBAAyE,EACzE,GAAG,IAA6C;IAEhD,MAAM,gBAAgB,GACpB,OAAO,kBAAkB,KAAK,UAAU;QACtC,CAAC,CAAC,IAAA,iCAAe,EAAC,CAAC,kBAAkB,EAAE,GAAG,IAAI,CAAC,CAAC;QAChD,CAAC,CAAC,kBAAkB,CAAC,YAAY,EAAE,CAAC;IAExC,OAAO,KAAK,EAAE,EAAE,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,EAAE,EAAE;QAC1C,MAAM,GAAG,GAAG,IAAA,+BAAS,EAAC,OAAO,CAA2B,CAAC;QACzD,IAAA,wCAAkB,EAAC,GAAG,EAAE,OAAO,CAAC,CAAC;QAEjC,MAAM,QAAQ,GAAG,MAAM,IAAI,OAAO,CAAkB,CAAC,OAAO,EAAE,EAAE;YAC9D,gEAAgE;YAChE,cAAc;YACd,MAAM,GAAG,GAAG;gBACV,OAAO,EAAE,KAAc;gBACvB,EAAE,EAAE,GAAG,CAAC,EAAE;aACQ,CAAC;YAErB,MAAM,GAAG,GAA6B,CAAC,KAAK,EAAE,EAAE;gBAC9C,IAAI,KAAK,KAAK,SAAS,EAAE;oBACtB,GAAsB,CAAC,KAAK,GAAG,IAAA,2BAAc,EAAC,KAAK,CAAC,CAAC;iBACvD;gBACD,OAAO,CAAC,GAAG,CAAC,CAAC;YACf,CAAC,CAAC;YAEF,uEAAuE;YACvE,kEAAkE;YAClE,aAAa;YACb,MAAM,UAAU,GAAG,CAAC,CAAC,EAA4B,EAAE,EAAE,CACnD,EAAE,CAAC,GAAG,CAAC,CAA8B,CAAC;YAExC,gBAAgB,CAAC,GAAG,EAAE,GAAG,EAAE,UAAU,EAAE,GAAG,CAAC,CAAC;QAC9C,CAAC,CAAC,CAAC;QACH,IAAA,wCAAkB,EAAC,GAAG,EAAE,OAAO,CAAC,CAAC;QAEjC,IAAI,IAAA,mBAAW,EAAC,QAAQ,EAAE,OAAO,CAAC,EAAE;YAClC,MAAM,IAAA,sCAAgB,EAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;SACxC;aAAM,IAAI,IAAA,mBAAW,EAAC,QAAQ,EAAE,QAAQ,CAAC,EAAE;YAC1C,OAAO,QAAQ,CAAC,MAAmC,CAAC;SACrD;QACD,OAAO,IAAI,CAAC,IAAA,uCAAiB,EAAC,GAAc,CAAC,CAAC,CAAC;IACjD,CAAC,CAAC;AACJ,CAAC;AAhDD,wCAgDC","sourcesContent":["import { serializeError } from '@metamask/rpc-errors';\nimport type { JsonRpcFailure, JsonRpcResponse } from '@metamask/utils';\nimport {\n hasProperty,\n type Json,\n type JsonRpcParams,\n type JsonRpcRequest,\n} from '@metamask/utils';\n\nimport type {\n JsonRpcEngine,\n JsonRpcEngineEndCallback,\n JsonRpcEngineNextCallback,\n} from './JsonRpcEngine';\nimport { type JsonRpcMiddleware as LegacyMiddleware } from './JsonRpcEngine';\nimport { mergeMiddleware } from './mergeMiddleware';\nimport {\n deepClone,\n fromLegacyRequest,\n propagateToContext,\n propagateToRequest,\n unserializeError,\n} from './v2/compatibility-utils';\nimport type {\n // Used in docs.\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n JsonRpcEngineV2,\n JsonRpcMiddleware,\n ResultConstraint,\n} from './v2/JsonRpcEngineV2';\n\n/**\n * Convert a legacy {@link JsonRpcEngine} into a {@link JsonRpcEngineV2} middleware.\n *\n * @param engine - The legacy engine to convert.\n * @returns The {@link JsonRpcEngineV2} middleware.\n */\nexport function asV2Middleware<\n Params extends JsonRpcParams,\n Request extends JsonRpcRequest<Params>,\n>(engine: JsonRpcEngine): JsonRpcMiddleware<Request>;\n\n/**\n * Convert one or more legacy middleware into a {@link JsonRpcEngineV2} middleware.\n *\n * @param middleware - The legacy middleware to convert.\n * @returns The {@link JsonRpcEngineV2} middleware.\n */\nexport function asV2Middleware<\n Params extends JsonRpcParams,\n Request extends JsonRpcRequest<Params>,\n>(\n ...middleware: LegacyMiddleware<JsonRpcParams, Json>[]\n): JsonRpcMiddleware<Request>;\n\n/**\n * The asV2Middleware implementation.\n *\n * @param engineOrMiddleware - A legacy engine or legacy middleware.\n * @param rest - Any additional legacy middleware when the first argument is a middleware.\n * @returns The {@link JsonRpcEngineV2} middleware.\n */\nexport function asV2Middleware<\n Params extends JsonRpcParams,\n Request extends JsonRpcRequest<Params>,\n>(\n engineOrMiddleware: JsonRpcEngine | LegacyMiddleware<JsonRpcParams, Json>,\n ...rest: LegacyMiddleware<JsonRpcParams, Json>[]\n): JsonRpcMiddleware<Request> {\n const legacyMiddleware =\n typeof engineOrMiddleware === 'function'\n ? mergeMiddleware([engineOrMiddleware, ...rest])\n : engineOrMiddleware.asMiddleware();\n\n return async ({ request, context, next }) => {\n const req = deepClone(request) as JsonRpcRequest<Params>;\n propagateToRequest(req, context);\n\n const response = await new Promise<JsonRpcResponse>((resolve) => {\n // The result or error property will be set by the legacy engine\n // middleware.\n const res = {\n jsonrpc: '2.0' as const,\n id: req.id,\n } as JsonRpcResponse;\n\n const end: JsonRpcEngineEndCallback = (error) => {\n if (error !== undefined) {\n (res as JsonRpcFailure).error = serializeError(error);\n }\n resolve(res);\n };\n\n // We know from the implementation of JsonRpcEngine.asMiddleware() that\n // legacyNext will always be passed a callback, so cb can never be\n // undefined.\n const legacyNext = ((cb: JsonRpcEngineEndCallback) =>\n cb(end)) as JsonRpcEngineNextCallback;\n\n legacyMiddleware(req, res, legacyNext, end);\n });\n propagateToContext(req, context);\n\n if (hasProperty(response, 'error')) {\n throw unserializeError(response.error);\n } else if (hasProperty(response, 'result')) {\n return response.result as ResultConstraint<Request>;\n }\n return next(fromLegacyRequest(req as Request));\n };\n}\n"]}
@@ -1,5 +1,6 @@
1
- import { type JsonRpcParams, type JsonRpcRequest } from "@metamask/utils";
1
+ import { type Json, type JsonRpcParams, type JsonRpcRequest } from "@metamask/utils";
2
2
  import type { JsonRpcEngine } from "./JsonRpcEngine.cjs";
3
+ import { type JsonRpcMiddleware as LegacyMiddleware } from "./JsonRpcEngine.cjs";
3
4
  import type { JsonRpcMiddleware } from "./v2/JsonRpcEngineV2.cjs";
4
5
  /**
5
6
  * Convert a legacy {@link JsonRpcEngine} into a {@link JsonRpcEngineV2} middleware.
@@ -8,4 +9,11 @@ import type { JsonRpcMiddleware } from "./v2/JsonRpcEngineV2.cjs";
8
9
  * @returns The {@link JsonRpcEngineV2} middleware.
9
10
  */
10
11
  export declare function asV2Middleware<Params extends JsonRpcParams, Request extends JsonRpcRequest<Params>>(engine: JsonRpcEngine): JsonRpcMiddleware<Request>;
12
+ /**
13
+ * Convert one or more legacy middleware into a {@link JsonRpcEngineV2} middleware.
14
+ *
15
+ * @param middleware - The legacy middleware to convert.
16
+ * @returns The {@link JsonRpcEngineV2} middleware.
17
+ */
18
+ export declare function asV2Middleware<Params extends JsonRpcParams, Request extends JsonRpcRequest<Params>>(...middleware: LegacyMiddleware<JsonRpcParams, Json>[]): JsonRpcMiddleware<Request>;
11
19
  //# sourceMappingURL=asV2Middleware.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"asV2Middleware.d.cts","sourceRoot":"","sources":["../src/asV2Middleware.ts"],"names":[],"mappings":"AAEA,OAAO,EAEL,KAAK,aAAa,EAClB,KAAK,cAAc,EACpB,wBAAwB;AAEzB,OAAO,KAAK,EACV,aAAa,EAGd,4BAAwB;AAQzB,OAAO,KAAK,EAIV,iBAAiB,EAElB,iCAA6B;AAE9B;;;;;GAKG;AACH,wBAAgB,cAAc,CAC5B,MAAM,SAAS,aAAa,EAC5B,OAAO,SAAS,cAAc,CAAC,MAAM,CAAC,EACtC,MAAM,EAAE,aAAa,GAAG,iBAAiB,CAAC,OAAO,CAAC,CAsCnD"}
1
+ {"version":3,"file":"asV2Middleware.d.cts","sourceRoot":"","sources":["../src/asV2Middleware.ts"],"names":[],"mappings":"AAEA,OAAO,EAEL,KAAK,IAAI,EACT,KAAK,aAAa,EAClB,KAAK,cAAc,EACpB,wBAAwB;AAEzB,OAAO,KAAK,EACV,aAAa,EAGd,4BAAwB;AACzB,OAAO,EAAE,KAAK,iBAAiB,IAAI,gBAAgB,EAAE,4BAAwB;AAS7E,OAAO,KAAK,EAIV,iBAAiB,EAElB,iCAA6B;AAE9B;;;;;GAKG;AACH,wBAAgB,cAAc,CAC5B,MAAM,SAAS,aAAa,EAC5B,OAAO,SAAS,cAAc,CAAC,MAAM,CAAC,EACtC,MAAM,EAAE,aAAa,GAAG,iBAAiB,CAAC,OAAO,CAAC,CAAC;AAErD;;;;;GAKG;AACH,wBAAgB,cAAc,CAC5B,MAAM,SAAS,aAAa,EAC5B,OAAO,SAAS,cAAc,CAAC,MAAM,CAAC,EAEtC,GAAG,UAAU,EAAE,gBAAgB,CAAC,aAAa,EAAE,IAAI,CAAC,EAAE,GACrD,iBAAiB,CAAC,OAAO,CAAC,CAAC"}
@@ -1,5 +1,6 @@
1
- import { type JsonRpcParams, type JsonRpcRequest } from "@metamask/utils";
1
+ import { type Json, type JsonRpcParams, type JsonRpcRequest } from "@metamask/utils";
2
2
  import type { JsonRpcEngine } from "./JsonRpcEngine.mjs";
3
+ import { type JsonRpcMiddleware as LegacyMiddleware } from "./JsonRpcEngine.mjs";
3
4
  import type { JsonRpcMiddleware } from "./v2/JsonRpcEngineV2.mjs";
4
5
  /**
5
6
  * Convert a legacy {@link JsonRpcEngine} into a {@link JsonRpcEngineV2} middleware.
@@ -8,4 +9,11 @@ import type { JsonRpcMiddleware } from "./v2/JsonRpcEngineV2.mjs";
8
9
  * @returns The {@link JsonRpcEngineV2} middleware.
9
10
  */
10
11
  export declare function asV2Middleware<Params extends JsonRpcParams, Request extends JsonRpcRequest<Params>>(engine: JsonRpcEngine): JsonRpcMiddleware<Request>;
12
+ /**
13
+ * Convert one or more legacy middleware into a {@link JsonRpcEngineV2} middleware.
14
+ *
15
+ * @param middleware - The legacy middleware to convert.
16
+ * @returns The {@link JsonRpcEngineV2} middleware.
17
+ */
18
+ export declare function asV2Middleware<Params extends JsonRpcParams, Request extends JsonRpcRequest<Params>>(...middleware: LegacyMiddleware<JsonRpcParams, Json>[]): JsonRpcMiddleware<Request>;
11
19
  //# sourceMappingURL=asV2Middleware.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"asV2Middleware.d.mts","sourceRoot":"","sources":["../src/asV2Middleware.ts"],"names":[],"mappings":"AAEA,OAAO,EAEL,KAAK,aAAa,EAClB,KAAK,cAAc,EACpB,wBAAwB;AAEzB,OAAO,KAAK,EACV,aAAa,EAGd,4BAAwB;AAQzB,OAAO,KAAK,EAIV,iBAAiB,EAElB,iCAA6B;AAE9B;;;;;GAKG;AACH,wBAAgB,cAAc,CAC5B,MAAM,SAAS,aAAa,EAC5B,OAAO,SAAS,cAAc,CAAC,MAAM,CAAC,EACtC,MAAM,EAAE,aAAa,GAAG,iBAAiB,CAAC,OAAO,CAAC,CAsCnD"}
1
+ {"version":3,"file":"asV2Middleware.d.mts","sourceRoot":"","sources":["../src/asV2Middleware.ts"],"names":[],"mappings":"AAEA,OAAO,EAEL,KAAK,IAAI,EACT,KAAK,aAAa,EAClB,KAAK,cAAc,EACpB,wBAAwB;AAEzB,OAAO,KAAK,EACV,aAAa,EAGd,4BAAwB;AACzB,OAAO,EAAE,KAAK,iBAAiB,IAAI,gBAAgB,EAAE,4BAAwB;AAS7E,OAAO,KAAK,EAIV,iBAAiB,EAElB,iCAA6B;AAE9B;;;;;GAKG;AACH,wBAAgB,cAAc,CAC5B,MAAM,SAAS,aAAa,EAC5B,OAAO,SAAS,cAAc,CAAC,MAAM,CAAC,EACtC,MAAM,EAAE,aAAa,GAAG,iBAAiB,CAAC,OAAO,CAAC,CAAC;AAErD;;;;;GAKG;AACH,wBAAgB,cAAc,CAC5B,MAAM,SAAS,aAAa,EAC5B,OAAO,SAAS,cAAc,CAAC,MAAM,CAAC,EAEtC,GAAG,UAAU,EAAE,gBAAgB,CAAC,aAAa,EAAE,IAAI,CAAC,EAAE,GACrD,iBAAiB,CAAC,OAAO,CAAC,CAAC"}
@@ -1,14 +1,18 @@
1
1
  import { serializeError } from "@metamask/rpc-errors";
2
2
  import { hasProperty } from "@metamask/utils";
3
+ import { mergeMiddleware } from "./mergeMiddleware.mjs";
3
4
  import { deepClone, fromLegacyRequest, propagateToContext, propagateToRequest, unserializeError } from "./v2/compatibility-utils.mjs";
4
5
  /**
5
- * Convert a legacy {@link JsonRpcEngine} into a {@link JsonRpcEngineV2} middleware.
6
+ * The asV2Middleware implementation.
6
7
  *
7
- * @param engine - The legacy engine to convert.
8
+ * @param engineOrMiddleware - A legacy engine or legacy middleware.
9
+ * @param rest - Any additional legacy middleware when the first argument is a middleware.
8
10
  * @returns The {@link JsonRpcEngineV2} middleware.
9
11
  */
10
- export function asV2Middleware(engine) {
11
- const middleware = engine.asMiddleware();
12
+ export function asV2Middleware(engineOrMiddleware, ...rest) {
13
+ const legacyMiddleware = typeof engineOrMiddleware === 'function'
14
+ ? mergeMiddleware([engineOrMiddleware, ...rest])
15
+ : engineOrMiddleware.asMiddleware();
12
16
  return async ({ request, context, next }) => {
13
17
  const req = deepClone(request);
14
18
  propagateToRequest(req, context);
@@ -29,7 +33,7 @@ export function asV2Middleware(engine) {
29
33
  // legacyNext will always be passed a callback, so cb can never be
30
34
  // undefined.
31
35
  const legacyNext = ((cb) => cb(end));
32
- middleware(req, res, legacyNext, end);
36
+ legacyMiddleware(req, res, legacyNext, end);
33
37
  });
34
38
  propagateToContext(req, context);
35
39
  if (hasProperty(response, 'error')) {
@@ -1 +1 @@
1
- {"version":3,"file":"asV2Middleware.mjs","sourceRoot":"","sources":["../src/asV2Middleware.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,6BAA6B;AAEtD,OAAO,EACL,WAAW,EAGZ,wBAAwB;AAOzB,OAAO,EACL,SAAS,EACT,iBAAiB,EACjB,kBAAkB,EAClB,kBAAkB,EAClB,gBAAgB,EACjB,qCAAiC;AASlC;;;;;GAKG;AACH,MAAM,UAAU,cAAc,CAG5B,MAAqB;IACrB,MAAM,UAAU,GAAG,MAAM,CAAC,YAAY,EAAE,CAAC;IACzC,OAAO,KAAK,EAAE,EAAE,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,EAAE,EAAE;QAC1C,MAAM,GAAG,GAAG,SAAS,CAAC,OAAO,CAA2B,CAAC;QACzD,kBAAkB,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;QAEjC,MAAM,QAAQ,GAAG,MAAM,IAAI,OAAO,CAAkB,CAAC,OAAO,EAAE,EAAE;YAC9D,gEAAgE;YAChE,cAAc;YACd,MAAM,GAAG,GAAG;gBACV,OAAO,EAAE,KAAc;gBACvB,EAAE,EAAE,GAAG,CAAC,EAAE;aACQ,CAAC;YAErB,MAAM,GAAG,GAA6B,CAAC,KAAK,EAAE,EAAE;gBAC9C,IAAI,KAAK,KAAK,SAAS,EAAE;oBACtB,GAAsB,CAAC,KAAK,GAAG,cAAc,CAAC,KAAK,CAAC,CAAC;iBACvD;gBACD,OAAO,CAAC,GAAG,CAAC,CAAC;YACf,CAAC,CAAC;YAEF,uEAAuE;YACvE,kEAAkE;YAClE,aAAa;YACb,MAAM,UAAU,GAAG,CAAC,CAAC,EAA4B,EAAE,EAAE,CACnD,EAAE,CAAC,GAAG,CAAC,CAA8B,CAAC;YAExC,UAAU,CAAC,GAAG,EAAE,GAAG,EAAE,UAAU,EAAE,GAAG,CAAC,CAAC;QACxC,CAAC,CAAC,CAAC;QACH,kBAAkB,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;QAEjC,IAAI,WAAW,CAAC,QAAQ,EAAE,OAAO,CAAC,EAAE;YAClC,MAAM,gBAAgB,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;SACxC;aAAM,IAAI,WAAW,CAAC,QAAQ,EAAE,QAAQ,CAAC,EAAE;YAC1C,OAAO,QAAQ,CAAC,MAAmC,CAAC;SACrD;QACD,OAAO,IAAI,CAAC,iBAAiB,CAAC,GAAc,CAAC,CAAC,CAAC;IACjD,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { serializeError } from '@metamask/rpc-errors';\nimport type { JsonRpcFailure, JsonRpcResponse } from '@metamask/utils';\nimport {\n hasProperty,\n type JsonRpcParams,\n type JsonRpcRequest,\n} from '@metamask/utils';\n\nimport type {\n JsonRpcEngine,\n JsonRpcEngineEndCallback,\n JsonRpcEngineNextCallback,\n} from './JsonRpcEngine';\nimport {\n deepClone,\n fromLegacyRequest,\n propagateToContext,\n propagateToRequest,\n unserializeError,\n} from './v2/compatibility-utils';\nimport type {\n // JsonRpcEngineV2 is used in docs.\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n JsonRpcEngineV2,\n JsonRpcMiddleware,\n ResultConstraint,\n} from './v2/JsonRpcEngineV2';\n\n/**\n * Convert a legacy {@link JsonRpcEngine} into a {@link JsonRpcEngineV2} middleware.\n *\n * @param engine - The legacy engine to convert.\n * @returns The {@link JsonRpcEngineV2} middleware.\n */\nexport function asV2Middleware<\n Params extends JsonRpcParams,\n Request extends JsonRpcRequest<Params>,\n>(engine: JsonRpcEngine): JsonRpcMiddleware<Request> {\n const middleware = engine.asMiddleware();\n return async ({ request, context, next }) => {\n const req = deepClone(request) as JsonRpcRequest<Params>;\n propagateToRequest(req, context);\n\n const response = await new Promise<JsonRpcResponse>((resolve) => {\n // The result or error property will be set by the legacy engine\n // middleware.\n const res = {\n jsonrpc: '2.0' as const,\n id: req.id,\n } as JsonRpcResponse;\n\n const end: JsonRpcEngineEndCallback = (error) => {\n if (error !== undefined) {\n (res as JsonRpcFailure).error = serializeError(error);\n }\n resolve(res);\n };\n\n // We know from the implementation of JsonRpcEngine.asMiddleware() that\n // legacyNext will always be passed a callback, so cb can never be\n // undefined.\n const legacyNext = ((cb: JsonRpcEngineEndCallback) =>\n cb(end)) as JsonRpcEngineNextCallback;\n\n middleware(req, res, legacyNext, end);\n });\n propagateToContext(req, context);\n\n if (hasProperty(response, 'error')) {\n throw unserializeError(response.error);\n } else if (hasProperty(response, 'result')) {\n return response.result as ResultConstraint<Request>;\n }\n return next(fromLegacyRequest(req as Request));\n };\n}\n"]}
1
+ {"version":3,"file":"asV2Middleware.mjs","sourceRoot":"","sources":["../src/asV2Middleware.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,6BAA6B;AAEtD,OAAO,EACL,WAAW,EAIZ,wBAAwB;AAQzB,OAAO,EAAE,eAAe,EAAE,8BAA0B;AACpD,OAAO,EACL,SAAS,EACT,iBAAiB,EACjB,kBAAkB,EAClB,kBAAkB,EAClB,gBAAgB,EACjB,qCAAiC;AAiClC;;;;;;GAMG;AACH,MAAM,UAAU,cAAc,CAI5B,kBAAyE,EACzE,GAAG,IAA6C;IAE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AE;YAC1C,OAAO,QAAQ,CAAC,MAAmC,CAAC;SACrD;QACD,OAAO,IAAI,CAAC,iBAAiB,CAAC,GAAc,CAAC,CAAC,CAAC;IACjD,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { serializeError } from '@metamask/rpc-errors';\nimport type { JsonRpcFailure, JsonRpcResponse } from '@metamask/utils';\nimport {\n hasProperty,\n type Json,\n type JsonRpcParams,\n type JsonRpcRequest,\n} from '@metamask/utils';\n\nimport type {\n JsonRpcEngine,\n JsonRpcEngineEndCallback,\n JsonRpcEngineNextCallback,\n} from './JsonRpcEngine';\nimport { type JsonRpcMiddleware as LegacyMiddleware } from './JsonRpcEngine';\nimport { mergeMiddleware } from './mergeMiddleware';\nimport {\n deepClone,\n fromLegacyRequest,\n propagateToContext,\n propagateToRequest,\n unserializeError,\n} from './v2/compatibility-utils';\nimport type {\n // Used in docs.\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n JsonRpcEngineV2,\n JsonRpcMiddleware,\n ResultConstraint,\n} from './v2/JsonRpcEngineV2';\n\n/**\n * Convert a legacy {@link JsonRpcEngine} into a {@link JsonRpcEngineV2} middleware.\n *\n * @param engine - The legacy engine to convert.\n * @returns The {@link JsonRpcEngineV2} middleware.\n */\nexport function asV2Middleware<\n Params extends JsonRpcParams,\n Request extends JsonRpcRequest<Params>,\n>(engine: JsonRpcEngine): JsonRpcMiddleware<Request>;\n\n/**\n * Convert one or more legacy middleware into a {@link JsonRpcEngineV2} middleware.\n *\n * @param middleware - The legacy middleware to convert.\n * @returns The {@link JsonRpcEngineV2} middleware.\n */\nexport function asV2Middleware<\n Params extends JsonRpcParams,\n Request extends JsonRpcRequest<Params>,\n>(\n ...middleware: LegacyMiddleware<JsonRpcParams, Json>[]\n): JsonRpcMiddleware<Request>;\n\n/**\n * The asV2Middleware implementation.\n *\n * @param engineOrMiddleware - A legacy engine or legacy middleware.\n * @param rest - Any additional legacy middleware when the first argument is a middleware.\n * @returns The {@link JsonRpcEngineV2} middleware.\n */\nexport function asV2Middleware<\n Params extends JsonRpcParams,\n Request extends JsonRpcRequest<Params>,\n>(\n engineOrMiddleware: JsonRpcEngine | LegacyMiddleware<JsonRpcParams, Json>,\n ...rest: LegacyMiddleware<JsonRpcParams, Json>[]\n): JsonRpcMiddleware<Request> {\n const legacyMiddleware =\n typeof engineOrMiddleware === 'function'\n ? mergeMiddleware([engineOrMiddleware, ...rest])\n : engineOrMiddleware.asMiddleware();\n\n return async ({ request, context, next }) => {\n const req = deepClone(request) as JsonRpcRequest<Params>;\n propagateToRequest(req, context);\n\n const response = await new Promise<JsonRpcResponse>((resolve) => {\n // The result or error property will be set by the legacy engine\n // middleware.\n const res = {\n jsonrpc: '2.0' as const,\n id: req.id,\n } as JsonRpcResponse;\n\n const end: JsonRpcEngineEndCallback = (error) => {\n if (error !== undefined) {\n (res as JsonRpcFailure).error = serializeError(error);\n }\n resolve(res);\n };\n\n // We know from the implementation of JsonRpcEngine.asMiddleware() that\n // legacyNext will always be passed a callback, so cb can never be\n // undefined.\n const legacyNext = ((cb: JsonRpcEngineEndCallback) =>\n cb(end)) as JsonRpcEngineNextCallback;\n\n legacyMiddleware(req, res, legacyNext, end);\n });\n propagateToContext(req, context);\n\n if (hasProperty(response, 'error')) {\n throw unserializeError(response.error);\n } else if (hasProperty(response, 'result')) {\n return response.result as ResultConstraint<Request>;\n }\n return next(fromLegacyRequest(req as Request));\n };\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"JsonRpcServer.cjs","sourceRoot":"","sources":["../../src/v2/JsonRpcServer.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,qDAAiE;AAQjE,2CAAwD;AAQxD,2DAAoD;AAEpD,oDAA6C;AAe7C,MAAM,OAAO,GAAG,KAAc,CAAC;AAE/B;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,MAAa,aAAa;IAiBxB;;;;;;;;;;;;OAYG;IACH,YAAY,OAA4B;;QApB/B,wCAGP;QAEO,yCAA+B;Q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C,EAAE,EAAE,IAAI,CAAC,CAAC;KAC9B;IACD,OAAO,CAAC,SAAS,EAAE,KAAK,CAAC,CAAC;AAC5B,CAAC","sourcesContent":["import { rpcErrors, serializeError } from '@metamask/rpc-errors';\nimport type {\n JsonRpcNotification,\n JsonRpcParams,\n JsonRpcRequest,\n JsonRpcResponse,\n NonEmptyArray,\n} from '@metamask/utils';\nimport { hasProperty, isObject } from '@metamask/utils';\n\nimport type {\n JsonRpcMiddleware,\n MergedContextOf,\n RequestOf,\n ResultConstraint,\n} from './JsonRpcEngineV2';\nimport { JsonRpcEngineV2 } from './JsonRpcEngineV2';\nimport type { JsonRpcCall } from './utils';\nimport { getUniqueId } from '../getUniqueId';\n\ntype OnError = (error: unknown) => void;\n\ntype Options<Middleware extends JsonRpcMiddleware> = {\n onError?: OnError;\n} & (\n | {\n engine: JsonRpcEngineV2;\n }\n | {\n middleware: NonEmptyArray<Middleware>;\n }\n);\n\nconst jsonrpc = '2.0' as const;\n\n/**\n * A JSON-RPC server that handles requests and notifications.\n *\n * Essentially wraps a {@link JsonRpcEngineV2} in order to create a conformant\n * yet permissive JSON-RPC 2.0 server.\n *\n * Note that the server will accept both requests and notifications via {@link handle},\n * even if the underlying engine is only able to handle one or the other.\n *\n * @example\n * ```ts\n * const server = new JsonRpcServer({\n * engine,\n * onError,\n * });\n *\n * const response = await server.handle(request);\n * if ('result' in response) {\n * // Handle result\n * } else {\n * // Handle error\n * }\n * ```\n */\nexport class JsonRpcServer<\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 readonly #engine: JsonRpcEngineV2<\n RequestOf<Middleware>,\n MergedContextOf<Middleware>\n >;\n\n readonly #onError?: OnError | undefined;\n\n /**\n * Construct a new JSON-RPC server.\n *\n * @param options - The options for the server.\n * @param options.onError - The callback to handle errors thrown by the\n * engine. Errors always result in a failed response object, containing a\n * JSON-RPC 2.0 serialized version of the original error. If you need to\n * access the original error, use the `onError` callback.\n * @param options.engine - The engine to use. Mutually exclusive with\n * `middleware`.\n * @param options.middleware - The middleware to use. Mutually exclusive with\n * `engine`.\n */\n constructor(options: Options<Middleware>) {\n this.#onError = options.onError;\n\n if (hasProperty(options, 'engine')) {\n // @ts-expect-error - hasProperty fails to narrow the type.\n this.#engine = options.engine;\n } else {\n // @ts-expect-error - TypeScript complains that engine is of the wrong type, but clearly it's not.\n this.#engine = JsonRpcEngineV2.create({ middleware: options.middleware });\n }\n }\n\n /**\n * Handle a JSON-RPC request.\n *\n * This method never throws. For requests, a response is always returned.\n * All errors are passed to the engine's `onError` callback.\n *\n * **WARNING**: This method is unaware of the request type of the underlying\n * engine. The request will fail if the engine can only handle notifications.\n *\n * @param request - The request to handle.\n * @returns The JSON-RPC response.\n */\n async handle(request: JsonRpcRequest): Promise<JsonRpcResponse>;\n\n /**\n * Handle a JSON-RPC notification.\n *\n * This method never throws. For notifications, `undefined` is always returned.\n * All errors are passed to the engine's `onError` callback.\n *\n * **WARNING**: This method is unaware of the request type of the underlying\n * engine. The request will fail if the engine cannot handle notifications.\n *\n * @param notification - The notification to handle.\n */\n async handle(notification: JsonRpcNotification): Promise<void>;\n\n /**\n * Handle an alleged JSON-RPC request or notification. Permits any plain\n * object with `{ method: string }`, so long as any present JSON-RPC 2.0\n * properties are valid. If the object has an `id` property, it will be\n * treated as a request, otherwise it will be treated as a notification.\n *\n * This method never throws. All errors are passed to the engine's\n * `onError` callback. A JSON-RPC response is always returned for requests,\n * and `undefined` is returned for notifications.\n *\n * **WARNING**: The request will fail if its coerced type (i.e. request or\n * response) is not of the type expected by the underlying engine.\n *\n * @param rawRequest - The raw request to handle.\n * @returns The JSON-RPC response, or `undefined` if the request is a\n * notification.\n */\n async handle(rawRequest: unknown): Promise<JsonRpcResponse | void>;\n\n async handle(rawRequest: unknown): Promise<JsonRpcResponse | void> {\n // If rawRequest is not a notification, the originalId will be attached\n // to the response. We attach our own, trusted id in #coerceRequest()\n // while the request is being handled.\n const [originalId, isRequest] = getOriginalId(rawRequest);\n\n try {\n const request = this.#coerceRequest(rawRequest, isRequest);\n // @ts-expect-error - The request may not be of the type expected by the engine,\n // and we intentionally allow this to happen.\n const result = await this.#engine.handle(request);\n\n if (result !== undefined) {\n return {\n jsonrpc,\n // @ts-expect-error - Reassign the original id, regardless of its type.\n id: originalId,\n result,\n };\n }\n } catch (error) {\n this.#onError?.(error);\n\n if (isRequest) {\n return {\n jsonrpc,\n // @ts-expect-error - Reassign the original id, regardless of its type.\n id: originalId,\n error: serializeError(error, {\n shouldIncludeStack: false,\n shouldPreserveMessage: true,\n }),\n };\n }\n }\n return undefined;\n }\n\n #coerceRequest(rawRequest: unknown, isRequest: boolean): JsonRpcCall {\n if (!isMinimalRequest(rawRequest)) {\n throw rpcErrors.invalidRequest({\n data: {\n request: rawRequest,\n },\n });\n }\n\n const request: JsonRpcCall = {\n jsonrpc,\n method: rawRequest.method,\n };\n\n if (hasProperty(rawRequest, 'params')) {\n request.params = rawRequest.params as JsonRpcParams;\n }\n\n if (isRequest) {\n (request as JsonRpcRequest).id = getUniqueId();\n }\n\n return request;\n }\n}\n\n/**\n * The most minimally conformant request object that we will accept.\n */\ntype MinimalRequest = {\n method: string;\n params?: JsonRpcParams;\n} & Record<string, unknown>;\n\n/**\n * Check if an unvalidated request is a minimal request.\n *\n * @param rawRequest - The raw request to check.\n * @returns `true` if the request is a {@link MinimalRequest}, `false` otherwise.\n */\nfunction isMinimalRequest(rawRequest: unknown): rawRequest is MinimalRequest {\n return (\n isObject(rawRequest) &&\n hasProperty(rawRequest, 'method') &&\n typeof rawRequest.method === 'string' &&\n hasValidParams(rawRequest)\n );\n}\n\n/**\n * Check if a request has valid params, i.e. an array or object.\n * The contents of the params are not inspected.\n *\n * @param rawRequest - The request to check.\n * @returns `true` if the request has valid params, `false` otherwise.\n */\nfunction hasValidParams(\n rawRequest: Record<string, unknown>,\n): rawRequest is { params?: JsonRpcParams } {\n if (hasProperty(rawRequest, 'params')) {\n return Array.isArray(rawRequest.params) || isObject(rawRequest.params);\n }\n return true;\n}\n\n/**\n * Get the original id from a request.\n *\n * @param rawRequest - The request to get the original id from.\n * @returns The original id and a boolean indicating if the request is a request\n * (as opposed to a notification).\n */\nfunction getOriginalId(rawRequest: unknown): [unknown, boolean] {\n if (isObject(rawRequest) && hasProperty(rawRequest, 'id')) {\n return [rawRequest.id, true];\n }\n return [undefined, false];\n}\n"]}
1
+ {"version":3,"file":"JsonRpcServer.cjs","sourceRoot":"","sources":["../../src/v2/JsonRpcServer.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,qDAAiE;AAQjE,2CAAwD;AAQxD,2DAAoD;AAEpD,oDAA6C;AAe7C,MAAM,OAAO,GAAG,KAAc,CAAC;AAE/B;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,MAAa,aAAa;IAiBxB;;;;;;;;;;;;OAYG;IACH,YAAY,OAA4B;;QApB/B,wCAGP;QAEO,yCAA+B;QAgBtC,uBAAA,IAAI,0BAAY,OAAO,CAAC,OAAO,MAAA,CAAC;QAEhC,IAAI,IAAA,mBAAW,EAAC,OAAO,EAAE,QAAQ,CAAC,EAAE;YAClC,2DAA2D;YAC3D,uBAAA,IAAI,yBAAW,OAAO,CAAC,MAAM,MAAA,CAAC;SAC/B;aAAM;YACL,kGAAkG;YAClG,uBAAA,IAAI,yBAAW,iCAAe,CAAC,MAAM,CAAC,EAAE,UAAU,EAAE,OAAO,CAAC,UAAU,EAAE,CAAC,MAAA,CAAC;SAC3E;IACH,CAAC;IAgDD,KAAK,CAAC,MAAM,CAAC,UAAmB;QAC9B,uEAAuE;QACvE,qEAAqE;QACrE,sCAAsC;QACtC,MAAM,CAAC,UAAU,EAAE,SAAS,CAAC,GAAG,aAAa,CAAC,UAAU,CAAC,CAAC;QAE1D,IAAI;YACF,MAAM,OAAO,GAAG,uBAAA,IA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;AACH,SAAS,gBAAgB,CAAC,UAAmB;IAC3C,OAAO,CACL,IAAA,gBAAQ,EAAC,UAAU,CAAC;QACpB,IAAA,mBAAW,EAAC,UAAU,EAAE,QAAQ,CAAC;QACjC,OAAO,UAAU,CAAC,MAAM,KAAK,QAAQ;QACrC,cAAc,CAAC,UAAU,CAAC,CAC3B,CAAC;AACJ,CAAC;AAED;;;;;;GAMG;AACH,SAAS,cAAc,CACrB,UAAmC;IAEnC,IAAI,IAAA,mBAAW,EAAC,UAAU,EAAE,QAAQ,CAAC,EAAE;QACrC,OAAO,KAAK,CAAC,OAAO,CAAC,UAAU,CAAC,MAAM,CAAC,IAAI,IAAA,gBAAQ,EAAC,UAAU,CAAC,MAAM,CAAC,CAAC;KACxE;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AAED;;;;;;GAMG;AACH,SAAS,aAAa,CAAC,UAAmB;IACxC,IAAI,IAAA,gBAAQ,EAAC,UAAU,CAAC,IAAI,IAAA,mBAAW,EAAC,UAAU,EAAE,IAAI,CAAC,EAAE;QACzD,OAAO,CAAC,UAAU,CAAC,EAAE,EAAE,IAAI,CAAC,CAAC;KAC9B;IACD,OAAO,CAAC,SAAS,EAAE,KAAK,CAAC,CAAC;AAC5B,CAAC","sourcesContent":["import { rpcErrors, serializeError } from '@metamask/rpc-errors';\nimport type {\n JsonRpcNotification,\n JsonRpcParams,\n JsonRpcRequest,\n JsonRpcResponse,\n NonEmptyArray,\n} from '@metamask/utils';\nimport { hasProperty, isObject } from '@metamask/utils';\n\nimport type {\n JsonRpcMiddleware,\n MergedContextOf,\n RequestOf,\n ResultConstraint,\n} from './JsonRpcEngineV2';\nimport { JsonRpcEngineV2 } from './JsonRpcEngineV2';\nimport type { JsonRpcCall } from './utils';\nimport { getUniqueId } from '../getUniqueId';\n\ntype OnError = (error: unknown) => void;\n\ntype Options<Middleware extends JsonRpcMiddleware> = {\n onError?: OnError;\n} & (\n | {\n engine: ReturnType<typeof JsonRpcEngineV2.create<Middleware>>;\n }\n | {\n middleware: NonEmptyArray<Middleware>;\n }\n);\n\nconst jsonrpc = '2.0' as const;\n\n/**\n * A JSON-RPC server that handles requests and notifications.\n *\n * Essentially wraps a {@link JsonRpcEngineV2} in order to create a conformant\n * yet permissive JSON-RPC 2.0 server.\n *\n * Note that the server will accept both requests and notifications via {@link handle},\n * even if the underlying engine is only able to handle one or the other.\n *\n * @example\n * ```ts\n * const server = new JsonRpcServer({\n * engine,\n * onError,\n * });\n *\n * const response = await server.handle(request);\n * if ('result' in response) {\n * // Handle result\n * } else {\n * // Handle error\n * }\n * ```\n */\nexport class JsonRpcServer<\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 readonly #engine: JsonRpcEngineV2<\n RequestOf<Middleware>,\n MergedContextOf<Middleware>\n >;\n\n readonly #onError?: OnError | undefined;\n\n /**\n * Construct a new JSON-RPC server.\n *\n * @param options - The options for the server.\n * @param options.onError - The callback to handle errors thrown by the\n * engine. Errors always result in a failed response object, containing a\n * JSON-RPC 2.0 serialized version of the original error. If you need to\n * access the original error, use the `onError` callback.\n * @param options.engine - The engine to use. Mutually exclusive with\n * `middleware`.\n * @param options.middleware - The middleware to use. Mutually exclusive with\n * `engine`.\n */\n constructor(options: Options<Middleware>) {\n this.#onError = options.onError;\n\n if (hasProperty(options, 'engine')) {\n // @ts-expect-error - hasProperty fails to narrow the type.\n this.#engine = options.engine;\n } else {\n // @ts-expect-error - TypeScript complains that engine is of the wrong type, but clearly it's not.\n this.#engine = JsonRpcEngineV2.create({ middleware: options.middleware });\n }\n }\n\n /**\n * Handle a JSON-RPC request.\n *\n * This method never throws. For requests, a response is always returned.\n * All errors are passed to the engine's `onError` callback.\n *\n * **WARNING**: This method is unaware of the request type of the underlying\n * engine. The request will fail if the engine can only handle notifications.\n *\n * @param request - The request to handle.\n * @returns The JSON-RPC response.\n */\n async handle(request: JsonRpcRequest): Promise<JsonRpcResponse>;\n\n /**\n * Handle a JSON-RPC notification.\n *\n * This method never throws. For notifications, `undefined` is always returned.\n * All errors are passed to the engine's `onError` callback.\n *\n * **WARNING**: This method is unaware of the request type of the underlying\n * engine. The request will fail if the engine cannot handle notifications.\n *\n * @param notification - The notification to handle.\n */\n async handle(notification: JsonRpcNotification): Promise<void>;\n\n /**\n * Handle an alleged JSON-RPC request or notification. Permits any plain\n * object with `{ method: string }`, so long as any present JSON-RPC 2.0\n * properties are valid. If the object has an `id` property, it will be\n * treated as a request, otherwise it will be treated as a notification.\n *\n * This method never throws. All errors are passed to the engine's\n * `onError` callback. A JSON-RPC response is always returned for requests,\n * and `undefined` is returned for notifications.\n *\n * **WARNING**: The request will fail if its coerced type (i.e. request or\n * response) is not of the type expected by the underlying engine.\n *\n * @param rawRequest - The raw request to handle.\n * @returns The JSON-RPC response, or `undefined` if the request is a\n * notification.\n */\n async handle(rawRequest: unknown): Promise<JsonRpcResponse | void>;\n\n async handle(rawRequest: unknown): Promise<JsonRpcResponse | void> {\n // If rawRequest is not a notification, the originalId will be attached\n // to the response. We attach our own, trusted id in #coerceRequest()\n // while the request is being handled.\n const [originalId, isRequest] = getOriginalId(rawRequest);\n\n try {\n const request = this.#coerceRequest(rawRequest, isRequest);\n // @ts-expect-error - The request may not be of the type expected by the engine,\n // and we intentionally allow this to happen.\n const result = await this.#engine.handle(request);\n\n if (result !== undefined) {\n return {\n jsonrpc,\n // @ts-expect-error - Reassign the original id, regardless of its type.\n id: originalId,\n result,\n };\n }\n } catch (error) {\n this.#onError?.(error);\n\n if (isRequest) {\n return {\n jsonrpc,\n // @ts-expect-error - Reassign the original id, regardless of its type.\n id: originalId,\n error: serializeError(error, {\n shouldIncludeStack: false,\n shouldPreserveMessage: true,\n }),\n };\n }\n }\n return undefined;\n }\n\n #coerceRequest(rawRequest: unknown, isRequest: boolean): JsonRpcCall {\n if (!isMinimalRequest(rawRequest)) {\n throw rpcErrors.invalidRequest({\n data: {\n request: rawRequest,\n },\n });\n }\n\n const request: JsonRpcCall = {\n jsonrpc,\n method: rawRequest.method,\n };\n\n if (hasProperty(rawRequest, 'params')) {\n request.params = rawRequest.params as JsonRpcParams;\n }\n\n if (isRequest) {\n (request as JsonRpcRequest).id = getUniqueId();\n }\n\n return request;\n }\n}\n\n/**\n * The most minimally conformant request object that we will accept.\n */\ntype MinimalRequest = {\n method: string;\n params?: JsonRpcParams;\n} & Record<string, unknown>;\n\n/**\n * Check if an unvalidated request is a minimal request.\n *\n * @param rawRequest - The raw request to check.\n * @returns `true` if the request is a {@link MinimalRequest}, `false` otherwise.\n */\nfunction isMinimalRequest(rawRequest: unknown): rawRequest is MinimalRequest {\n return (\n isObject(rawRequest) &&\n hasProperty(rawRequest, 'method') &&\n typeof rawRequest.method === 'string' &&\n hasValidParams(rawRequest)\n );\n}\n\n/**\n * Check if a request has valid params, i.e. an array or object.\n * The contents of the params are not inspected.\n *\n * @param rawRequest - The request to check.\n * @returns `true` if the request has valid params, `false` otherwise.\n */\nfunction hasValidParams(\n rawRequest: Record<string, unknown>,\n): rawRequest is { params?: JsonRpcParams } {\n if (hasProperty(rawRequest, 'params')) {\n return Array.isArray(rawRequest.params) || isObject(rawRequest.params);\n }\n return true;\n}\n\n/**\n * Get the original id from a request.\n *\n * @param rawRequest - The request to get the original id from.\n * @returns The original id and a boolean indicating if the request is a request\n * (as opposed to a notification).\n */\nfunction getOriginalId(rawRequest: unknown): [unknown, boolean] {\n if (isObject(rawRequest) && hasProperty(rawRequest, 'id')) {\n return [rawRequest.id, true];\n }\n return [undefined, false];\n}\n"]}
@@ -5,7 +5,7 @@ type OnError = (error: unknown) => void;
5
5
  type Options<Middleware extends JsonRpcMiddleware> = {
6
6
  onError?: OnError;
7
7
  } & ({
8
- engine: JsonRpcEngineV2;
8
+ engine: ReturnType<typeof JsonRpcEngineV2.create<Middleware>>;
9
9
  } | {
10
10
  middleware: NonEmptyArray<Middleware>;
11
11
  });
@@ -1 +1 @@
1
- {"version":3,"file":"JsonRpcServer.d.cts","sourceRoot":"","sources":["../../src/v2/JsonRpcServer.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,mBAAmB,EAEnB,cAAc,EACd,eAAe,EACf,aAAa,EACd,wBAAwB;AAGzB,OAAO,KAAK,EACV,iBAAiB,EAGjB,gBAAgB,EACjB,8BAA0B;AAC3B,OAAO,EAAE,eAAe,EAAE,8BAA0B;AAIpD,KAAK,OAAO,GAAG,CAAC,KAAK,EAAE,OAAO,KAAK,IAAI,CAAC;AAExC,KAAK,OAAO,CAAC,UAAU,SAAS,iBAAiB,IAAI;IACnD,OAAO,CAAC,EAAE,OAAO,CAAC;CACnB,GAAG,CACA;IACE,MAAM,EAAE,eAAe,CAAC;CACzB,GACD;IACE,UAAU,EAAE,aAAa,CAAC,UAAU,CAAC,CAAC;CACvC,CACJ,CAAC;AAIF;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,qBAAa,aAAa,CACxB,UAAU,SAAS,iBAAiB,CAGlC,GAAG,EACH,gBAAgB,CAAC,GAAG,CAAC,EACrB,GAAG,CAEJ,GAAG,iBAAiB;;IASrB;;;;;;;;;;;;OAYG;gBACS,OAAO,EAAE,OAAO,CAAC,UAAU,CAAC;IAYxC;;;;;;;;;;;OAWG;IACG,MAAM,CAAC,OAAO,EAAE,cAAc,GAAG,OAAO,CAAC,eAAe,CAAC;IAE/D;;;;;;;;;;OAUG;IACG,MAAM,CAAC,YAAY,EAAE,mBAAmB,GAAG,OAAO,CAAC,IAAI,CAAC;IAE9D;;;;;;;;;;;;;;;;OAgBG;IACG,MAAM,CAAC,UAAU,EAAE,OAAO,GAAG,OAAO,CAAC,eAAe,GAAG,IAAI,CAAC;CAgEnE"}
1
+ {"version":3,"file":"JsonRpcServer.d.cts","sourceRoot":"","sources":["../../src/v2/JsonRpcServer.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,mBAAmB,EAEnB,cAAc,EACd,eAAe,EACf,aAAa,EACd,wBAAwB;AAGzB,OAAO,KAAK,EACV,iBAAiB,EAGjB,gBAAgB,EACjB,8BAA0B;AAC3B,OAAO,EAAE,eAAe,EAAE,8BAA0B;AAIpD,KAAK,OAAO,GAAG,CAAC,KAAK,EAAE,OAAO,KAAK,IAAI,CAAC;AAExC,KAAK,OAAO,CAAC,UAAU,SAAS,iBAAiB,IAAI;IACnD,OAAO,CAAC,EAAE,OAAO,CAAC;CACnB,GAAG,CACA;IACE,MAAM,EAAE,UAAU,CAAC,OAAO,eAAe,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC,CAAC;CAC/D,GACD;IACE,UAAU,EAAE,aAAa,CAAC,UAAU,CAAC,CAAC;CACvC,CACJ,CAAC;AAIF;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,qBAAa,aAAa,CACxB,UAAU,SAAS,iBAAiB,CAGlC,GAAG,EACH,gBAAgB,CAAC,GAAG,CAAC,EACrB,GAAG,CAEJ,GAAG,iBAAiB;;IASrB;;;;;;;;;;;;OAYG;gBACS,OAAO,EAAE,OAAO,CAAC,UAAU,CAAC;IAYxC;;;;;;;;;;;OAWG;IACG,MAAM,CAAC,OAAO,EAAE,cAAc,GAAG,OAAO,CAAC,eAAe,CAAC;IAE/D;;;;;;;;;;OAUG;IACG,MAAM,CAAC,YAAY,EAAE,mBAAmB,GAAG,OAAO,CAAC,IAAI,CAAC;IAE9D;;;;;;;;;;;;;;;;OAgBG;IACG,MAAM,CAAC,UAAU,EAAE,OAAO,GAAG,OAAO,CAAC,eAAe,GAAG,IAAI,CAAC;CAgEnE"}
@@ -5,7 +5,7 @@ type OnError = (error: unknown) => void;
5
5
  type Options<Middleware extends JsonRpcMiddleware> = {
6
6
  onError?: OnError;
7
7
  } & ({
8
- engine: JsonRpcEngineV2;
8
+ engine: ReturnType<typeof JsonRpcEngineV2.create<Middleware>>;
9
9
  } | {
10
10
  middleware: NonEmptyArray<Middleware>;
11
11
  });
@@ -1 +1 @@
1
- {"version":3,"file":"JsonRpcServer.d.mts","sourceRoot":"","sources":["../../src/v2/JsonRpcServer.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,mBAAmB,EAEnB,cAAc,EACd,eAAe,EACf,aAAa,EACd,wBAAwB;AAGzB,OAAO,KAAK,EACV,iBAAiB,EAGjB,gBAAgB,EACjB,8BAA0B;AAC3B,OAAO,EAAE,eAAe,EAAE,8BAA0B;AAIpD,KAAK,OAAO,GAAG,CAAC,KAAK,EAAE,OAAO,KAAK,IAAI,CAAC;AAExC,KAAK,OAAO,CAAC,UAAU,SAAS,iBAAiB,IAAI;IACnD,OAAO,CAAC,EAAE,OAAO,CAAC;CACnB,GAAG,CACA;IACE,MAAM,EAAE,eAAe,CAAC;CACzB,GACD;IACE,UAAU,EAAE,aAAa,CAAC,UAAU,CAAC,CAAC;CACvC,CACJ,CAAC;AAIF;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,qBAAa,aAAa,CACxB,UAAU,SAAS,iBAAiB,CAGlC,GAAG,EACH,gBAAgB,CAAC,GAAG,CAAC,EACrB,GAAG,CAEJ,GAAG,iBAAiB;;IASrB;;;;;;;;;;;;OAYG;gBACS,OAAO,EAAE,OAAO,CAAC,UAAU,CAAC;IAYxC;;;;;;;;;;;OAWG;IACG,MAAM,CAAC,OAAO,EAAE,cAAc,GAAG,OAAO,CAAC,eAAe,CAAC;IAE/D;;;;;;;;;;OAUG;IACG,MAAM,CAAC,YAAY,EAAE,mBAAmB,GAAG,OAAO,CAAC,IAAI,CAAC;IAE9D;;;;;;;;;;;;;;;;OAgBG;IACG,MAAM,CAAC,UAAU,EAAE,OAAO,GAAG,OAAO,CAAC,eAAe,GAAG,IAAI,CAAC;CAgEnE"}
1
+ {"version":3,"file":"JsonRpcServer.d.mts","sourceRoot":"","sources":["../../src/v2/JsonRpcServer.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,mBAAmB,EAEnB,cAAc,EACd,eAAe,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H,SAAS,aAAa,CAAC,UAAmB;IACxC,IAAI,QAAQ,CAAC,UAAU,CAAC,IAAI,WAAW,CAAC,UAAU,EAAE,IAAI,CAAC,EAAE;QACzD,OAAO,CAAC,UAAU,CAAC,EAAE,EAAE,IAAI,CAAC,CAAC;KAC9B;IACD,OAAO,CAAC,SAAS,EAAE,KAAK,CAAC,CAAC;AAC5B,CAAC","sourcesContent":["import { rpcErrors, serializeError } from '@metamask/rpc-errors';\nimport type {\n JsonRpcNotification,\n JsonRpcParams,\n JsonRpcRequest,\n JsonRpcResponse,\n NonEmptyArray,\n} from '@metamask/utils';\nimport { hasProperty, isObject } from '@metamask/utils';\n\nimport type {\n JsonRpcMiddleware,\n MergedContextOf,\n RequestOf,\n ResultConstraint,\n} from './JsonRpcEngineV2';\nimport { JsonRpcEngineV2 } from './JsonRpcEngineV2';\nimport type { JsonRpcCall } from './utils';\nimport { getUniqueId } from '../getUniqueId';\n\ntype OnError = (error: unknown) => void;\n\ntype Options<Middleware extends JsonRpcMiddleware> = {\n onError?: OnError;\n} & (\n | {\n engine: JsonRpcEngineV2;\n }\n | {\n middleware: NonEmptyArray<Middleware>;\n }\n);\n\nconst jsonrpc = '2.0' as const;\n\n/**\n * A JSON-RPC server that handles requests and notifications.\n *\n * Essentially wraps a {@link JsonRpcEngineV2} in order to create a conformant\n * yet permissive JSON-RPC 2.0 server.\n *\n * Note that the server will accept both requests and notifications via {@link handle},\n * even if the underlying engine is only able to handle one or the other.\n *\n * @example\n * ```ts\n * const server = new JsonRpcServer({\n * engine,\n * onError,\n * });\n *\n * const response = await server.handle(request);\n * if ('result' in response) {\n * // Handle result\n * } else {\n * // Handle error\n * }\n * ```\n */\nexport class JsonRpcServer<\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 readonly #engine: JsonRpcEngineV2<\n RequestOf<Middleware>,\n MergedContextOf<Middleware>\n >;\n\n readonly #onError?: OnError | undefined;\n\n /**\n * Construct a new JSON-RPC server.\n *\n * @param options - The options for the server.\n * @param options.onError - The callback to handle errors thrown by the\n * engine. Errors always result in a failed response object, containing a\n * JSON-RPC 2.0 serialized version of the original error. If you need to\n * access the original error, use the `onError` callback.\n * @param options.engine - The engine to use. Mutually exclusive with\n * `middleware`.\n * @param options.middleware - The middleware to use. Mutually exclusive with\n * `engine`.\n */\n constructor(options: Options<Middleware>) {\n this.#onError = options.onError;\n\n if (hasProperty(options, 'engine')) {\n // @ts-expect-error - hasProperty fails to narrow the type.\n this.#engine = options.engine;\n } else {\n // @ts-expect-error - TypeScript complains that engine is of the wrong type, but clearly it's not.\n this.#engine = JsonRpcEngineV2.create({ middleware: options.middleware });\n }\n }\n\n /**\n * Handle a JSON-RPC request.\n *\n * This method never throws. For requests, a response is always returned.\n * All errors are passed to the engine's `onError` callback.\n *\n * **WARNING**: This method is unaware of the request type of the underlying\n * engine. The request will fail if the engine can only handle notifications.\n *\n * @param request - The request to handle.\n * @returns The JSON-RPC response.\n */\n async handle(request: JsonRpcRequest): Promise<JsonRpcResponse>;\n\n /**\n * Handle a JSON-RPC notification.\n *\n * This method never throws. For notifications, `undefined` is always returned.\n * All errors are passed to the engine's `onError` callback.\n *\n * **WARNING**: This method is unaware of the request type of the underlying\n * engine. The request will fail if the engine cannot handle notifications.\n *\n * @param notification - The notification to handle.\n */\n async handle(notification: JsonRpcNotification): Promise<void>;\n\n /**\n * Handle an alleged JSON-RPC request or notification. Permits any plain\n * object with `{ method: string }`, so long as any present JSON-RPC 2.0\n * properties are valid. If the object has an `id` property, it will be\n * treated as a request, otherwise it will be treated as a notification.\n *\n * This method never throws. All errors are passed to the engine's\n * `onError` callback. A JSON-RPC response is always returned for requests,\n * and `undefined` is returned for notifications.\n *\n * **WARNING**: The request will fail if its coerced type (i.e. request or\n * response) is not of the type expected by the underlying engine.\n *\n * @param rawRequest - The raw request to handle.\n * @returns The JSON-RPC response, or `undefined` if the request is a\n * notification.\n */\n async handle(rawRequest: unknown): Promise<JsonRpcResponse | void>;\n\n async handle(rawRequest: unknown): Promise<JsonRpcResponse | void> {\n // If rawRequest is not a notification, the originalId will be attached\n // to the response. We attach our own, trusted id in #coerceRequest()\n // while the request is being handled.\n const [originalId, isRequest] = getOriginalId(rawRequest);\n\n try {\n const request = this.#coerceRequest(rawRequest, isRequest);\n // @ts-expect-error - The request may not be of the type expected by the engine,\n // and we intentionally allow this to happen.\n const result = await this.#engine.handle(request);\n\n if (result !== undefined) {\n return {\n jsonrpc,\n // @ts-expect-error - Reassign the original id, regardless of its type.\n id: originalId,\n result,\n };\n }\n } catch (error) {\n this.#onError?.(error);\n\n if (isRequest) {\n return {\n jsonrpc,\n // @ts-expect-error - Reassign the original id, regardless of its type.\n id: originalId,\n error: serializeError(error, {\n shouldIncludeStack: false,\n shouldPreserveMessage: true,\n }),\n };\n }\n }\n return undefined;\n }\n\n #coerceRequest(rawRequest: unknown, isRequest: boolean): JsonRpcCall {\n if (!isMinimalRequest(rawRequest)) {\n throw rpcErrors.invalidRequest({\n data: {\n request: rawRequest,\n },\n });\n }\n\n const request: JsonRpcCall = {\n jsonrpc,\n method: rawRequest.method,\n };\n\n if (hasProperty(rawRequest, 'params')) {\n request.params = rawRequest.params as JsonRpcParams;\n }\n\n if (isRequest) {\n (request as JsonRpcRequest).id = getUniqueId();\n }\n\n return request;\n }\n}\n\n/**\n * The most minimally conformant request object that we will accept.\n */\ntype MinimalRequest = {\n method: string;\n params?: JsonRpcParams;\n} & Record<string, unknown>;\n\n/**\n * Check if an unvalidated request is a minimal request.\n *\n * @param rawRequest - The raw request to check.\n * @returns `true` if the request is a {@link MinimalRequest}, `false` otherwise.\n */\nfunction isMinimalRequest(rawRequest: unknown): rawRequest is MinimalRequest {\n return (\n isObject(rawRequest) &&\n hasProperty(rawRequest, 'method') &&\n typeof rawRequest.method === 'string' &&\n hasValidParams(rawRequest)\n );\n}\n\n/**\n * Check if a request has valid params, i.e. an array or object.\n * The contents of the params are not inspected.\n *\n * @param rawRequest - The request to check.\n * @returns `true` if the request has valid params, `false` otherwise.\n */\nfunction hasValidParams(\n rawRequest: Record<string, unknown>,\n): rawRequest is { params?: JsonRpcParams } {\n if (hasProperty(rawRequest, 'params')) {\n return Array.isArray(rawRequest.params) || isObject(rawRequest.params);\n }\n return true;\n}\n\n/**\n * Get the original id from a request.\n *\n * @param rawRequest - The request to get the original id from.\n * @returns The original id and a boolean indicating if the request is a request\n * (as opposed to a notification).\n */\nfunction getOriginalId(rawRequest: unknown): [unknown, boolean] {\n if (isObject(rawRequest) && hasProperty(rawRequest, 'id')) {\n return [rawRequest.id, true];\n }\n return [undefined, false];\n}\n"]}
1
+ {"version":3,"file":"JsonRpcServer.mjs","sourceRoot":"","sources":["../../src/v2/JsonRpcServer.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EAAE,SAAS,EAAE,cAAc,EAAE,6BAA6B;AAQjE,OAAO,EAAE,WAAW,EAAE,QAAQ,EAAE,wBAAwB;AAQxD,OAAO,EAAE,eAAe,EAAE,8BAA0B;AAEpD,OAAO,EAAE,WAAW,EAAE,2BAAuB;AAe7C,MAAM,OAAO,GAAG,KAAc,CAAC;AAE/B;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,MAAM,OAAO,aAAa;IAiBxB;;;;;;;;;;;;OAYG;IACH,YAAY,OAA4B;;QApB/B,wCAGP;QAEO,yCAA+B;QAgBtC,uBAAA,IAAI,0BAAY,OAAO,CAAC,OAAO,MAAA,CAAC;QAEhC,IAAI,WAAW,CAAC,OAAO,EAAE,QAAQ,CAAC,EAAE;YAClC,2DAA2D;YAC3D,uBAAA,IAAI,yBAAW,OAAO,CAAC,MAAM,MAAA,CAAC;SAC/B;aAAM;YACL,kGAAkG;YAClG,uBAAA,IAAI,yBAAW,eAAe,CAAC,MAAM,CAAC,EAAE,UAAU,EAAE,OAAO,CAAC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U,EAAE,QAAQ,CAAC,EAAE;QACrC,OAAO,CAAC,MAAM,GAAG,UAAU,CAAC,MAAuB,CAAC;KACrD;IAED,IAAI,SAAS,EAAE;QACZ,OAA0B,CAAC,EAAE,GAAG,WAAW,EAAE,CAAC;KAChD;IAED,OAAO,OAAO,CAAC;AACjB,CAAC;AAWH;;;;;GAKG;AACH,SAAS,gBAAgB,CAAC,UAAmB;IAC3C,OAAO,CACL,QAAQ,CAAC,UAAU,CAAC;QACpB,WAAW,CAAC,UAAU,EAAE,QAAQ,CAAC;QACjC,OAAO,UAAU,CAAC,MAAM,KAAK,QAAQ;QACrC,cAAc,CAAC,UAAU,CAAC,CAC3B,CAAC;AACJ,CAAC;AAED;;;;;;GAMG;AACH,SAAS,cAAc,CACrB,UAAmC;IAEnC,IAAI,WAAW,CAAC,UAAU,EAAE,QAAQ,CAAC,EAAE;QACrC,OAAO,KAAK,CAAC,OAAO,CAAC,UAAU,CAAC,MAAM,CAAC,IAAI,QAAQ,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;KACxE;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AAED;;;;;;GAMG;AACH,SAAS,aAAa,CAAC,UAAmB;IACxC,IAAI,QAAQ,CAAC,UAAU,CAAC,IAAI,WAAW,CAAC,UAAU,EAAE,IAAI,CAAC,EAAE;QACzD,OAAO,CAAC,UAAU,CAAC,EAAE,EAAE,IAAI,CAAC,CAAC;KAC9B;IACD,OAAO,CAAC,SAAS,EAAE,KAAK,CAAC,CAAC;AAC5B,CAAC","sourcesContent":["import { rpcErrors, serializeError } from '@metamask/rpc-errors';\nimport type {\n JsonRpcNotification,\n JsonRpcParams,\n JsonRpcRequest,\n JsonRpcResponse,\n NonEmptyArray,\n} from '@metamask/utils';\nimport { hasProperty, isObject } from '@metamask/utils';\n\nimport type {\n JsonRpcMiddleware,\n MergedContextOf,\n RequestOf,\n ResultConstraint,\n} from './JsonRpcEngineV2';\nimport { JsonRpcEngineV2 } from './JsonRpcEngineV2';\nimport type { JsonRpcCall } from './utils';\nimport { getUniqueId } from '../getUniqueId';\n\ntype OnError = (error: unknown) => void;\n\ntype Options<Middleware extends JsonRpcMiddleware> = {\n onError?: OnError;\n} & (\n | {\n engine: ReturnType<typeof JsonRpcEngineV2.create<Middleware>>;\n }\n | {\n middleware: NonEmptyArray<Middleware>;\n }\n);\n\nconst jsonrpc = '2.0' as const;\n\n/**\n * A JSON-RPC server that handles requests and notifications.\n *\n * Essentially wraps a {@link JsonRpcEngineV2} in order to create a conformant\n * yet permissive JSON-RPC 2.0 server.\n *\n * Note that the server will accept both requests and notifications via {@link handle},\n * even if the underlying engine is only able to handle one or the other.\n *\n * @example\n * ```ts\n * const server = new JsonRpcServer({\n * engine,\n * onError,\n * });\n *\n * const response = await server.handle(request);\n * if ('result' in response) {\n * // Handle result\n * } else {\n * // Handle error\n * }\n * ```\n */\nexport class JsonRpcServer<\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 readonly #engine: JsonRpcEngineV2<\n RequestOf<Middleware>,\n MergedContextOf<Middleware>\n >;\n\n readonly #onError?: OnError | undefined;\n\n /**\n * Construct a new JSON-RPC server.\n *\n * @param options - The options for the server.\n * @param options.onError - The callback to handle errors thrown by the\n * engine. Errors always result in a failed response object, containing a\n * JSON-RPC 2.0 serialized version of the original error. If you need to\n * access the original error, use the `onError` callback.\n * @param options.engine - The engine to use. Mutually exclusive with\n * `middleware`.\n * @param options.middleware - The middleware to use. Mutually exclusive with\n * `engine`.\n */\n constructor(options: Options<Middleware>) {\n this.#onError = options.onError;\n\n if (hasProperty(options, 'engine')) {\n // @ts-expect-error - hasProperty fails to narrow the type.\n this.#engine = options.engine;\n } else {\n // @ts-expect-error - TypeScript complains that engine is of the wrong type, but clearly it's not.\n this.#engine = JsonRpcEngineV2.create({ middleware: options.middleware });\n }\n }\n\n /**\n * Handle a JSON-RPC request.\n *\n * This method never throws. For requests, a response is always returned.\n * All errors are passed to the engine's `onError` callback.\n *\n * **WARNING**: This method is unaware of the request type of the underlying\n * engine. The request will fail if the engine can only handle notifications.\n *\n * @param request - The request to handle.\n * @returns The JSON-RPC response.\n */\n async handle(request: JsonRpcRequest): Promise<JsonRpcResponse>;\n\n /**\n * Handle a JSON-RPC notification.\n *\n * This method never throws. For notifications, `undefined` is always returned.\n * All errors are passed to the engine's `onError` callback.\n *\n * **WARNING**: This method is unaware of the request type of the underlying\n * engine. The request will fail if the engine cannot handle notifications.\n *\n * @param notification - The notification to handle.\n */\n async handle(notification: JsonRpcNotification): Promise<void>;\n\n /**\n * Handle an alleged JSON-RPC request or notification. Permits any plain\n * object with `{ method: string }`, so long as any present JSON-RPC 2.0\n * properties are valid. If the object has an `id` property, it will be\n * treated as a request, otherwise it will be treated as a notification.\n *\n * This method never throws. All errors are passed to the engine's\n * `onError` callback. A JSON-RPC response is always returned for requests,\n * and `undefined` is returned for notifications.\n *\n * **WARNING**: The request will fail if its coerced type (i.e. request or\n * response) is not of the type expected by the underlying engine.\n *\n * @param rawRequest - The raw request to handle.\n * @returns The JSON-RPC response, or `undefined` if the request is a\n * notification.\n */\n async handle(rawRequest: unknown): Promise<JsonRpcResponse | void>;\n\n async handle(rawRequest: unknown): Promise<JsonRpcResponse | void> {\n // If rawRequest is not a notification, the originalId will be attached\n // to the response. We attach our own, trusted id in #coerceRequest()\n // while the request is being handled.\n const [originalId, isRequest] = getOriginalId(rawRequest);\n\n try {\n const request = this.#coerceRequest(rawRequest, isRequest);\n // @ts-expect-error - The request may not be of the type expected by the engine,\n // and we intentionally allow this to happen.\n const result = await this.#engine.handle(request);\n\n if (result !== undefined) {\n return {\n jsonrpc,\n // @ts-expect-error - Reassign the original id, regardless of its type.\n id: originalId,\n result,\n };\n }\n } catch (error) {\n this.#onError?.(error);\n\n if (isRequest) {\n return {\n jsonrpc,\n // @ts-expect-error - Reassign the original id, regardless of its type.\n id: originalId,\n error: serializeError(error, {\n shouldIncludeStack: false,\n shouldPreserveMessage: true,\n }),\n };\n }\n }\n return undefined;\n }\n\n #coerceRequest(rawRequest: unknown, isRequest: boolean): JsonRpcCall {\n if (!isMinimalRequest(rawRequest)) {\n throw rpcErrors.invalidRequest({\n data: {\n request: rawRequest,\n },\n });\n }\n\n const request: JsonRpcCall = {\n jsonrpc,\n method: rawRequest.method,\n };\n\n if (hasProperty(rawRequest, 'params')) {\n request.params = rawRequest.params as JsonRpcParams;\n }\n\n if (isRequest) {\n (request as JsonRpcRequest).id = getUniqueId();\n }\n\n return request;\n }\n}\n\n/**\n * The most minimally conformant request object that we will accept.\n */\ntype MinimalRequest = {\n method: string;\n params?: JsonRpcParams;\n} & Record<string, unknown>;\n\n/**\n * Check if an unvalidated request is a minimal request.\n *\n * @param rawRequest - The raw request to check.\n * @returns `true` if the request is a {@link MinimalRequest}, `false` otherwise.\n */\nfunction isMinimalRequest(rawRequest: unknown): rawRequest is MinimalRequest {\n return (\n isObject(rawRequest) &&\n hasProperty(rawRequest, 'method') &&\n typeof rawRequest.method === 'string' &&\n hasValidParams(rawRequest)\n );\n}\n\n/**\n * Check if a request has valid params, i.e. an array or object.\n * The contents of the params are not inspected.\n *\n * @param rawRequest - The request to check.\n * @returns `true` if the request has valid params, `false` otherwise.\n */\nfunction hasValidParams(\n rawRequest: Record<string, unknown>,\n): rawRequest is { params?: JsonRpcParams } {\n if (hasProperty(rawRequest, 'params')) {\n return Array.isArray(rawRequest.params) || isObject(rawRequest.params);\n }\n return true;\n}\n\n/**\n * Get the original id from a request.\n *\n * @param rawRequest - The request to get the original id from.\n * @returns The original id and a boolean indicating if the request is a request\n * (as opposed to a notification).\n */\nfunction getOriginalId(rawRequest: unknown): [unknown, boolean] {\n if (isObject(rawRequest) && hasProperty(rawRequest, 'id')) {\n return [rawRequest.id, true];\n }\n return [undefined, false];\n}\n"]}
@@ -2,20 +2,26 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.asLegacyMiddleware = void 0;
4
4
  const compatibility_utils_1 = require("./compatibility-utils.cjs");
5
+ const JsonRpcEngineV2_1 = require("./JsonRpcEngineV2.cjs");
5
6
  const __1 = require("../index.cjs");
6
7
  /**
7
- * Convert a {@link JsonRpcEngineV2} into a legacy middleware.
8
+ * The asLegacyMiddleware implementation.
8
9
  *
9
- * @param engine - The engine to convert.
10
+ * @param engineOrMiddleware - A V2 engine or V2 middleware.
11
+ * @param rest - Any additional V2 middleware when the first argument is a middleware.
10
12
  * @returns The legacy middleware.
11
13
  */
12
- function asLegacyMiddleware(engine) {
13
- const middleware = engine.asMiddleware();
14
+ function asLegacyMiddleware(engineOrMiddleware, ...rest) {
15
+ const v2Middleware = typeof engineOrMiddleware === 'function'
16
+ ? JsonRpcEngineV2_1.JsonRpcEngineV2.create({
17
+ middleware: [engineOrMiddleware, ...rest],
18
+ }).asMiddleware()
19
+ : engineOrMiddleware.asMiddleware();
14
20
  return (0, __1.createAsyncMiddleware)(async (req, res, next) => {
15
21
  const request = (0, compatibility_utils_1.fromLegacyRequest)(req);
16
22
  const context = (0, compatibility_utils_1.makeContext)(req);
17
23
  let modifiedRequest;
18
- const result = await middleware({
24
+ const result = await v2Middleware({
19
25
  request,
20
26
  context,
21
27
  next: (finalRequest) => {
@@ -1 +1 @@
1
- {"version":3,"file":"asLegacyMiddleware.cjs","sourceRoot":"","sources":["../../src/v2/asLegacyMiddleware.ts"],"names":[],"mappings":";;;AAEA,mEAK+B;AAE/B,oCAA2C;AAG3C;;;;;GAKG;AACH,SAAgB,kBAAkB,CAIhC,MAAgC;IAEhC,MAAM,UAAU,GAAG,MAAM,CAAC,YAAY,EAAE,CAAC;IACzC,OAAO,IAAA,yBAAqB,EAAC,KAAK,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;QACpD,MAAM,OAAO,GAAG,IAAA,uCAAiB,EAAC,GAAc,CAAC,CAAC;QAClD,MAAM,OAAO,GAAG,IAAA,iCAAW,EAAC,GAAG,CAAC,CAAC;QACjC,IAAI,eAAoC,CAAC;QAEzC,MAAM,MAAM,GAAG,MAAM,UAAU,CAAC;YAC9B,OAAO;YACP,OAAO;YACP,IAAI,EAAE,CAAC,YAAY,EAAE,EAAE;gBACrB,eAAe,GAAG,YAAY,CAAC;gBAC/B,OAAO,OAAO,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;YACpC,CAAC;SACF,CAAC,CAAC;QAEH,IAAI,eAAe,KAAK,SAAS,IAAI,eAAe,KAAK,OAAO,EAAE;YAChE,MAAM,CAAC,MAAM,CAAC,GAAG,EAAE,IAAA,+BAAS,EAAC,eAAe,CAAC,CAAC,CAAC;SAChD;QACD,IAAA,wCAAkB,EAAC,GAAG,EAAE,OAAO,CAAC,CAAC;QAEjC,IAAI,MAAM,KAAK,SAAS,EAAE;YACxB,qEAAqE;YACrE,GAAG,CAAC,MAAM,GAAG,IAAA,+BAAS,EAAC,MAAM,CAAyC,CAAC;YACvE,OAAO,SAAS,CAAC;SAClB;QACD,OAAO,IAAI,EAAE,CAAC;IAChB,CAAC,CAAC,CAAC;AACL,CAAC;AAjCD,gDAiCC","sourcesContent":["import type { JsonRpcParams, JsonRpcRequest } from '@metamask/utils';\n\nimport {\n deepClone,\n fromLegacyRequest,\n makeContext,\n propagateToRequest,\n} from './compatibility-utils';\nimport type { JsonRpcEngineV2, ResultConstraint } from './JsonRpcEngineV2';\nimport { createAsyncMiddleware } from '..';\nimport type { JsonRpcMiddleware as LegacyMiddleware } from '..';\n\n/**\n * Convert a {@link JsonRpcEngineV2} into a legacy middleware.\n *\n * @param engine - The engine to convert.\n * @returns The legacy middleware.\n */\nexport function asLegacyMiddleware<\n Params extends JsonRpcParams,\n Request extends JsonRpcRequest<Params>,\n>(\n engine: JsonRpcEngineV2<Request>,\n): LegacyMiddleware<Params, ResultConstraint<Request>> {\n const middleware = engine.asMiddleware();\n return createAsyncMiddleware(async (req, res, next) => {\n const request = fromLegacyRequest(req as Request);\n const context = makeContext(req);\n let modifiedRequest: Request | undefined;\n\n const result = await middleware({\n request,\n context,\n next: (finalRequest) => {\n modifiedRequest = finalRequest;\n return Promise.resolve(undefined);\n },\n });\n\n if (modifiedRequest !== undefined && modifiedRequest !== request) {\n Object.assign(req, deepClone(modifiedRequest));\n }\n propagateToRequest(req, context);\n\n if (result !== undefined) {\n // Unclear why the `as unknown` is needed here, but the cast is safe.\n res.result = deepClone(result) as unknown as ResultConstraint<Request>;\n return undefined;\n }\n return next();\n });\n}\n"]}
1
+ {"version":3,"file":"asLegacyMiddleware.cjs","sourceRoot":"","sources":["../../src/v2/asLegacyMiddleware.ts"],"names":[],"mappings":";;;AAEA,mEAK+B;AAE/B,2DAAoD;AACpD,oCAA2C;AA6B3C;;;;;;GAMG;AACH,SAAgB,kBAAkB,CAIhC,kBAEyD,EACzD,GAAG,IAA6D;IAEhE,MAAM,YAAY,GAChB,OAAO,kBAAkB,KAAK,UAAU;QACtC,CAAC,CAAC,iCAAe,CAAC,MAAM,CAAC;YACrB,UAAU,EAAE,CAAC,kBAAkB,EAAE,GAAG,IAAI,CAAC;SAC1C,CAAC,CAAC,YAAY,EAAE;QACnB,CAAC,CAAC,kBAAkB,CAAC,YAAY,EAAE,CAAC;IAExC,OAAO,IAAA,yBAAqB,EAAC,KAAK,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;QACpD,MAAM,OAAO,GAAG,IAAA,uCAAiB,EAAC,GAAc,CAAC,CAAC;QAClD,MAAM,OAAO,GAAG,IAAA,iCAAW,EAAC,GAAG,CAAC,CAAC;QACjC,IAAI,eAAoC,CAAC;QAEzC,MAAM,MAAM,GAAG,MAAM,YAAY,CAAC;YAChC,OAAO;YACP,OAAO;YACP,IAAI,EAAE,CAAC,YAAY,EAAE,EAAE;gBACrB,eAAe,GAAG,YAAY,CAAC;gBAC/B,OAAO,OAAO,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;YACpC,CAAC;SACF,CAAC,CAAC;QAEH,IAAI,eAAe,KAAK,SAAS,IAAI,eAAe,KAAK,OAAO,EAAE;YAChE,MAAM,CAAC,MAAM,CAAC,GAAG,EAAE,IAAA,+BAAS,EAAC,eAAe,CAAC,CAAC,CAAC;SAChD;QACD,IAAA,wCAAkB,EAAC,GAAG,EAAE,OAAO,CAAC,CAAC;QAEjC,IAAI,MAAM,KAAK,SAAS,EAAE;YACxB,qEAAqE;YACrE,GAAG,CAAC,MAAM,GAAG,IAAA,+BAAS,EAAC,MAAM,CAAyC,CAAC;YACvE,OAAO,SAAS,CAAC;SAClB;QACD,OAAO,IAAI,EAAE,CAAC;IAChB,CAAC,CAAC,CAAC;AACL,CAAC;AA1CD,gDA0CC","sourcesContent":["import type { JsonRpcParams, JsonRpcRequest } from '@metamask/utils';\n\nimport {\n deepClone,\n fromLegacyRequest,\n makeContext,\n propagateToRequest,\n} from './compatibility-utils';\nimport type { JsonRpcMiddleware, ResultConstraint } from './JsonRpcEngineV2';\nimport { JsonRpcEngineV2 } from './JsonRpcEngineV2';\nimport { createAsyncMiddleware } from '..';\nimport type { JsonRpcMiddleware as LegacyMiddleware } from '..';\n\n/**\n * Convert a {@link JsonRpcEngineV2} into a legacy middleware.\n *\n * @param engine - The engine to convert.\n * @returns The legacy middleware.\n */\nexport function asLegacyMiddleware<\n Params extends JsonRpcParams,\n Request extends JsonRpcRequest<Params>,\n>(\n engine: JsonRpcEngineV2<Request>,\n): LegacyMiddleware<Params, ResultConstraint<Request>>;\n\n/**\n * Convert one or more V2 middlewares into a legacy middleware.\n *\n * @param middleware - The V2 middleware(s) to convert.\n * @returns The legacy middleware.\n */\nexport function asLegacyMiddleware<\n Params extends JsonRpcParams,\n Request extends JsonRpcRequest<Params>,\n>(\n ...middleware: JsonRpcMiddleware<Request, ResultConstraint<Request>>[]\n): LegacyMiddleware<Params, ResultConstraint<Request>>;\n\n/**\n * The asLegacyMiddleware implementation.\n *\n * @param engineOrMiddleware - A V2 engine or V2 middleware.\n * @param rest - Any additional V2 middleware when the first argument is a middleware.\n * @returns The legacy middleware.\n */\nexport function asLegacyMiddleware<\n Params extends JsonRpcParams,\n Request extends JsonRpcRequest<Params>,\n>(\n engineOrMiddleware:\n | JsonRpcEngineV2<Request>\n | JsonRpcMiddleware<Request, ResultConstraint<Request>>,\n ...rest: JsonRpcMiddleware<Request, ResultConstraint<Request>>[]\n): LegacyMiddleware<Params, ResultConstraint<Request>> {\n const v2Middleware =\n typeof engineOrMiddleware === 'function'\n ? JsonRpcEngineV2.create({\n middleware: [engineOrMiddleware, ...rest],\n }).asMiddleware()\n : engineOrMiddleware.asMiddleware();\n\n return createAsyncMiddleware(async (req, res, next) => {\n const request = fromLegacyRequest(req as Request);\n const context = makeContext(req);\n let modifiedRequest: Request | undefined;\n\n const result = await v2Middleware({\n request,\n context,\n next: (finalRequest) => {\n modifiedRequest = finalRequest;\n return Promise.resolve(undefined);\n },\n });\n\n if (modifiedRequest !== undefined && modifiedRequest !== request) {\n Object.assign(req, deepClone(modifiedRequest));\n }\n propagateToRequest(req, context);\n\n if (result !== undefined) {\n // Unclear why the `as unknown` is needed here, but the cast is safe.\n res.result = deepClone(result) as unknown as ResultConstraint<Request>;\n return undefined;\n }\n return next();\n });\n}\n"]}
@@ -1,5 +1,6 @@
1
1
  import type { JsonRpcParams, JsonRpcRequest } from "@metamask/utils";
2
- import type { JsonRpcEngineV2, ResultConstraint } from "./JsonRpcEngineV2.cjs";
2
+ import type { JsonRpcMiddleware, ResultConstraint } from "./JsonRpcEngineV2.cjs";
3
+ import { JsonRpcEngineV2 } from "./JsonRpcEngineV2.cjs";
3
4
  import type { JsonRpcMiddleware as LegacyMiddleware } from "../index.cjs";
4
5
  /**
5
6
  * Convert a {@link JsonRpcEngineV2} into a legacy middleware.
@@ -8,4 +9,11 @@ import type { JsonRpcMiddleware as LegacyMiddleware } from "../index.cjs";
8
9
  * @returns The legacy middleware.
9
10
  */
10
11
  export declare function asLegacyMiddleware<Params extends JsonRpcParams, Request extends JsonRpcRequest<Params>>(engine: JsonRpcEngineV2<Request>): LegacyMiddleware<Params, ResultConstraint<Request>>;
12
+ /**
13
+ * Convert one or more V2 middlewares into a legacy middleware.
14
+ *
15
+ * @param middleware - The V2 middleware(s) to convert.
16
+ * @returns The legacy middleware.
17
+ */
18
+ export declare function asLegacyMiddleware<Params extends JsonRpcParams, Request extends JsonRpcRequest<Params>>(...middleware: JsonRpcMiddleware<Request, ResultConstraint<Request>>[]): LegacyMiddleware<Params, ResultConstraint<Request>>;
11
19
  //# sourceMappingURL=asLegacyMiddleware.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"asLegacyMiddleware.d.cts","sourceRoot":"","sources":["../../src/v2/asLegacyMiddleware.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,cAAc,EAAE,wBAAwB;AAQrE,OAAO,KAAK,EAAE,eAAe,EAAE,gBAAgB,EAAE,8BAA0B;AAE3E,OAAO,KAAK,EAAE,iBAAiB,IAAI,gBAAgB,EAAE,qBAAW;AAEhE;;;;;GAKG;AACH,wBAAgB,kBAAkB,CAChC,MAAM,SAAS,aAAa,EAC5B,OAAO,SAAS,cAAc,CAAC,MAAM,CAAC,EAEtC,MAAM,EAAE,eAAe,CAAC,OAAO,CAAC,GAC/B,gBAAgB,CAAC,MAAM,EAAE,gBAAgB,CAAC,OAAO,CAAC,CAAC,CA4BrD"}
1
+ {"version":3,"file":"asLegacyMiddleware.d.cts","sourceRoot":"","sources":["../../src/v2/asLegacyMiddleware.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,cAAc,EAAE,wBAAwB;AAQrE,OAAO,KAAK,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,8BAA0B;AAC7E,OAAO,EAAE,eAAe,EAAE,8BAA0B;AAEpD,OAAO,KAAK,EAAE,iBAAiB,IAAI,gBAAgB,EAAE,qBAAW;AAEhE;;;;;GAKG;AACH,wBAAgB,kBAAkB,CAChC,MAAM,SAAS,aAAa,EAC5B,OAAO,SAAS,cAAc,CAAC,MAAM,CAAC,EAEtC,MAAM,EAAE,eAAe,CAAC,OAAO,CAAC,GAC/B,gBAAgB,CAAC,MAAM,EAAE,gBAAgB,CAAC,OAAO,CAAC,CAAC,CAAC;AAEvD;;;;;GAKG;AACH,wBAAgB,kBAAkB,CAChC,MAAM,SAAS,aAAa,EAC5B,OAAO,SAAS,cAAc,CAAC,MAAM,CAAC,EAEtC,GAAG,UAAU,EAAE,iBAAiB,CAAC,OAAO,EAAE,gBAAgB,CAAC,OAAO,CAAC,CAAC,EAAE,GACrE,gBAAgB,CAAC,MAAM,EAAE,gBAAgB,CAAC,OAAO,CAAC,CAAC,CAAC"}
@@ -1,5 +1,6 @@
1
1
  import type { JsonRpcParams, JsonRpcRequest } from "@metamask/utils";
2
- import type { JsonRpcEngineV2, ResultConstraint } from "./JsonRpcEngineV2.mjs";
2
+ import type { JsonRpcMiddleware, ResultConstraint } from "./JsonRpcEngineV2.mjs";
3
+ import { JsonRpcEngineV2 } from "./JsonRpcEngineV2.mjs";
3
4
  import type { JsonRpcMiddleware as LegacyMiddleware } from "../index.mjs";
4
5
  /**
5
6
  * Convert a {@link JsonRpcEngineV2} into a legacy middleware.
@@ -8,4 +9,11 @@ import type { JsonRpcMiddleware as LegacyMiddleware } from "../index.mjs";
8
9
  * @returns The legacy middleware.
9
10
  */
10
11
  export declare function asLegacyMiddleware<Params extends JsonRpcParams, Request extends JsonRpcRequest<Params>>(engine: JsonRpcEngineV2<Request>): LegacyMiddleware<Params, ResultConstraint<Request>>;
12
+ /**
13
+ * Convert one or more V2 middlewares into a legacy middleware.
14
+ *
15
+ * @param middleware - The V2 middleware(s) to convert.
16
+ * @returns The legacy middleware.
17
+ */
18
+ export declare function asLegacyMiddleware<Params extends JsonRpcParams, Request extends JsonRpcRequest<Params>>(...middleware: JsonRpcMiddleware<Request, ResultConstraint<Request>>[]): LegacyMiddleware<Params, ResultConstraint<Request>>;
11
19
  //# sourceMappingURL=asLegacyMiddleware.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"asLegacyMiddleware.d.mts","sourceRoot":"","sources":["../../src/v2/asLegacyMiddleware.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,cAAc,EAAE,wBAAwB;AAQrE,OAAO,KAAK,EAAE,eAAe,EAAE,gBAAgB,EAAE,8BAA0B;AAE3E,OAAO,KAAK,EAAE,iBAAiB,IAAI,gBAAgB,EAAE,qBAAW;AAEhE;;;;;GAKG;AACH,wBAAgB,kBAAkB,CAChC,MAAM,SAAS,aAAa,EAC5B,OAAO,SAAS,cAAc,CAAC,MAAM,CAAC,EAEtC,MAAM,EAAE,eAAe,CAAC,OAAO,CAAC,GAC/B,gBAAgB,CAAC,MAAM,EAAE,gBAAgB,CAAC,OAAO,CAAC,CAAC,CA4BrD"}
1
+ {"version":3,"file":"asLegacyMiddleware.d.mts","sourceRoot":"","sources":["../../src/v2/asLegacyMiddleware.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,cAAc,EAAE,wBAAwB;AAQrE,OAAO,KAAK,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,8BAA0B;AAC7E,OAAO,EAAE,eAAe,EAAE,8BAA0B;AAEpD,OAAO,KAAK,EAAE,iBAAiB,IAAI,gBAAgB,EAAE,qBAAW;AAEhE;;;;;GAKG;AACH,wBAAgB,kBAAkB,CAChC,MAAM,SAAS,aAAa,EAC5B,OAAO,SAAS,cAAc,CAAC,MAAM,CAAC,EAEtC,MAAM,EAAE,eAAe,CAAC,OAAO,CAAC,GAC/B,gBAAgB,CAAC,MAAM,EAAE,gBAAgB,CAAC,OAAO,CAAC,CAAC,CAAC;AAEvD;;;;;GAKG;AACH,wBAAgB,kBAAkB,CAChC,MAAM,SAAS,aAAa,EAC5B,OAAO,SAAS,cAAc,CAAC,MAAM,CAAC,EAEtC,GAAG,UAAU,EAAE,iBAAiB,CAAC,OAAO,EAAE,gBAAgB,CAAC,OAAO,CAAC,CAAC,EAAE,GACrE,gBAAgB,CAAC,MAAM,EAAE,gBAAgB,CAAC,OAAO,CAAC,CAAC,CAAC"}
@@ -1,18 +1,24 @@
1
1
  import { deepClone, fromLegacyRequest, makeContext, propagateToRequest } from "./compatibility-utils.mjs";
2
+ import { JsonRpcEngineV2 } from "./JsonRpcEngineV2.mjs";
2
3
  import { createAsyncMiddleware } from "../index.mjs";
3
4
  /**
4
- * Convert a {@link JsonRpcEngineV2} into a legacy middleware.
5
+ * The asLegacyMiddleware implementation.
5
6
  *
6
- * @param engine - The engine to convert.
7
+ * @param engineOrMiddleware - A V2 engine or V2 middleware.
8
+ * @param rest - Any additional V2 middleware when the first argument is a middleware.
7
9
  * @returns The legacy middleware.
8
10
  */
9
- export function asLegacyMiddleware(engine) {
10
- const middleware = engine.asMiddleware();
11
+ export function asLegacyMiddleware(engineOrMiddleware, ...rest) {
12
+ const v2Middleware = typeof engineOrMiddleware === 'function'
13
+ ? JsonRpcEngineV2.create({
14
+ middleware: [engineOrMiddleware, ...rest],
15
+ }).asMiddleware()
16
+ : engineOrMiddleware.asMiddleware();
11
17
  return createAsyncMiddleware(async (req, res, next) => {
12
18
  const request = fromLegacyRequest(req);
13
19
  const context = makeContext(req);
14
20
  let modifiedRequest;
15
- const result = await middleware({
21
+ const result = await v2Middleware({
16
22
  request,
17
23
  context,
18
24
  next: (finalRequest) => {
@@ -1 +1 @@
1
- {"version":3,"file":"asLegacyMiddleware.mjs","sourceRoot":"","sources":["../../src/v2/asLegacyMiddleware.ts"],"names":[],"mappings":"AAEA,OAAO,EACL,SAAS,EACT,iBAAiB,EACjB,WAAW,EACX,kBAAkB,EACnB,kCAA8B;AAE/B,OAAO,EAAE,qBAAqB,EAAE,qBAAW;AAG3C;;;;;GAKG;AACH,MAAM,UAAU,kBAAkB,CAIhC,MAAgC;IAEhC,MAAM,UAAU,GAAG,MAAM,CAAC,YAAY,EAAE,CAAC;IACzC,OAAO,qBAAqB,CAAC,KAAK,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;QACpD,MAAM,OAAO,GAAG,iBAAiB,CAAC,GAAc,CAAC,CAAC;QAClD,MAAM,OAAO,GAAG,WAAW,CAAC,GAAG,CAAC,CAAC;QACjC,IAAI,eAAoC,CAAC;QAEzC,MAAM,MAAM,GAAG,MAAM,UAAU,CAAC;YAC9B,OAAO;YACP,OAAO;YACP,IAAI,EAAE,CAAC,YAAY,EAAE,EAAE;gBACrB,eAAe,GAAG,YAAY,CAAC;gBAC/B,OAAO,OAAO,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;YACpC,CAAC;SACF,CAAC,CAAC;QAEH,IAAI,eAAe,KAAK,SAAS,IAAI,eAAe,KAAK,OAAO,EAAE;YAChE,MAAM,CAAC,MAAM,CAAC,GAAG,EAAE,SAAS,CAAC,eAAe,CAAC,CAAC,CAAC;SAChD;QACD,kBAAkB,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;QAEjC,IAAI,MAAM,KAAK,SAAS,EAAE;YACxB,qEAAqE;YACrE,GAAG,CAAC,MAAM,GAAG,SAAS,CAAC,MAAM,CAAyC,CAAC;YACvE,OAAO,SAAS,CAAC;SAClB;QACD,OAAO,IAAI,EAAE,CAAC;IAChB,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { JsonRpcParams, JsonRpcRequest } from '@metamask/utils';\n\nimport {\n deepClone,\n fromLegacyRequest,\n makeContext,\n propagateToRequest,\n} from './compatibility-utils';\nimport type { JsonRpcEngineV2, ResultConstraint } from './JsonRpcEngineV2';\nimport { createAsyncMiddleware } from '..';\nimport type { JsonRpcMiddleware as LegacyMiddleware } from '..';\n\n/**\n * Convert a {@link JsonRpcEngineV2} into a legacy middleware.\n *\n * @param engine - The engine to convert.\n * @returns The legacy middleware.\n */\nexport function asLegacyMiddleware<\n Params extends JsonRpcParams,\n Request extends JsonRpcRequest<Params>,\n>(\n engine: JsonRpcEngineV2<Request>,\n): LegacyMiddleware<Params, ResultConstraint<Request>> {\n const middleware = engine.asMiddleware();\n return createAsyncMiddleware(async (req, res, next) => {\n const request = fromLegacyRequest(req as Request);\n const context = makeContext(req);\n let modifiedRequest: Request | undefined;\n\n const result = await middleware({\n request,\n context,\n next: (finalRequest) => {\n modifiedRequest = finalRequest;\n return Promise.resolve(undefined);\n },\n });\n\n if (modifiedRequest !== undefined && modifiedRequest !== request) {\n Object.assign(req, deepClone(modifiedRequest));\n }\n propagateToRequest(req, context);\n\n if (result !== undefined) {\n // Unclear why the `as unknown` is needed here, but the cast is safe.\n res.result = deepClone(result) as unknown as ResultConstraint<Request>;\n return undefined;\n }\n return next();\n });\n}\n"]}
1
+ {"version":3,"file":"asLegacyMiddleware.mjs","sourceRoot":"","sources":["../../src/v2/asLegacyMiddleware.ts"],"names":[],"mappings":"AAEA,OAAO,EACL,SAAS,EACT,iBAAiB,EACjB,WAAW,EACX,kBAAkB,EACnB,kCAA8B;AAE/B,OAAO,EAAE,eAAe,EAAE,8BAA0B;AACpD,OAAO,EAAE,qBAAqB,EAAE,qBAAW;AA6B3C;;;;;;GAMG;AACH,MAAM,UAAU,kBAAkB,CAIhC,kBAEyD,EACzD,GAAG,IAA6D;IAEhE,MAAM,YAAY,GAChB,OAAO,kBAAkB,KAAK,UAAU;QACtC,CAAC,CAAC,eAAe,CAAC,MAAM,CAAC;YACrB,UAAU,EAAE,CAAC,kBAAkB,EAAE,GAAG,IAAI,CAAC;SAC1C,CAAC,CAAC,YAAY,EAAE;QACnB,CAAC,CAAC,kBAAkB,CAAC,YAAY,EAAE,CAAC;IAExC,OAAO,qBAAqB,CAAC,KAAK,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;QACpD,MAAM,OAAO,GAAG,iBAAiB,CAAC,GAAc,CAAC,CAAC;QAClD,MAAM,OAAO,GAAG,WAAW,CAAC,GAAG,CAAC,CAAC;QACjC,IAAI,eAAoC,CAAC;QAEzC,MAAM,MAAM,GAAG,MAAM,YAAY,CAAC;YAChC,OAAO;YACP,OAAO;YACP,IAAI,EAAE,CAAC,YAAY,EAAE,EAAE;gBACrB,eAAe,GAAG,YAAY,CAAC;gBAC/B,OAAO,OAAO,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;YACpC,CAAC;SACF,CAAC,CAAC;QAEH,IAAI,eAAe,KAAK,SAAS,IAAI,eAAe,KAAK,OAAO,EAAE;YAChE,MAAM,CAAC,MAAM,CAAC,GAAG,EAAE,SAAS,CAAC,eAAe,CAAC,CAAC,CAAC;SAChD;QACD,kBAAkB,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;QAEjC,IAAI,MAAM,KAAK,SAAS,EAAE;YACxB,qEAAqE;YACrE,GAAG,CAAC,MAAM,GAAG,SAAS,CAAC,MAAM,CAAyC,CAAC;YACvE,OAAO,SAAS,CAAC;SAClB;QACD,OAAO,IAAI,EAAE,CAAC;IAChB,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { JsonRpcParams, JsonRpcRequest } from '@metamask/utils';\n\nimport {\n deepClone,\n fromLegacyRequest,\n makeContext,\n propagateToRequest,\n} from './compatibility-utils';\nimport type { JsonRpcMiddleware, ResultConstraint } from './JsonRpcEngineV2';\nimport { JsonRpcEngineV2 } from './JsonRpcEngineV2';\nimport { createAsyncMiddleware } from '..';\nimport type { JsonRpcMiddleware as LegacyMiddleware } from '..';\n\n/**\n * Convert a {@link JsonRpcEngineV2} into a legacy middleware.\n *\n * @param engine - The engine to convert.\n * @returns The legacy middleware.\n */\nexport function asLegacyMiddleware<\n Params extends JsonRpcParams,\n Request extends JsonRpcRequest<Params>,\n>(\n engine: JsonRpcEngineV2<Request>,\n): LegacyMiddleware<Params, ResultConstraint<Request>>;\n\n/**\n * Convert one or more V2 middlewares into a legacy middleware.\n *\n * @param middleware - The V2 middleware(s) to convert.\n * @returns The legacy middleware.\n */\nexport function asLegacyMiddleware<\n Params extends JsonRpcParams,\n Request extends JsonRpcRequest<Params>,\n>(\n ...middleware: JsonRpcMiddleware<Request, ResultConstraint<Request>>[]\n): LegacyMiddleware<Params, ResultConstraint<Request>>;\n\n/**\n * The asLegacyMiddleware implementation.\n *\n * @param engineOrMiddleware - A V2 engine or V2 middleware.\n * @param rest - Any additional V2 middleware when the first argument is a middleware.\n * @returns The legacy middleware.\n */\nexport function asLegacyMiddleware<\n Params extends JsonRpcParams,\n Request extends JsonRpcRequest<Params>,\n>(\n engineOrMiddleware:\n | JsonRpcEngineV2<Request>\n | JsonRpcMiddleware<Request, ResultConstraint<Request>>,\n ...rest: JsonRpcMiddleware<Request, ResultConstraint<Request>>[]\n): LegacyMiddleware<Params, ResultConstraint<Request>> {\n const v2Middleware =\n typeof engineOrMiddleware === 'function'\n ? JsonRpcEngineV2.create({\n middleware: [engineOrMiddleware, ...rest],\n }).asMiddleware()\n : engineOrMiddleware.asMiddleware();\n\n return createAsyncMiddleware(async (req, res, next) => {\n const request = fromLegacyRequest(req as Request);\n const context = makeContext(req);\n let modifiedRequest: Request | undefined;\n\n const result = await v2Middleware({\n request,\n context,\n next: (finalRequest) => {\n modifiedRequest = finalRequest;\n return Promise.resolve(undefined);\n },\n });\n\n if (modifiedRequest !== undefined && modifiedRequest !== request) {\n Object.assign(req, deepClone(modifiedRequest));\n }\n propagateToRequest(req, context);\n\n if (result !== undefined) {\n // Unclear why the `as unknown` is needed here, but the cast is safe.\n res.result = deepClone(result) as unknown as ResultConstraint<Request>;\n return undefined;\n }\n return next();\n });\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metamask-previews/json-rpc-engine",
3
- "version": "10.1.1-preview-eee46d4b",
3
+ "version": "10.1.1-preview-ac95634",
4
4
  "description": "A tool for processing JSON-RPC messages",
5
5
  "keywords": [
6
6
  "MetaMask",