@metamask-previews/json-rpc-engine 10.5.0-preview-8bfa290fb → 11.0.0-preview-0a30e47

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (208) hide show
  1. package/CHANGELOG.md +10 -2
  2. package/dist/{JsonRpcEngine.d.mts → JsonRpcEngine.d.ts} +3 -3
  3. package/dist/JsonRpcEngine.d.ts.map +1 -0
  4. package/dist/JsonRpcEngine.js +386 -0
  5. package/dist/JsonRpcEngine.js.map +1 -0
  6. package/dist/{asV2Middleware.d.cts → asV2Middleware.d.ts} +6 -6
  7. package/dist/asV2Middleware.d.ts.map +1 -0
  8. package/dist/{asV2Middleware.mjs → asV2Middleware.js} +5 -5
  9. package/dist/asV2Middleware.js.map +1 -0
  10. package/dist/{createAsyncMiddleware.d.mts → createAsyncMiddleware.d.ts} +3 -3
  11. package/dist/createAsyncMiddleware.d.ts.map +1 -0
  12. package/dist/{createAsyncMiddleware.mjs → createAsyncMiddleware.js} +1 -1
  13. package/dist/createAsyncMiddleware.js.map +1 -0
  14. package/dist/{createMethodMiddleware.d.mts → createMethodMiddleware.d.ts} +6 -6
  15. package/dist/createMethodMiddleware.d.ts.map +1 -0
  16. package/dist/{createMethodMiddleware.mjs → createMethodMiddleware.js} +3 -3
  17. package/dist/createMethodMiddleware.js.map +1 -0
  18. package/dist/{createOriginMiddleware.d.cts → createOriginMiddleware.d.ts} +3 -3
  19. package/dist/createOriginMiddleware.d.ts.map +1 -0
  20. package/dist/{createOriginMiddleware.mjs → createOriginMiddleware.js} +1 -1
  21. package/dist/createOriginMiddleware.js.map +1 -0
  22. package/dist/{createScaffoldMiddleware.d.cts → createScaffoldMiddleware.d.ts} +3 -3
  23. package/dist/createScaffoldMiddleware.d.ts.map +1 -0
  24. package/dist/{createScaffoldMiddleware.mjs → createScaffoldMiddleware.js} +1 -1
  25. package/dist/createScaffoldMiddleware.js.map +1 -0
  26. package/dist/{getUniqueId.d.mts → getUniqueId.d.ts} +1 -1
  27. package/dist/getUniqueId.d.ts.map +1 -0
  28. package/dist/{getUniqueId.mjs → getUniqueId.js} +2 -2
  29. package/dist/getUniqueId.js.map +1 -0
  30. package/dist/{idRemapMiddleware.d.mts → idRemapMiddleware.d.ts} +3 -3
  31. package/dist/idRemapMiddleware.d.ts.map +1 -0
  32. package/dist/{idRemapMiddleware.mjs → idRemapMiddleware.js} +2 -2
  33. package/dist/idRemapMiddleware.js.map +1 -0
  34. package/dist/index.d.ts +13 -0
  35. package/dist/index.d.ts.map +1 -0
  36. package/dist/index.js +10 -0
  37. package/dist/index.js.map +1 -0
  38. package/dist/{mergeMiddleware.d.cts → mergeMiddleware.d.ts} +3 -3
  39. package/dist/mergeMiddleware.d.ts.map +1 -0
  40. package/dist/{mergeMiddleware.mjs → mergeMiddleware.js} +2 -2
  41. package/dist/mergeMiddleware.js.map +1 -0
  42. package/dist/v2/{JsonRpcEngineV2.d.mts → JsonRpcEngineV2.d.ts} +5 -5
  43. package/dist/v2/JsonRpcEngineV2.d.ts.map +1 -0
  44. package/dist/v2/JsonRpcEngineV2.js +231 -0
  45. package/dist/v2/JsonRpcEngineV2.js.map +1 -0
  46. package/dist/v2/{JsonRpcServer.d.mts → JsonRpcServer.d.ts} +4 -4
  47. package/dist/v2/JsonRpcServer.d.ts.map +1 -0
  48. package/dist/v2/{JsonRpcServer.mjs → JsonRpcServer.js} +33 -45
  49. package/dist/v2/JsonRpcServer.js.map +1 -0
  50. package/dist/v2/{MiddlewareContext.d.mts → MiddlewareContext.d.ts} +2 -2
  51. package/dist/v2/MiddlewareContext.d.ts.map +1 -0
  52. package/dist/v2/{MiddlewareContext.mjs → MiddlewareContext.js} +6 -8
  53. package/dist/v2/MiddlewareContext.js.map +1 -0
  54. package/dist/v2/{asLegacyMiddleware.d.mts → asLegacyMiddleware.d.ts} +5 -5
  55. package/dist/v2/asLegacyMiddleware.d.ts.map +1 -0
  56. package/dist/v2/{asLegacyMiddleware.mjs → asLegacyMiddleware.js} +4 -4
  57. package/dist/v2/asLegacyMiddleware.js.map +1 -0
  58. package/dist/v2/{compatibility-utils.d.mts → compatibility-utils.d.ts} +5 -5
  59. package/dist/v2/compatibility-utils.d.ts.map +1 -0
  60. package/dist/v2/{compatibility-utils.mjs → compatibility-utils.js} +6 -6
  61. package/dist/v2/compatibility-utils.js.map +1 -0
  62. package/dist/v2/{createMethodMiddleware.d.cts → createMethodMiddleware.d.ts} +5 -5
  63. package/dist/v2/createMethodMiddleware.d.ts.map +1 -0
  64. package/dist/v2/{createMethodMiddleware.mjs → createMethodMiddleware.js} +2 -3
  65. package/dist/v2/createMethodMiddleware.js.map +1 -0
  66. package/dist/v2/{createOriginMiddleware.d.cts → createOriginMiddleware.d.ts} +4 -4
  67. package/dist/v2/createOriginMiddleware.d.ts.map +1 -0
  68. package/dist/v2/{createOriginMiddleware.mjs → createOriginMiddleware.js} +1 -2
  69. package/dist/v2/createOriginMiddleware.js.map +1 -0
  70. package/dist/v2/{createScaffoldMiddleware.d.cts → createScaffoldMiddleware.d.ts} +4 -4
  71. package/dist/v2/createScaffoldMiddleware.d.ts.map +1 -0
  72. package/dist/v2/{createScaffoldMiddleware.mjs → createScaffoldMiddleware.js} +1 -1
  73. package/dist/v2/createScaffoldMiddleware.js.map +1 -0
  74. package/dist/v2/index.d.ts +14 -0
  75. package/dist/v2/index.d.ts.map +1 -0
  76. package/dist/v2/index.js +10 -0
  77. package/dist/v2/index.js.map +1 -0
  78. package/dist/v2/{utils.d.mts → utils.d.ts} +5 -5
  79. package/dist/v2/utils.d.ts.map +1 -0
  80. package/dist/v2/{utils.mjs → utils.js} +7 -9
  81. package/dist/v2/utils.js.map +1 -0
  82. package/package.json +16 -26
  83. package/dist/JsonRpcEngine.cjs +0 -352
  84. package/dist/JsonRpcEngine.cjs.map +0 -1
  85. package/dist/JsonRpcEngine.d.cts +0 -132
  86. package/dist/JsonRpcEngine.d.cts.map +0 -1
  87. package/dist/JsonRpcEngine.d.mts.map +0 -1
  88. package/dist/JsonRpcEngine.mjs +0 -345
  89. package/dist/JsonRpcEngine.mjs.map +0 -1
  90. package/dist/asV2Middleware.cjs +0 -57
  91. package/dist/asV2Middleware.cjs.map +0 -1
  92. package/dist/asV2Middleware.d.cts.map +0 -1
  93. package/dist/asV2Middleware.d.mts +0 -20
  94. package/dist/asV2Middleware.d.mts.map +0 -1
  95. package/dist/asV2Middleware.mjs.map +0 -1
  96. package/dist/createAsyncMiddleware.cjs +0 -71
  97. package/dist/createAsyncMiddleware.cjs.map +0 -1
  98. package/dist/createAsyncMiddleware.d.cts +0 -28
  99. package/dist/createAsyncMiddleware.d.cts.map +0 -1
  100. package/dist/createAsyncMiddleware.d.mts.map +0 -1
  101. package/dist/createAsyncMiddleware.mjs.map +0 -1
  102. package/dist/createMethodMiddleware.cjs +0 -56
  103. package/dist/createMethodMiddleware.cjs.map +0 -1
  104. package/dist/createMethodMiddleware.d.cts +0 -86
  105. package/dist/createMethodMiddleware.d.cts.map +0 -1
  106. package/dist/createMethodMiddleware.d.mts.map +0 -1
  107. package/dist/createMethodMiddleware.mjs.map +0 -1
  108. package/dist/createOriginMiddleware.cjs +0 -18
  109. package/dist/createOriginMiddleware.cjs.map +0 -1
  110. package/dist/createOriginMiddleware.d.cts.map +0 -1
  111. package/dist/createOriginMiddleware.d.mts +0 -11
  112. package/dist/createOriginMiddleware.d.mts.map +0 -1
  113. package/dist/createOriginMiddleware.mjs.map +0 -1
  114. package/dist/createScaffoldMiddleware.cjs +0 -31
  115. package/dist/createScaffoldMiddleware.cjs.map +0 -1
  116. package/dist/createScaffoldMiddleware.d.cts.map +0 -1
  117. package/dist/createScaffoldMiddleware.d.mts +0 -18
  118. package/dist/createScaffoldMiddleware.d.mts.map +0 -1
  119. package/dist/createScaffoldMiddleware.mjs.map +0 -1
  120. package/dist/getUniqueId.cjs +0 -20
  121. package/dist/getUniqueId.cjs.map +0 -1
  122. package/dist/getUniqueId.d.cts +0 -9
  123. package/dist/getUniqueId.d.cts.map +0 -1
  124. package/dist/getUniqueId.d.mts.map +0 -1
  125. package/dist/getUniqueId.mjs.map +0 -1
  126. package/dist/idRemapMiddleware.cjs +0 -29
  127. package/dist/idRemapMiddleware.cjs.map +0 -1
  128. package/dist/idRemapMiddleware.d.cts +0 -14
  129. package/dist/idRemapMiddleware.d.cts.map +0 -1
  130. package/dist/idRemapMiddleware.d.mts.map +0 -1
  131. package/dist/idRemapMiddleware.mjs.map +0 -1
  132. package/dist/index.cjs +0 -22
  133. package/dist/index.cjs.map +0 -1
  134. package/dist/index.d.cts +0 -13
  135. package/dist/index.d.cts.map +0 -1
  136. package/dist/index.d.mts +0 -13
  137. package/dist/index.d.mts.map +0 -1
  138. package/dist/index.mjs +0 -10
  139. package/dist/index.mjs.map +0 -1
  140. package/dist/mergeMiddleware.cjs +0 -18
  141. package/dist/mergeMiddleware.cjs.map +0 -1
  142. package/dist/mergeMiddleware.d.cts.map +0 -1
  143. package/dist/mergeMiddleware.d.mts +0 -11
  144. package/dist/mergeMiddleware.d.mts.map +0 -1
  145. package/dist/mergeMiddleware.mjs.map +0 -1
  146. package/dist/v2/JsonRpcEngineV2.cjs +0 -220
  147. package/dist/v2/JsonRpcEngineV2.cjs.map +0 -1
  148. package/dist/v2/JsonRpcEngineV2.d.cts +0 -136
  149. package/dist/v2/JsonRpcEngineV2.d.cts.map +0 -1
  150. package/dist/v2/JsonRpcEngineV2.d.mts.map +0 -1
  151. package/dist/v2/JsonRpcEngineV2.mjs +0 -220
  152. package/dist/v2/JsonRpcEngineV2.mjs.map +0 -1
  153. package/dist/v2/JsonRpcServer.cjs +0 -178
  154. package/dist/v2/JsonRpcServer.cjs.map +0 -1
  155. package/dist/v2/JsonRpcServer.d.cts +0 -104
  156. package/dist/v2/JsonRpcServer.d.cts.map +0 -1
  157. package/dist/v2/JsonRpcServer.d.mts.map +0 -1
  158. package/dist/v2/JsonRpcServer.mjs.map +0 -1
  159. package/dist/v2/MiddlewareContext.cjs +0 -108
  160. package/dist/v2/MiddlewareContext.cjs.map +0 -1
  161. package/dist/v2/MiddlewareContext.d.cts +0 -108
  162. package/dist/v2/MiddlewareContext.d.cts.map +0 -1
  163. package/dist/v2/MiddlewareContext.d.mts.map +0 -1
  164. package/dist/v2/MiddlewareContext.mjs.map +0 -1
  165. package/dist/v2/asLegacyMiddleware.cjs +0 -45
  166. package/dist/v2/asLegacyMiddleware.cjs.map +0 -1
  167. package/dist/v2/asLegacyMiddleware.d.cts +0 -19
  168. package/dist/v2/asLegacyMiddleware.d.cts.map +0 -1
  169. package/dist/v2/asLegacyMiddleware.d.mts.map +0 -1
  170. package/dist/v2/asLegacyMiddleware.mjs.map +0 -1
  171. package/dist/v2/compatibility-utils.cjs +0 -167
  172. package/dist/v2/compatibility-utils.cjs.map +0 -1
  173. package/dist/v2/compatibility-utils.d.cts +0 -75
  174. package/dist/v2/compatibility-utils.d.cts.map +0 -1
  175. package/dist/v2/compatibility-utils.d.mts.map +0 -1
  176. package/dist/v2/compatibility-utils.mjs.map +0 -1
  177. package/dist/v2/createMethodMiddleware.cjs +0 -44
  178. package/dist/v2/createMethodMiddleware.cjs.map +0 -1
  179. package/dist/v2/createMethodMiddleware.d.cts.map +0 -1
  180. package/dist/v2/createMethodMiddleware.d.mts +0 -71
  181. package/dist/v2/createMethodMiddleware.d.mts.map +0 -1
  182. package/dist/v2/createMethodMiddleware.mjs.map +0 -1
  183. package/dist/v2/createOriginMiddleware.cjs +0 -18
  184. package/dist/v2/createOriginMiddleware.cjs.map +0 -1
  185. package/dist/v2/createOriginMiddleware.d.cts.map +0 -1
  186. package/dist/v2/createOriginMiddleware.d.mts +0 -13
  187. package/dist/v2/createOriginMiddleware.d.mts.map +0 -1
  188. package/dist/v2/createOriginMiddleware.mjs.map +0 -1
  189. package/dist/v2/createScaffoldMiddleware.cjs +0 -25
  190. package/dist/v2/createScaffoldMiddleware.cjs.map +0 -1
  191. package/dist/v2/createScaffoldMiddleware.d.cts.map +0 -1
  192. package/dist/v2/createScaffoldMiddleware.d.mts +0 -30
  193. package/dist/v2/createScaffoldMiddleware.d.mts.map +0 -1
  194. package/dist/v2/createScaffoldMiddleware.mjs.map +0 -1
  195. package/dist/v2/index.cjs +0 -26
  196. package/dist/v2/index.cjs.map +0 -1
  197. package/dist/v2/index.d.cts +0 -14
  198. package/dist/v2/index.d.cts.map +0 -1
  199. package/dist/v2/index.d.mts +0 -14
  200. package/dist/v2/index.d.mts.map +0 -1
  201. package/dist/v2/index.mjs +0 -10
  202. package/dist/v2/index.mjs.map +0 -1
  203. package/dist/v2/utils.cjs +0 -122
  204. package/dist/v2/utils.cjs.map +0 -1
  205. package/dist/v2/utils.d.cts +0 -85
  206. package/dist/v2/utils.d.cts.map +0 -1
  207. package/dist/v2/utils.d.mts.map +0 -1
  208. package/dist/v2/utils.mjs.map +0 -1
package/CHANGELOG.md CHANGED
@@ -7,10 +7,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [11.0.0]
11
+
10
12
  ### Changed
11
13
 
14
+ - **BREAKING:** Drop CommonJS support ([#9536](https://github.com/MetaMask/core/pull/9536))
15
+ - This package is now ESM-only, but can still be used in CommonJS projects via `require(esm)` in modern Node.js versions (22+), or dynamic imports in older Node.js versions.
16
+ - **BREAKING:** Bump minimum Node.js version to 22 ([#9976](https://github.com/MetaMask/core/pull/9976))
17
+ - **BREAKING:** Bump TypeScript target to ES2022 ([#10019](https://github.com/MetaMask/core/pull/10019))
18
+ - This package now ships ES2022 code, requiring a compatible modern environment or bundler configuration to consume.
12
19
  - Bump `@metamask/utils` from `^11.9.0` to `^11.12.0` ([#9074](https://github.com/MetaMask/core/pull/9074), [#10076](https://github.com/MetaMask/core/pull/10076))
13
- - Bump `@metamask/messenger` from `^1.2.0` to `^2.0.0` ([#9392](https://github.com/MetaMask/core/pull/9392))
20
+ - Bump `@metamask/messenger` from `^1.2.0` to `^3.0.0` ([#9392](https://github.com/MetaMask/core/pull/9392), [#10160](https://github.com/MetaMask/core/pull/10160))
14
21
 
15
22
  ## [10.5.0]
16
23
 
@@ -315,7 +322,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
315
322
  This change may affect consumers that depend on the eager execution of middleware _during_ request processing, _outside of_ middleware functions and request handlers.
316
323
  - In general, it is a bad practice to work with state that depends on middleware execution, while the middleware are executing.
317
324
 
318
- [Unreleased]: https://github.com/MetaMask/core/compare/@metamask/json-rpc-engine@10.5.0...HEAD
325
+ [Unreleased]: https://github.com/MetaMask/core/compare/@metamask/json-rpc-engine@11.0.0...HEAD
326
+ [11.0.0]: https://github.com/MetaMask/core/compare/@metamask/json-rpc-engine@10.5.0...@metamask/json-rpc-engine@11.0.0
319
327
  [10.5.0]: https://github.com/MetaMask/core/compare/@metamask/json-rpc-engine@10.4.0...@metamask/json-rpc-engine@10.5.0
320
328
  [10.4.0]: https://github.com/MetaMask/core/compare/@metamask/json-rpc-engine@10.3.0...@metamask/json-rpc-engine@10.4.0
321
329
  [10.3.0]: https://github.com/MetaMask/core/compare/@metamask/json-rpc-engine@10.2.4...@metamask/json-rpc-engine@10.3.0
@@ -1,5 +1,5 @@
1
- import SafeEventEmitter from "@metamask/safe-event-emitter";
2
- import type { JsonRpcError as SerializedJsonRpcError, JsonRpcRequest, JsonRpcResponse, JsonRpcNotification, Json, JsonRpcParams, PendingJsonRpcResponse } from "@metamask/utils";
1
+ import SafeEventEmitter from '@metamask/safe-event-emitter';
2
+ import type { JsonRpcError as SerializedJsonRpcError, JsonRpcRequest, JsonRpcResponse, JsonRpcNotification, Json, JsonRpcParams, PendingJsonRpcResponse } from '@metamask/utils';
3
3
  export type JsonRpcEngineCallbackError = Error | SerializedJsonRpcError | null;
4
4
  /**
5
5
  * @deprecated Use `JsonRpcEngineV2` and its corresponding types instead.
@@ -129,4 +129,4 @@ export declare class JsonRpcEngine extends SafeEventEmitter {
129
129
  private _promiseHandle;
130
130
  }
131
131
  export {};
132
- //# sourceMappingURL=JsonRpc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AI,EACtD,OAAO,EAAE,cAAc,CAAC,MAAM,CAAC,GAC9B,OAAO,CAAC,eAAe,CAAC,MAAM,CAAC,CAAC,CAAC;IAEpC;;;;OAIG;IACH,MAAM,CAAC,MAAM,SAAS,aAAa,EACjC,YAAY,EAAE,mBAAmB,CAAC,MAAM,CAAC,GACxC,OAAO,CAAC,IAAI,CAAC,CAAC;IAEjB;;;;;;OAMG;IACH,MAAM,CAAC,MAAM,SAAS,aAAa,EAAE,MAAM,SAAS,IAAI,EACtD,QAAQ,EAAE,CAAC,cAAc,CAAC,MAAM,CAAC,GAAG,mBAAmB,CAAC,MAAM,CAAC,CAAC,EAAE,GACjE,OAAO,CAAC,eAAe,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;IAoCtC;;;;;OAKG;IACH,YAAY,IAAI,iBAAiB,CAAC,aAAa,EAAE,IAAI,CAAC,CA2BrD;IA2ED;;;;;OAKG;YAIW,cAAc;CAkS7B"}
@@ -0,0 +1,386 @@
1
+ var _a;
2
+ import { errorCodes, JsonRpcError, serializeError } from '@metamask/rpc-errors';
3
+ import SafeEventEmitter from '@metamask/safe-event-emitter';
4
+ import { hasProperty, isJsonRpcNotification, isJsonRpcRequest, } from '@metamask/utils';
5
+ import { stringify } from './v2/utils.js';
6
+ const DESTROYED_ERROR_MESSAGE = 'This engine is destroyed and can no longer be used.';
7
+ /**
8
+ * A JSON-RPC request and response processor.
9
+ *
10
+ * Give it a stack of middleware, pass it requests, and get back responses.
11
+ *
12
+ * @deprecated Use `JsonRpcEngineV2` instead.
13
+ */
14
+ export class JsonRpcEngine extends SafeEventEmitter {
15
+ /**
16
+ * Indicating whether this engine is destroyed or not.
17
+ */
18
+ #isDestroyed = false;
19
+ #middleware;
20
+ #notificationHandler;
21
+ /**
22
+ * Constructs a {@link JsonRpcEngine} instance.
23
+ *
24
+ * @param options - Options bag.
25
+ * @param options.notificationHandler - A function for handling JSON-RPC
26
+ * notifications. A JSON-RPC notification is defined as a JSON-RPC request
27
+ * without an `id` property. If this option is _not_ provided, notifications
28
+ * will be treated the same as requests. If this option _is_ provided,
29
+ * notifications will be passed to the handler function without touching
30
+ * the engine's middleware stack. This function should not throw or reject.
31
+ */
32
+ constructor({ notificationHandler } = {}) {
33
+ super();
34
+ this.#middleware = [];
35
+ this.#notificationHandler = notificationHandler;
36
+ }
37
+ /**
38
+ * Throws an error if this engine is destroyed.
39
+ */
40
+ #assertIsNotDestroyed() {
41
+ if (this.#isDestroyed) {
42
+ throw new Error(DESTROYED_ERROR_MESSAGE);
43
+ }
44
+ }
45
+ /**
46
+ * Calls the `destroy()` function of any middleware with that property, clears
47
+ * the middleware array, and marks this engine as destroyed. A destroyed
48
+ * engine cannot be used.
49
+ */
50
+ destroy() {
51
+ this.#middleware.forEach((middleware) => {
52
+ if (
53
+ // `in` walks the prototype chain, which is probably the desired
54
+ // behavior here.
55
+ 'destroy' in middleware &&
56
+ typeof middleware.destroy === 'function') {
57
+ // eslint-disable-next-line @typescript-eslint/no-floating-promises
58
+ middleware.destroy();
59
+ }
60
+ });
61
+ this.#middleware = [];
62
+ this.#isDestroyed = true;
63
+ }
64
+ /**
65
+ * Add a middleware function to the engine's middleware stack.
66
+ *
67
+ * @param middleware - The middleware function to add.
68
+ */
69
+ push(middleware) {
70
+ this.#assertIsNotDestroyed();
71
+ this.#middleware.push(middleware);
72
+ }
73
+ handle(req, callback) {
74
+ this.#assertIsNotDestroyed();
75
+ if (callback && typeof callback !== 'function') {
76
+ throw new Error('"callback" must be a function if provided.');
77
+ }
78
+ if (Array.isArray(req)) {
79
+ if (callback) {
80
+ return this.#handleBatch(req,
81
+ // This assertion is safe because of the runtime checks validating that `req` is an array and `callback` is defined.
82
+ // There is only one overload signature that satisfies both conditions, and its `callback` type is the one that's being asserted.
83
+ callback);
84
+ }
85
+ return this.#handleBatch(req);
86
+ }
87
+ if (callback) {
88
+ return this.#handle(req, callback);
89
+ }
90
+ return this._promiseHandle(req);
91
+ }
92
+ /**
93
+ * Returns this engine as a middleware function that can be pushed to other
94
+ * engines.
95
+ *
96
+ * @returns This engine as a middleware function.
97
+ */
98
+ asMiddleware() {
99
+ this.#assertIsNotDestroyed();
100
+ // eslint-disable-next-line @typescript-eslint/no-misused-promises
101
+ return async (req, res, next, end) => {
102
+ try {
103
+ const [middlewareError, isComplete, returnHandlers] = await _a.#runAllMiddleware(req, res, this.#middleware);
104
+ if (isComplete) {
105
+ await _a.#runReturnHandlers(returnHandlers);
106
+ return end(middlewareError);
107
+ }
108
+ // eslint-disable-next-line @typescript-eslint/no-misused-promises
109
+ return next(async (handlerCallback) => {
110
+ try {
111
+ await _a.#runReturnHandlers(returnHandlers);
112
+ }
113
+ catch (error) {
114
+ return handlerCallback(error);
115
+ }
116
+ return handlerCallback();
117
+ });
118
+ }
119
+ catch (error) {
120
+ return end(error);
121
+ }
122
+ };
123
+ }
124
+ /**
125
+ * Handles a batch of JSON-RPC requests, either in `async` or callback
126
+ * fashion.
127
+ *
128
+ * @param requests - The request objects to process.
129
+ * @param callback - The completion callback.
130
+ * @returns The array of responses, or nothing if a callback was specified.
131
+ */
132
+ async #handleBatch(requests, callback) {
133
+ // The order here is important
134
+ try {
135
+ // If the batch is an empty array, the response array must contain a single object
136
+ if (requests.length === 0) {
137
+ const response = [
138
+ {
139
+ id: null,
140
+ jsonrpc: '2.0',
141
+ error: new JsonRpcError(errorCodes.rpc.invalidRequest, 'Request batch must contain plain objects. Received an empty array'),
142
+ },
143
+ ];
144
+ if (callback) {
145
+ return callback(null, response);
146
+ }
147
+ return response;
148
+ }
149
+ // 2. Wait for all requests to finish, or throw on some kind of fatal
150
+ // error
151
+ const responses = (await Promise.all(
152
+ // 1. Begin executing each request in the order received
153
+ requests.map(this._promiseHandle.bind(this)))).filter(
154
+ // Filter out any notification responses.
155
+ (response) => response !== undefined);
156
+ // 3. Return batch response
157
+ if (callback) {
158
+ return callback(null, responses);
159
+ }
160
+ return responses;
161
+ }
162
+ catch (error) {
163
+ if (callback) {
164
+ return callback(error);
165
+ }
166
+ throw error;
167
+ }
168
+ }
169
+ /**
170
+ * A promise-wrapped _handle.
171
+ *
172
+ * @param request - The JSON-RPC request.
173
+ * @returns The JSON-RPC response.
174
+ */
175
+ // This function is used in tests, so we cannot easily change it to use the
176
+ // hash syntax.
177
+ // eslint-disable-next-line no-restricted-syntax
178
+ async _promiseHandle(request) {
179
+ return new Promise((resolve, reject) => {
180
+ this.#handle(request, (error, res) => {
181
+ // For notifications, the response will be `undefined`, and any caught
182
+ // errors are unexpected and should be surfaced to the caller.
183
+ if (error && res === undefined) {
184
+ // We are not going to change this behavior.
185
+ // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors
186
+ reject(error);
187
+ }
188
+ else {
189
+ // Excepting notifications, there will always be a response, and it will
190
+ // always have any error that is caught and propagated.
191
+ resolve(res);
192
+ }
193
+ }).catch(reject);
194
+ });
195
+ }
196
+ /**
197
+ * Ensures that the request / notification object is valid, processes it, and
198
+ * passes any error and response object to the given callback.
199
+ *
200
+ * Does not reject.
201
+ *
202
+ * @param callerReq - The request object from the caller.
203
+ * @param callback - The callback function.
204
+ * @returns Nothing.
205
+ */
206
+ async #handle(callerReq, callback) {
207
+ if (!callerReq ||
208
+ Array.isArray(callerReq) ||
209
+ typeof callerReq !== 'object') {
210
+ const error = new JsonRpcError(errorCodes.rpc.invalidRequest, `Requests must be plain objects. Received: ${typeof callerReq}`, { request: callerReq });
211
+ return callback(error, { id: null, jsonrpc: '2.0', error });
212
+ }
213
+ if (typeof callerReq.method !== 'string') {
214
+ const error = new JsonRpcError(errorCodes.rpc.invalidRequest, `Must specify a string method. Received: ${typeof callerReq.method}`, { request: callerReq });
215
+ if (this.#notificationHandler && !isJsonRpcRequest(callerReq)) {
216
+ // Do not reply to notifications, even if they are malformed.
217
+ return callback(null);
218
+ }
219
+ return callback(error, {
220
+ // Typecast: This could be a notification, but we want to access the
221
+ // `id` even if it doesn't exist.
222
+ id: callerReq.id ?? null,
223
+ jsonrpc: '2.0',
224
+ error,
225
+ });
226
+ }
227
+ else if (this.#notificationHandler &&
228
+ isJsonRpcNotification(callerReq) &&
229
+ !isJsonRpcRequest(callerReq)) {
230
+ try {
231
+ await this.#notificationHandler(callerReq);
232
+ }
233
+ catch (error) {
234
+ return callback(error);
235
+ }
236
+ return callback(null);
237
+ }
238
+ let error = null;
239
+ // Handle requests.
240
+ // Typecast: Permit missing id's for backwards compatibility.
241
+ const req = { ...callerReq };
242
+ const res = {
243
+ id: req.id,
244
+ jsonrpc: req.jsonrpc,
245
+ };
246
+ try {
247
+ await _a.#processRequest(req, res, this.#middleware);
248
+ }
249
+ catch (_error) {
250
+ // A request handler error, a re-thrown middleware error, or something
251
+ // unexpected.
252
+ error = _error;
253
+ }
254
+ if (error) {
255
+ // Ensure no result is present on an errored response
256
+ delete res.result;
257
+ res.error ??= serializeError(error);
258
+ }
259
+ return callback(error, res);
260
+ }
261
+ /**
262
+ * For the given request and response, runs all middleware and their return
263
+ * handlers, if any, and ensures that internal request processing semantics
264
+ * are satisfied.
265
+ *
266
+ * @param req - The request object.
267
+ * @param res - The response object.
268
+ * @param middlewares - The stack of middleware functions.
269
+ */
270
+ static async #processRequest(req, res, middlewares) {
271
+ const [error, isComplete, returnHandlers] = await _a.#runAllMiddleware(req, res, middlewares);
272
+ // Throw if "end" was not called, or if the response has neither a result
273
+ // nor an error.
274
+ _a.#checkForCompletion(req, res, isComplete);
275
+ // The return handlers should run even if an error was encountered during
276
+ // middleware processing.
277
+ await _a.#runReturnHandlers(returnHandlers);
278
+ // Now we re-throw the middleware processing error, if any, to catch it
279
+ // further up the call chain.
280
+ if (error) {
281
+ // eslint-disable-next-line @typescript-eslint/only-throw-error
282
+ throw error;
283
+ }
284
+ }
285
+ /**
286
+ * Serially executes the given stack of middleware.
287
+ *
288
+ * @param req - The request object.
289
+ * @param res - The response object.
290
+ * @param middlewares - The stack of middleware functions to execute.
291
+ * @returns An array of any error encountered during middleware execution,
292
+ * a boolean indicating whether the request was completed, and an array of
293
+ * middleware-defined return handlers.
294
+ */
295
+ static async #runAllMiddleware(req, res, middlewares) {
296
+ const returnHandlers = [];
297
+ let error = null;
298
+ let isComplete = false;
299
+ // Go down stack of middleware, call and collect optional returnHandlers
300
+ for (const middleware of middlewares) {
301
+ [error, isComplete] = await _a.#runMiddleware(req, res, middleware, returnHandlers);
302
+ if (isComplete) {
303
+ break;
304
+ }
305
+ }
306
+ return [error, isComplete, returnHandlers.reverse()];
307
+ }
308
+ /**
309
+ * Runs an individual middleware function.
310
+ *
311
+ * @param request - The request object.
312
+ * @param response - The response object.
313
+ * @param middleware - The middleware function to execute.
314
+ * @param returnHandlers - The return handlers array for the current request.
315
+ * @returns An array of any error encountered during middleware execution,
316
+ * and a boolean indicating whether the request should end.
317
+ */
318
+ static async #runMiddleware(request, response, middleware, returnHandlers) {
319
+ return new Promise((resolve) => {
320
+ const end = (error) => {
321
+ const parsedError = error ?? response.error;
322
+ if (parsedError) {
323
+ response.error = serializeError(parsedError);
324
+ }
325
+ // True indicates that the request should end
326
+ resolve([parsedError, true]);
327
+ };
328
+ const next = (returnHandler) => {
329
+ if (response.error) {
330
+ end(response.error);
331
+ }
332
+ else {
333
+ if (returnHandler) {
334
+ if (typeof returnHandler !== 'function') {
335
+ end(new JsonRpcError(errorCodes.rpc.internal, `JsonRpcEngine: "next" return handlers must be functions. ` +
336
+ `Received "${typeof returnHandler}" for request:\n${stringify(request)}`, { request }));
337
+ }
338
+ returnHandlers.push(returnHandler);
339
+ }
340
+ // False indicates that the request should not end
341
+ resolve([null, false]);
342
+ }
343
+ };
344
+ try {
345
+ middleware(request, response, next, end);
346
+ }
347
+ catch (error) {
348
+ end(error);
349
+ }
350
+ });
351
+ }
352
+ /**
353
+ * Serially executes array of return handlers. The request and response are
354
+ * assumed to be in their scope.
355
+ *
356
+ * @param handlers - The return handlers to execute.
357
+ */
358
+ static async #runReturnHandlers(handlers) {
359
+ for (const handler of handlers) {
360
+ await new Promise((resolve, reject) => {
361
+ // We are not going to change this behavior.
362
+ // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors
363
+ handler((error) => (error ? reject(error) : resolve()));
364
+ });
365
+ }
366
+ }
367
+ /**
368
+ * Throws an error if the response has neither a result nor an error, or if
369
+ * the "isComplete" flag is falsy.
370
+ *
371
+ * @param request - The request object.
372
+ * @param response - The response object.
373
+ * @param isComplete - Boolean from {@link JsonRpcEngine.#runAllMiddleware}
374
+ * indicating whether a middleware ended the request.
375
+ */
376
+ static #checkForCompletion(request, response, isComplete) {
377
+ if (!hasProperty(response, 'result') && !hasProperty(response, 'error')) {
378
+ throw new JsonRpcError(errorCodes.rpc.internal, `JsonRpcEngine: Response has no error or result for request:\n${stringify(request)}`, { request });
379
+ }
380
+ if (!isComplete) {
381
+ throw new JsonRpcError(errorCodes.rpc.internal, `JsonRpcEngine: Nothing ended request:\n${stringify(request)}`, { request });
382
+ }
383
+ }
384
+ }
385
+ _a = JsonRpcEngine;
386
+ //# sourceMappingURL=JsonRpcEngine.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"JsonRpcEngine.js","sourceRoot":"","sources":["../src/JsonRpcEngine.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAChF,OAAO,gBAAgB,MAAM,8BAA8B,CAAC;AAU5D,OAAO,EACL,WAAW,EACX,qBAAqB,EACrB,gBAAgB,GACjB,MAAM,iBAAiB,CAAC;AAEzB,OAAO,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AAuC1C,MAAM,uBAAuB,GAC3B,qDAAqD,CAAC;AAsBxD;;;;;;GAMG;AACH,MAAM,OAAO,aAAc,SAAQ,gBAAgB;IACjD;;OAEG;IACH,YAAY,GAAG,KAAK,CAAC;IAErB,WAAW,CAA2C;IAE7C,oBAAoB,CAEf;IAEd;;;;;;;;;;OAUG;IACH,YAAY,EAAE,mBAAmB,EAAE,GAAsB,EAAE;QACzD,KAAK,EAAE,CAAC;QACR,IAAI,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AC1C,4CAA4C;gBAC5C,2EAA2E;gBAC3E,OAAO,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC;YAC1D,CAAC,CAAC,CAAC;QACL,CAAC;IACH,CAAC;IAED;;;;;;;;OAQG;IACH,MAAM,CAAC,mBAAmB,CACxB,OAAuB,EACvB,QAAgC,EAChC,UAAmB;QAEnB,IAAI,CAAC,WAAW,CAAC,QAAQ,EAAE,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,QAAQ,EAAE,OAAO,CAAC,EAAE,CAAC;YACxE,MAAM,IAAI,YAAY,CACpB,UAAU,CAAC,GAAG,CAAC,QAAQ,EACvB,gEAAgE,SAAS,CACvE,OAAO,CACR,EAAE,EACH,EAAE,OAAO,EAAE,CACZ,CAAC;QACJ,CAAC;QAED,IAAI,CAAC,UAAU,EAAE,CAAC;YAChB,MAAM,IAAI,YAAY,CACpB,UAAU,CAAC,GAAG,CAAC,QAAQ,EACvB,0CAA0C,SAAS,CAAC,OAAO,CAAC,EAAE,EAC9D,EAAE,OAAO,EAAE,CACZ,CAAC;QACJ,CAAC;IACH,CAAC;CACF","sourcesContent":["import { errorCodes, JsonRpcError, serializeError } from '@metamask/rpc-errors';\nimport SafeEventEmitter from '@metamask/safe-event-emitter';\nimport type {\n JsonRpcError as SerializedJsonRpcError,\n JsonRpcRequest,\n JsonRpcResponse,\n JsonRpcNotification,\n Json,\n JsonRpcParams,\n PendingJsonRpcResponse,\n} from '@metamask/utils';\nimport {\n hasProperty,\n isJsonRpcNotification,\n isJsonRpcRequest,\n} from '@metamask/utils';\n\nimport { stringify } from './v2/utils.js';\n\nexport type JsonRpcEngineCallbackError = Error | SerializedJsonRpcError | null;\n\n/**\n * @deprecated Use `JsonRpcEngineV2` and its corresponding types instead.\n */\nexport type JsonRpcEngineReturnHandler = (\n done: (error?: unknown) => void,\n) => void;\n\n/**\n * @deprecated Use `JsonRpcEngineV2` and its corresponding types instead.\n */\nexport type JsonRpcEngineNextCallback = (\n returnHandlerCallback?: JsonRpcEngineReturnHandler,\n) => void;\n\n/**\n * @deprecated Use `JsonRpcEngineV2` and its corresponding types instead.\n */\nexport type JsonRpcEngineEndCallback = (error?: unknown) => void;\n\n/**\n * @deprecated Use `JsonRpcEngineV2` and its corresponding types instead.\n */\nexport type JsonRpcMiddleware<\n Params extends JsonRpcParams,\n Result extends Json,\n> = {\n (\n req: JsonRpcRequest<Params>,\n res: PendingJsonRpcResponse<Result>,\n next: JsonRpcEngineNextCallback,\n end: JsonRpcEngineEndCallback,\n ): void;\n destroy?: () => void | Promise<void>;\n};\n\nconst DESTROYED_ERROR_MESSAGE =\n 'This engine is destroyed and can no longer be used.';\n\n/**\n * @deprecated Use `JsonRpcEngineV2` and its corresponding types instead.\n */\nexport type JsonRpcNotificationHandler<Params extends JsonRpcParams> = (\n notification: JsonRpcNotification<Params>,\n) => void | Promise<void>;\n\ntype JsonRpcEngineArgs = {\n /**\n * A function for handling JSON-RPC notifications. A JSON-RPC notification is\n * defined as a JSON-RPC request without an `id` property. If this option is\n * _not_ provided, notifications will be treated the same as requests. If this\n * option _is_ provided, notifications will be passed to the handler\n * function without touching the engine's middleware stack.\n *\n * This function should not throw or reject.\n */\n notificationHandler?: JsonRpcNotificationHandler<JsonRpcParams>;\n};\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 * @deprecated Use `JsonRpcEngineV2` instead.\n */\nexport class JsonRpcEngine extends SafeEventEmitter {\n /**\n * Indicating whether this engine is destroyed or not.\n */\n #isDestroyed = false;\n\n #middleware: JsonRpcMiddleware<JsonRpcParams, Json>[];\n\n readonly #notificationHandler?:\n | JsonRpcNotificationHandler<JsonRpcParams>\n | undefined;\n\n /**\n * Constructs a {@link JsonRpcEngine} instance.\n *\n * @param options - Options bag.\n * @param options.notificationHandler - A function for handling JSON-RPC\n * notifications. A JSON-RPC notification is defined as a JSON-RPC request\n * without an `id` property. If this option is _not_ provided, notifications\n * will be treated the same as requests. If this option _is_ provided,\n * notifications will be passed to the handler function without touching\n * the engine's middleware stack. This function should not throw or reject.\n */\n constructor({ notificationHandler }: JsonRpcEngineArgs = {}) {\n super();\n this.#middleware = [];\n this.#notificationHandler = notificationHandler;\n }\n\n /**\n * Throws an error if this engine is destroyed.\n */\n #assertIsNotDestroyed(): void {\n if (this.#isDestroyed) {\n throw new Error(DESTROYED_ERROR_MESSAGE);\n }\n }\n\n /**\n * Calls the `destroy()` function of any middleware with that property, clears\n * the middleware array, and marks this engine as destroyed. A destroyed\n * engine cannot be used.\n */\n destroy(): void {\n this.#middleware.forEach(\n (middleware: JsonRpcMiddleware<JsonRpcParams, Json>) => {\n if (\n // `in` walks the prototype chain, which is probably the desired\n // behavior here.\n 'destroy' in middleware &&\n typeof middleware.destroy === 'function'\n ) {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n middleware.destroy();\n }\n },\n );\n this.#middleware = [];\n this.#isDestroyed = true;\n }\n\n /**\n * Add a middleware function to the engine's middleware stack.\n *\n * @param middleware - The middleware function to add.\n */\n push<Params extends JsonRpcParams, Result extends Json>(\n middleware: JsonRpcMiddleware<Params, Result>,\n ): void {\n this.#assertIsNotDestroyed();\n this.#middleware.push(middleware as JsonRpcMiddleware<JsonRpcParams, Json>);\n }\n\n /**\n * Handle a JSON-RPC request, and return a response.\n *\n * @param request - The request to handle.\n * @param callback - An error-first callback that will receive the response.\n */\n handle<Params extends JsonRpcParams, Result extends Json>(\n request: JsonRpcRequest<Params>,\n callback: (error: unknown, response: JsonRpcResponse<Result>) => void,\n ): void;\n\n /**\n * Handle a JSON-RPC notification.\n *\n * @param notification - The notification to handle.\n * @param callback - An error-first callback that will receive a `void` response.\n */\n handle<Params extends JsonRpcParams>(\n notification: JsonRpcNotification<Params>,\n callback: (error: unknown, response: void) => void,\n ): void;\n\n /**\n * Handle an array of JSON-RPC requests and/or notifications, and return an\n * array of responses to any included requests.\n *\n * @param request - The requests to handle.\n * @param callback - An error-first callback that will receive the array of\n * responses.\n */\n handle<Params extends JsonRpcParams, Result extends Json>(\n requests: (JsonRpcRequest<Params> | JsonRpcNotification<Params>)[],\n callback: (error: unknown, responses: JsonRpcResponse<Result>[]) => void,\n ): void;\n\n /**\n * Handle a JSON-RPC request, and return a response.\n *\n * @param request - The JSON-RPC request to handle.\n * @returns The JSON-RPC response.\n */\n handle<Params extends JsonRpcParams, Result extends Json>(\n request: JsonRpcRequest<Params>,\n ): Promise<JsonRpcResponse<Result>>;\n\n /**\n * Handle a JSON-RPC notification.\n *\n * @param notification - The notification to handle.\n */\n handle<Params extends JsonRpcParams>(\n notification: JsonRpcNotification<Params>,\n ): Promise<void>;\n\n /**\n * Handle an array of JSON-RPC requests and/or notifications, and return an\n * array of responses to any included requests.\n *\n * @param request - The JSON-RPC requests to handle.\n * @returns An array of JSON-RPC responses.\n */\n handle<Params extends JsonRpcParams, Result extends Json>(\n requests: (JsonRpcRequest<Params> | JsonRpcNotification<Params>)[],\n ): Promise<JsonRpcResponse<Result>[]>;\n\n handle(\n req:\n | (JsonRpcRequest | JsonRpcNotification)[]\n | JsonRpcRequest\n | JsonRpcNotification,\n callback?: (error: unknown, response: never) => void,\n ): Promise<JsonRpcResponse[]> | Promise<JsonRpcResponse | void> {\n this.#assertIsNotDestroyed();\n\n if (callback && typeof callback !== 'function') {\n throw new Error('\"callback\" must be a function if provided.');\n }\n\n if (Array.isArray(req)) {\n if (callback) {\n return this.#handleBatch(\n req,\n // This assertion is safe because of the runtime checks validating that `req` is an array and `callback` is defined.\n // There is only one overload signature that satisfies both conditions, and its `callback` type is the one that's being asserted.\n callback as (error: unknown, responses?: JsonRpcResponse[]) => void,\n );\n }\n return this.#handleBatch(req);\n }\n\n if (callback) {\n return this.#handle(\n req,\n callback as (error: unknown, response?: JsonRpcResponse) => void,\n );\n }\n return this._promiseHandle(req);\n }\n\n /**\n * Returns this engine as a middleware function that can be pushed to other\n * engines.\n *\n * @returns This engine as a middleware function.\n */\n asMiddleware(): JsonRpcMiddleware<JsonRpcParams, Json> {\n this.#assertIsNotDestroyed();\n\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n return async (req, res, next, end) => {\n try {\n const [middlewareError, isComplete, returnHandlers] =\n await JsonRpcEngine.#runAllMiddleware(req, res, this.#middleware);\n\n if (isComplete) {\n await JsonRpcEngine.#runReturnHandlers(returnHandlers);\n return end(middlewareError);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n return next(async (handlerCallback) => {\n try {\n await JsonRpcEngine.#runReturnHandlers(returnHandlers);\n } catch (error) {\n return handlerCallback(error);\n }\n return handlerCallback();\n });\n } catch (error) {\n return end(error);\n }\n };\n }\n\n /**\n * Like _handle, but for batch requests.\n */\n #handleBatch(\n reqs: (JsonRpcRequest | JsonRpcNotification)[],\n ): Promise<JsonRpcResponse[]>;\n\n /**\n * Like _handle, but for batch requests.\n */\n #handleBatch(\n reqs: (JsonRpcRequest | JsonRpcNotification)[],\n callback: (error: unknown, responses?: JsonRpcResponse[]) => void,\n ): Promise<void>;\n\n /**\n * Handles a batch of JSON-RPC requests, either in `async` or callback\n * fashion.\n *\n * @param requests - The request objects to process.\n * @param callback - The completion callback.\n * @returns The array of responses, or nothing if a callback was specified.\n */\n async #handleBatch(\n requests: (JsonRpcRequest | JsonRpcNotification)[],\n callback?: (error: unknown, responses?: JsonRpcResponse[]) => void,\n ): Promise<JsonRpcResponse[] | void> {\n // The order here is important\n try {\n // If the batch is an empty array, the response array must contain a single object\n if (requests.length === 0) {\n const response: JsonRpcResponse[] = [\n {\n id: null,\n jsonrpc: '2.0',\n error: new JsonRpcError(\n errorCodes.rpc.invalidRequest,\n 'Request batch must contain plain objects. Received an empty array',\n ),\n },\n ];\n if (callback) {\n return callback(null, response);\n }\n return response;\n }\n\n // 2. Wait for all requests to finish, or throw on some kind of fatal\n // error\n const responses = (\n await Promise.all(\n // 1. Begin executing each request in the order received\n requests.map(this._promiseHandle.bind(this)),\n )\n ).filter(\n // Filter out any notification responses.\n (response): response is JsonRpcResponse => response !== undefined,\n );\n\n // 3. Return batch response\n if (callback) {\n return callback(null, responses);\n }\n return responses;\n } catch (error) {\n if (callback) {\n return callback(error);\n }\n\n throw error;\n }\n }\n\n /**\n * A promise-wrapped _handle.\n *\n * @param request - The JSON-RPC request.\n * @returns The JSON-RPC response.\n */\n // This function is used in tests, so we cannot easily change it to use the\n // hash syntax.\n // eslint-disable-next-line no-restricted-syntax\n private async _promiseHandle(\n request: JsonRpcRequest | JsonRpcNotification,\n ): Promise<JsonRpcResponse | void> {\n return new Promise((resolve, reject) => {\n this.#handle(request, (error, res) => {\n // For notifications, the response will be `undefined`, and any caught\n // errors are unexpected and should be surfaced to the caller.\n if (error && res === undefined) {\n // We are not going to change this behavior.\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors\n reject(error);\n } else {\n // Excepting notifications, there will always be a response, and it will\n // always have any error that is caught and propagated.\n resolve(res);\n }\n }).catch(reject);\n });\n }\n\n /**\n * Ensures that the request / notification object is valid, processes it, and\n * passes any error and response object to the given callback.\n *\n * Does not reject.\n *\n * @param callerReq - The request object from the caller.\n * @param callback - The callback function.\n * @returns Nothing.\n */\n async #handle(\n callerReq: JsonRpcRequest | JsonRpcNotification,\n callback: (error: unknown, response?: JsonRpcResponse) => void,\n ): Promise<void> {\n if (\n !callerReq ||\n Array.isArray(callerReq) ||\n typeof callerReq !== 'object'\n ) {\n const error = new JsonRpcError(\n errorCodes.rpc.invalidRequest,\n `Requests must be plain objects. Received: ${typeof callerReq}`,\n { request: callerReq },\n );\n return callback(error, { id: null, jsonrpc: '2.0', error });\n }\n\n if (typeof callerReq.method !== 'string') {\n const error = new JsonRpcError(\n errorCodes.rpc.invalidRequest,\n `Must specify a string method. Received: ${typeof callerReq.method}`,\n { request: callerReq },\n );\n\n if (this.#notificationHandler && !isJsonRpcRequest(callerReq)) {\n // Do not reply to notifications, even if they are malformed.\n return callback(null);\n }\n\n return callback(error, {\n // Typecast: This could be a notification, but we want to access the\n // `id` even if it doesn't exist.\n id: (callerReq as JsonRpcRequest).id ?? null,\n jsonrpc: '2.0',\n error,\n });\n } else if (\n this.#notificationHandler &&\n isJsonRpcNotification(callerReq) &&\n !isJsonRpcRequest(callerReq)\n ) {\n try {\n await this.#notificationHandler(callerReq);\n } catch (error) {\n return callback(error);\n }\n return callback(null);\n }\n let error = null;\n\n // Handle requests.\n // Typecast: Permit missing id's for backwards compatibility.\n const req = { ...(callerReq as JsonRpcRequest) };\n const res: PendingJsonRpcResponse = {\n id: req.id,\n jsonrpc: req.jsonrpc,\n };\n\n try {\n await JsonRpcEngine.#processRequest(req, res, this.#middleware);\n } catch (_error) {\n // A request handler error, a re-thrown middleware error, or something\n // unexpected.\n error = _error;\n }\n\n if (error) {\n // Ensure no result is present on an errored response\n delete res.result;\n res.error ??= serializeError(error);\n }\n\n return callback(error, res as JsonRpcResponse);\n }\n\n /**\n * For the given request and response, runs all middleware and their return\n * handlers, if any, and ensures that internal request processing semantics\n * are satisfied.\n *\n * @param req - The request object.\n * @param res - The response object.\n * @param middlewares - The stack of middleware functions.\n */\n static async #processRequest(\n req: JsonRpcRequest,\n res: PendingJsonRpcResponse,\n middlewares: JsonRpcMiddleware<JsonRpcParams, Json>[],\n ): Promise<void> {\n const [error, isComplete, returnHandlers] =\n await JsonRpcEngine.#runAllMiddleware(req, res, middlewares);\n\n // Throw if \"end\" was not called, or if the response has neither a result\n // nor an error.\n JsonRpcEngine.#checkForCompletion(req, res, isComplete);\n\n // The return handlers should run even if an error was encountered during\n // middleware processing.\n await JsonRpcEngine.#runReturnHandlers(returnHandlers);\n\n // Now we re-throw the middleware processing error, if any, to catch it\n // further up the call chain.\n if (error) {\n // eslint-disable-next-line @typescript-eslint/only-throw-error\n throw error;\n }\n }\n\n /**\n * Serially executes the given stack of middleware.\n *\n * @param req - The request object.\n * @param res - The response object.\n * @param middlewares - The stack of middleware functions to execute.\n * @returns An array of any error encountered during middleware execution,\n * a boolean indicating whether the request was completed, and an array of\n * middleware-defined return handlers.\n */\n static async #runAllMiddleware(\n req: JsonRpcRequest,\n res: PendingJsonRpcResponse,\n middlewares: JsonRpcMiddleware<JsonRpcParams, Json>[],\n ): Promise<\n [\n unknown, // error\n boolean, // isComplete\n JsonRpcEngineReturnHandler[],\n ]\n > {\n const returnHandlers: JsonRpcEngineReturnHandler[] = [];\n let error = null;\n let isComplete = false;\n\n // Go down stack of middleware, call and collect optional returnHandlers\n for (const middleware of middlewares) {\n [error, isComplete] = await JsonRpcEngine.#runMiddleware(\n req,\n res,\n middleware,\n returnHandlers,\n );\n\n if (isComplete) {\n break;\n }\n }\n return [error, isComplete, returnHandlers.reverse()];\n }\n\n /**\n * Runs an individual middleware function.\n *\n * @param request - The request object.\n * @param response - The response object.\n * @param middleware - The middleware function to execute.\n * @param returnHandlers - The return handlers array for the current request.\n * @returns An array of any error encountered during middleware execution,\n * and a boolean indicating whether the request should end.\n */\n static async #runMiddleware(\n request: JsonRpcRequest,\n response: PendingJsonRpcResponse,\n middleware: JsonRpcMiddleware<JsonRpcParams, Json>,\n returnHandlers: JsonRpcEngineReturnHandler[],\n ): Promise<[unknown, boolean]> {\n return new Promise((resolve) => {\n const end: JsonRpcEngineEndCallback = (error) => {\n const parsedError = error ?? response.error;\n if (parsedError) {\n response.error = serializeError(parsedError);\n }\n // True indicates that the request should end\n resolve([parsedError, true]);\n };\n\n const next: JsonRpcEngineNextCallback = (\n returnHandler?: JsonRpcEngineReturnHandler,\n ) => {\n if (response.error) {\n end(response.error);\n } else {\n if (returnHandler) {\n if (typeof returnHandler !== 'function') {\n end(\n new JsonRpcError(\n errorCodes.rpc.internal,\n `JsonRpcEngine: \"next\" return handlers must be functions. ` +\n `Received \"${typeof returnHandler}\" for request:\\n${stringify(\n request,\n )}`,\n { request },\n ),\n );\n }\n returnHandlers.push(returnHandler);\n }\n\n // False indicates that the request should not end\n resolve([null, false]);\n }\n };\n\n try {\n middleware(request, response, next, end);\n } catch (error) {\n end(error);\n }\n });\n }\n\n /**\n * Serially executes array of return handlers. The request and response are\n * assumed to be in their scope.\n *\n * @param handlers - The return handlers to execute.\n */\n static async #runReturnHandlers(\n handlers: JsonRpcEngineReturnHandler[],\n ): Promise<void> {\n for (const handler of handlers) {\n await new Promise<void>((resolve, reject) => {\n // We are not going to change this behavior.\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors\n handler((error) => (error ? reject(error) : resolve()));\n });\n }\n }\n\n /**\n * Throws an error if the response has neither a result nor an error, or if\n * the \"isComplete\" flag is falsy.\n *\n * @param request - The request object.\n * @param response - The response object.\n * @param isComplete - Boolean from {@link JsonRpcEngine.#runAllMiddleware}\n * indicating whether a middleware ended the request.\n */\n static #checkForCompletion(\n request: JsonRpcRequest,\n response: PendingJsonRpcResponse,\n isComplete: boolean,\n ): void {\n if (!hasProperty(response, 'result') && !hasProperty(response, 'error')) {\n throw new JsonRpcError(\n errorCodes.rpc.internal,\n `JsonRpcEngine: Response has no error or result for request:\\n${stringify(\n request,\n )}`,\n { request },\n );\n }\n\n if (!isComplete) {\n throw new JsonRpcError(\n errorCodes.rpc.internal,\n `JsonRpcEngine: Nothing ended request:\\n${stringify(request)}`,\n { request },\n );\n }\n }\n}\n"]}
@@ -1,8 +1,8 @@
1
- import type { JsonRpcParams, JsonRpcRequest } from "@metamask/utils";
2
- import type { JsonRpcEngine } from "./JsonRpcEngine.cjs";
3
- import type { JsonRpcMiddleware as LegacyMiddleware } from "./JsonRpcEngine.cjs";
4
- import type { ContextConstraint, MiddlewareContext } from "./v2/index.cjs";
5
- import type { JsonRpcMiddleware, ResultConstraint } from "./v2/JsonRpcEngineV2.cjs";
1
+ import type { JsonRpcParams, JsonRpcRequest } from '@metamask/utils';
2
+ import type { JsonRpcEngine } from './JsonRpcEngine.js';
3
+ import type { JsonRpcMiddleware as LegacyMiddleware } from './JsonRpcEngine.js';
4
+ import type { ContextConstraint, MiddlewareContext } from './v2/index.js';
5
+ import type { JsonRpcMiddleware, ResultConstraint } from './v2/JsonRpcEngineV2.js';
6
6
  /**
7
7
  * Convert a legacy {@link JsonRpcEngine} into a {@link JsonRpcEngineV2} middleware.
8
8
  *
@@ -17,4 +17,4 @@ export declare function asV2Middleware<Params extends JsonRpcParams, Request ext
17
17
  * @returns The {@link JsonRpcEngineV2} middleware.
18
18
  */
19
19
  export declare function asV2Middleware<Params extends JsonRpcParams = JsonRpcParams, Request extends JsonRpcRequest<Params> = JsonRpcRequest<Params>, Result extends ResultConstraint<Request> = ResultConstraint<Request>, Context extends ContextConstraint = MiddlewareContext>(...middleware: LegacyMiddleware<Params, Result>[]): JsonRpcMiddleware<Request, Result, Context>;
20
- //# sourceMappingURL=asV2Middleware.d.cts.map
20
+ //# sourceMappingURL=asV2Middleware.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"asV2Middleware.d.ts","sourceRoot":"","sources":["../src/asV2Middleware.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAGV,aAAa,EACb,cAAc,EAEf,MAAM,iBAAiB,CAAC;AAEzB,OAAO,KAAK,EACV,aAAa,EAGd,MAAM,oBAAoB,CAAC;AAC5B,OAAO,KAAK,EAAE,iBAAiB,IAAI,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAShF,OAAO,KAAK,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAC1E,OAAO,KAAK,EAIV,iBAAiB,EACjB,gBAAgB,EACjB,MAAM,yBAAyB,CAAC;AAEjC;;;;;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,GAAG,aAAa,EAC5C,OAAO,SAAS,cAAc,CAAC,MAAM,CAAC,GAAG,cAAc,CAAC,MAAM,CAAC,EAC/D,MAAM,SAAS,gBAAgB,CAAC,OAAO,CAAC,GAAG,gBAAgB,CAAC,OAAO,CAAC,EACpE,OAAO,SAAS,iBAAiB,GAAG,iBAAiB,EAErD,GAAG,UAAU,EAAE,gBAAgB,CAAC,MAAM,EAAE,MAAM,CAAC,EAAE,GAChD,iBAAiB,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC"}
@@ -1,7 +1,7 @@
1
- import { serializeError } from "@metamask/rpc-errors";
2
- import { hasProperty } from "@metamask/utils";
3
- import { mergeMiddleware } from "./mergeMiddleware.mjs";
4
- import { deepClone, fromLegacyRequest, propagateToContext, propagateToRequest, deserializeError } from "./v2/compatibility-utils.mjs";
1
+ import { serializeError } from '@metamask/rpc-errors';
2
+ import { hasProperty } from '@metamask/utils';
3
+ import { mergeMiddleware } from './mergeMiddleware.js';
4
+ import { deepClone, fromLegacyRequest, propagateToContext, propagateToRequest, deserializeError, } from './v2/compatibility-utils.js';
5
5
  /**
6
6
  * The asV2Middleware implementation.
7
7
  *
@@ -50,4 +50,4 @@ export function asV2Middleware(engineOrMiddleware, ...rest) {
50
50
  return next(fromLegacyRequest(req));
51
51
  };
52
52
  }
53
- //# sourceMappingURL=asV2Middleware.mjs.map
53
+ //# sourceMappingURL=asV2Middleware.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"asV2Middleware.js","sourceRoot":"","sources":["../src/asV2Middleware.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AACtD,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAe9C,OAAO,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AACvD,OAAO,EACL,SAAS,EACT,iBAAiB,EACjB,kBAAkB,EAClB,kBAAkB,EAClB,gBAAgB,GACjB,MAAM,6BAA6B,CAAC;AAoCrC;;;;;;GAMG;A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C,QAAQ,EAAE,OAAO,CAAC,IAAI,QAAQ,CAAC,KAAK,EAAE,CAAC;YACrD,MAAM,gBAAgB,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;QACzC,CAAC;aAAM,IAAI,WAAW,CAAC,QAAQ,EAAE,QAAQ,CAAC,EAAE,CAAC;YAC3C,OAAO,QAAQ,CAAC,MAAmC,CAAC;QACtD,CAAC;QACD,OAAO,IAAI,CAAC,iBAAiB,CAAC,GAAc,CAAC,CAAC,CAAC;IACjD,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { serializeError } from '@metamask/rpc-errors';\nimport { hasProperty } from '@metamask/utils';\nimport type {\n Json,\n JsonRpcFailure,\n JsonRpcParams,\n JsonRpcRequest,\n JsonRpcResponse,\n} from '@metamask/utils';\n\nimport type {\n JsonRpcEngine,\n JsonRpcEngineEndCallback,\n JsonRpcEngineNextCallback,\n} from './JsonRpcEngine.js';\nimport type { JsonRpcMiddleware as LegacyMiddleware } from './JsonRpcEngine.js';\nimport { mergeMiddleware } from './mergeMiddleware.js';\nimport {\n deepClone,\n fromLegacyRequest,\n propagateToContext,\n propagateToRequest,\n deserializeError,\n} from './v2/compatibility-utils.js';\nimport type { ContextConstraint, MiddlewareContext } from './v2/index.js';\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.js';\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 = JsonRpcParams,\n Request extends JsonRpcRequest<Params> = JsonRpcRequest<Params>,\n Result extends ResultConstraint<Request> = ResultConstraint<Request>,\n Context extends ContextConstraint = MiddlewareContext,\n>(\n ...middleware: LegacyMiddleware<Params, Result>[]\n): JsonRpcMiddleware<Request, Result, Context>;\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 uses .asMiddleware() internally, which is necessary for our purposes.\n // See comment on this below.\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 = ((callback: JsonRpcEngineEndCallback) =>\n callback(end)) as JsonRpcEngineNextCallback;\n\n legacyMiddleware(req, res, legacyNext, end);\n });\n propagateToContext(req, context);\n\n // Mimic the behavior of JsonRpcEngine.#handle(), which only treats truthy errors as errors.\n // Legacy middleware may violate the invariant that response objects have either a result or an\n // error property. In practice, we may see response objects with results and `{ error: undefined }`.\n if (hasProperty(response, 'error') && response.error) {\n throw deserializeError(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,5 @@
1
- import type { Json, JsonRpcParams, JsonRpcRequest, PendingJsonRpcResponse } from "@metamask/utils";
2
- import type { JsonRpcMiddleware } from "./JsonRpcEngine.mjs";
1
+ import type { Json, JsonRpcParams, JsonRpcRequest, PendingJsonRpcResponse } from '@metamask/utils';
2
+ import type { JsonRpcMiddleware } from './JsonRpcEngine.js';
3
3
  export type AsyncJsonRpcEngineNextCallback = () => Promise<void>;
4
4
  export type AsyncJsonrpcMiddleware<Params extends JsonRpcParams, Result extends Json> = (request: JsonRpcRequest<Params>, response: PendingJsonRpcResponse<Result>, next: AsyncJsonRpcEngineNextCallback) => Promise<void>;
5
5
  /**
@@ -25,4 +25,4 @@ export type AsyncJsonrpcMiddleware<Params extends JsonRpcParams, Result extends
25
25
  * by JsonRpcEngine.
26
26
  */
27
27
  export declare function createAsyncMiddleware<Params extends JsonRpcParams, Result extends Json>(asyncMiddleware: AsyncJsonrpcMiddleware<Params, Result>): JsonRpcMiddleware<Params, Result>;
28
- //# sourceMappingURL=createAsyncMiddleware.d.mts.map
28
+ //# sourceMappingURL=createAsyncMiddleware.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"createAsyncMiddleware.d.ts","sourceRoot":"","sources":["../src/createAsyncMiddleware.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,IAAI,EACJ,aAAa,EACb,cAAc,EACd,sBAAsB,EACvB,MAAM,iBAAiB,CAAC;AAEzB,OAAO,KAAK,EAEV,iBAAiB,EAClB,MAAM,oBAAoB,CAAC;AAE5B,MAAM,MAAM,8BAA8B,GAAG,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;AAEjE,MAAM,MAAM,sBAAsB,CAChC,MAAM,SAAS,aAAa,EAC5B,MAAM,SAAS,IAAI,IACjB,CACF,OAAO,EAAE,cAAc,CAAC,MAAM,CAAC,EAC/B,QAAQ,EAAE,sBAAsB,CAAC,MAAM,CAAC,EACxC,IAAI,EAAE,8BAA8B,KACjC,OAAO,CAAC,IAAI,CAAC,CAAC;AAInB;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAgB,qBAAqB,CACnC,MAAM,SAAS,aAAa,EAC5B,MAAM,SAAS,IAAI,EAEnB,eAAe,EAAE,sBAAsB,CAAC,MAAM,EAAE,MAAM,CAAC,GACtD,iBAAiB,CAAC,MAAM,EAAE,MAAM,CAAC,CA6CnC"}
@@ -64,4 +64,4 @@ export function createAsyncMiddleware(asyncMiddleware) {
64
64
  }
65
65
  };
66
66
  }
67
- //# sourceMappingURL=createAsyncMiddleware.mjs.map
67
+ //# sourceMappingURL=createAsyncMiddleware.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"createAsyncMiddleware.js","sourceRoot":"","sources":["../src/createAsyncMiddleware.ts"],"names":[],"mappings":"AAyBA;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,MAAM,UAAU,qBAAqB,CAInC,eAAuD;IAEvD,kEAAkE;IAClE,OAAO,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,GAAG,EAAE,EAAE;QAC5C,+CAA+C;QAC/C,qDAAqD;QACrD,kBAAkB;QAClB,IAAI,kBAA8B,CAAC;QACnC,MAAM,WAAW,GAAG,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,EAAE;YAChD,kBAAkB,GAAG,OAAO,CAAC;QAC/B,CAAC,CAAC,CAAC;QAEH,IAAI,qBAAqB,GAAY,IAAI,CAAC;QAC1C,IAAI,aAAa,GAAG,KAAK,CAAC;QAE1B,0DAA0D;QAC1D,MAAM,SAAS,GAAG,KAAK,IAAmB,EAAE;YAC1C,aAAa,GAAG,IAAI,CAAC;YAErB,uEAAuE;YACvE,yDAAyD;YACzD,IAAI,CAAC,CAAC,yBAAyB,EAAE,EAAE;gBACjC,4DAA4D;gBAC5D,qBAAqB,GAAG,yBAAyB,CAAC;gBAClD,kBAAkB,EAAE,CAAC;YACvB,CAAC,CAAC,CAAC;YACH,OAAO,WAAW,CAAC;QACrB,CAAC,CAAC;QAEF,IAAI,CAAC;YACH,MAAM,eAAe,CAAC,OAAO,EAAE,QAAQ,EAAE,SAAS,CAAC,CAAC;YAEpD,IAAI,aAAa,EAAE,CAAC;gBAClB,MAAM,WAAW,CAAC,CAAC,kDAAkD;gBACpE,qBAA+C,CAAC,IAAI,CAAC,CAAC;YACzD,CAAC;iBAAM,CAAC;gBACN,GAAG,CAAC,IAAI,CAAC,CAAC;YACZ,CAAC;QACH,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,qBAAqB,EAAE,CAAC;gBACzB,qBAA+C,CAAC,KAAK,CAAC,CAAC;YAC1D,CAAC;iBAAM,CAAC;gBACN,GAAG,CAAC,KAAK,CAAC,CAAC;YACb,CAAC;QACH,CAAC;IACH,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import type {\n Json,\n JsonRpcParams,\n JsonRpcRequest,\n PendingJsonRpcResponse,\n} from '@metamask/utils';\n\nimport type {\n JsonRpcEngineReturnHandler,\n JsonRpcMiddleware,\n} from './JsonRpcEngine.js';\n\nexport type AsyncJsonRpcEngineNextCallback = () => Promise<void>;\n\nexport type AsyncJsonrpcMiddleware<\n Params extends JsonRpcParams,\n Result extends Json,\n> = (\n request: JsonRpcRequest<Params>,\n response: PendingJsonRpcResponse<Result>,\n next: AsyncJsonRpcEngineNextCallback,\n) => Promise<void>;\n\ntype ReturnHandlerCallback = Parameters<JsonRpcEngineReturnHandler>[0];\n\n/**\n * JsonRpcEngine only accepts callback-based middleware directly.\n * createAsyncMiddleware exists to enable consumers to pass in async middleware\n * functions.\n *\n * Async middleware have no \"end\" function. Instead, they \"end\" if they return\n * without calling \"next\". Rather than passing in explicit return handlers,\n * async middleware can simply await \"next\", and perform operations on the\n * response object when execution resumes.\n *\n * To accomplish this, createAsyncMiddleware passes the async middleware a\n * wrapped \"next\" function. That function calls the internal JsonRpcEngine\n * \"next\" function with a return handler that resolves a promise when called.\n *\n * The return handler will always be called. Its resolution of the promise\n * enables the control flow described above.\n *\n * @deprecated Use `JsonRpcEngineV2` and its corresponding types instead.\n * @param asyncMiddleware - The asynchronous middleware function to wrap.\n * @returns The wrapped asynchronous middleware function, ready to be consumed\n * by JsonRpcEngine.\n */\nexport function createAsyncMiddleware<\n Params extends JsonRpcParams,\n Result extends Json,\n>(\n asyncMiddleware: AsyncJsonrpcMiddleware<Params, Result>,\n): JsonRpcMiddleware<Params, Result> {\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n return async (request, response, next, end) => {\n // nextPromise is the key to the implementation\n // it is resolved by the return handler passed to the\n // \"next\" function\n let resolveNextPromise: () => void;\n const nextPromise = new Promise<void>((resolve) => {\n resolveNextPromise = resolve;\n });\n\n let returnHandlerCallback: unknown = null;\n let nextWasCalled = false;\n\n // This will be called by the consumer's async middleware.\n const asyncNext = async (): Promise<void> => {\n nextWasCalled = true;\n\n // We pass a return handler to next(). When it is called by the engine,\n // the consumer's async middleware will resume executing.\n next((runReturnHandlersCallback) => {\n // This callback comes from JsonRpcEngine._runReturnHandlers\n returnHandlerCallback = runReturnHandlersCallback;\n resolveNextPromise();\n });\n return nextPromise;\n };\n\n try {\n await asyncMiddleware(request, response, asyncNext);\n\n if (nextWasCalled) {\n await nextPromise; // we must wait until the return handler is called\n (returnHandlerCallback as ReturnHandlerCallback)(null);\n } else {\n end(null);\n }\n } catch (error) {\n if (returnHandlerCallback) {\n (returnHandlerCallback as ReturnHandlerCallback)(error);\n } else {\n end(error);\n }\n }\n };\n}\n"]}
@@ -1,8 +1,8 @@
1
- import type { ActionConstraint } from "@metamask/messenger";
2
- import type { Messenger } from "@metamask/messenger";
3
- import type { Json, JsonRpcParams, JsonRpcRequest, PendingJsonRpcResponse } from "@metamask/utils";
4
- import type { JsonRpcEngineEndCallback, JsonRpcEngineNextCallback, JsonRpcMiddleware } from "./JsonRpcEngine.mjs";
5
- import { UnionToIntersection } from "./v2/utils.mjs";
1
+ import type { ActionConstraint } from '@metamask/messenger';
2
+ import type { Messenger } from '@metamask/messenger';
3
+ import type { Json, JsonRpcParams, JsonRpcRequest, PendingJsonRpcResponse } from '@metamask/utils';
4
+ import type { JsonRpcEngineEndCallback, JsonRpcEngineNextCallback, JsonRpcMiddleware } from './JsonRpcEngine.js';
5
+ import { UnionToIntersection } from './v2/utils.js';
6
6
  type HandlerActions<Handler> = Handler extends {
7
7
  implementation: (...args: infer Args) => unknown;
8
8
  } ? Args extends [
@@ -83,4 +83,4 @@ export type CreateMethodMiddlewareOptions<Handlers extends Record<string, AnyMet
83
83
  */
84
84
  export declare function createMethodMiddleware<Handlers extends Record<string, AnyMethodHandler>>(options: CreateMethodMiddlewareOptions<Handlers>): JsonRpcMiddleware<JsonRpcParams, Json>;
85
85
  export {};
86
- //# sourceMappingURL=createMethodMiddleware.d.mts.map
86
+ //# sourceMappingURL=createMethodMiddleware.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"createMethodMiddleware.d.ts","sourceRoot":"","sources":["../src/createMethodMiddleware.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAC5D,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAErD,OAAO,KAAK,EACV,IAAI,EACJ,aAAa,EACb,cAAc,EACd,sBAAsB,EACvB,MAAM,iBAAiB,CAAC;AAEzB,OAAO,KAAK,EACV,wBAAwB,EACxB,yBAAyB,EACzB,iBAAiB,EAClB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAIL,mBAAmB,EACpB,MAAM,eAAe,CAAC;AAEvB,KAAK,cAAc,CAAC,OAAO,IAAI,OAAO,SAAS;IAC7C,cAAc,EAAE,CAAC,GAAG,IAAI,EAAE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