@metamask-previews/json-rpc-engine 7.3.0-preview.eb58a59 → 7.3.1-preview.228ccaca

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
@@ -6,6 +6,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [7.3.1]
10
+ ### Changed
11
+ - There are no consumer-facing changes to this package. This version is a part of a synchronized release across all packages in our monorepo.
12
+
9
13
  ## [7.3.0]
10
14
  ### Added
11
15
  - Migrate `@metamask/json-rpc-engine` into the core monorepo ([#1895](https://github.com/MetaMask/core/pull/1895))
@@ -92,7 +96,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
92
96
  This change may affect consumers that depend on the eager execution of middleware _during_ request processing, _outside of_ middleware functions and request handlers.
93
97
  - In general, it is a bad practice to work with state that depends on middleware execution, while the middleware are executing.
94
98
 
95
- [Unreleased]: https://github.com/MetaMask/core/compare/@metamask/json-rpc-engine@7.3.0...HEAD
99
+ [Unreleased]: https://github.com/MetaMask/core/compare/@metamask/json-rpc-engine@7.3.1...HEAD
100
+ [7.3.1]: https://github.com/MetaMask/core/compare/@metamask/json-rpc-engine@7.3.0...@metamask/json-rpc-engine@7.3.1
96
101
  [7.3.0]: https://github.com/MetaMask/core/compare/@metamask/json-rpc-engine@7.2.0...@metamask/json-rpc-engine@7.3.0
97
102
  [7.2.0]: https://github.com/MetaMask/core/compare/@metamask/json-rpc-engine@7.1.1...@metamask/json-rpc-engine@7.2.0
98
103
  [7.1.1]: https://github.com/MetaMask/core/compare/@metamask/json-rpc-engine@7.1.0...@metamask/json-rpc-engine@7.1.1
@@ -1 +1 @@
1
- {"version":3,"file":"JsonRpcEngine.d.ts","sourceRoot":"","sources":["../src/JsonRpcEngine.ts"],"names":[],"mappings":"AACA,OAAO,gBAAgB,MAAM,8BAA8B,CAAC;AAC5D,OA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MAAM,CAAC,MAAM,SAAS,aAAa,EAAE,MAAM,SAAS,IAAI,EACtD,OAAO,EAAE,cAAc,CAAC,MAAM,CAAC,GAC9B,OAAO,CAAC,eAAe,CAAC,MAAM,CAAC,CAAC;IAEnC;;;;OAIG;IACH,MAAM,CAAC,MAAM,SAAS,aAAa,EACjC,YAAY,EAAE,mBAAmB,CAAC,MAAM,CAAC,GACxC,OAAO,CAAC,IAAI,CAAC;IAEhB;;;;;;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;IAwBrC;;;;;OAKG;IACH,YAAY,IAAI,iBAAiB,CAAC,aAAa,EAAE,IAAI,CAAC;IA0GtD;;;;;OAKG;YAIW,cAAc;CAsS7B"}
@@ -85,6 +85,8 @@ class JsonRpcEngine extends safe_event_emitter_1.default {
85
85
  __classPrivateFieldGet(this, _JsonRpcEngine_instances, "m", _JsonRpcEngine_assertIsNotDestroyed).call(this);
86
86
  __classPrivateFieldGet(this, _JsonRpcEngine_middleware, "f").push(middleware);
87
87
  }
88
+ // TODO: Replace `any` with type
89
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
88
90
  handle(req, callback) {
89
91
  __classPrivateFieldGet(this, _JsonRpcEngine_instances, "m", _JsonRpcEngine_assertIsNotDestroyed).call(this);
90
92
  if (callback && typeof callback !== 'function') {
@@ -121,12 +123,16 @@ class JsonRpcEngine extends safe_event_emitter_1.default {
121
123
  return next((handlerCallback) => __awaiter(this, void 0, void 0, function* () {
122
124
  try {
123
125
  yield __classPrivateFieldGet(JsonRpcEngine, _a, "m", _JsonRpcEngine_runReturnHandlers).call(JsonRpcEngine, returnHandlers);
126
+ // TODO: Replace `any` with type
127
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
124
128
  }
125
129
  catch (error) {
126
130
  return handlerCallback(error);
127
131
  }
128
132
  return handlerCallback();
129
133
  }));
134
+ // TODO: Replace `any` with type
135
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
130
136
  }
131
137
  catch (error) {
132
138
  return end(error);
@@ -249,6 +255,8 @@ _a = JsonRpcEngine, _JsonRpcEngine_isDestroyed = new WeakMap(), _JsonRpcEngine_m
249
255
  };
250
256
  try {
251
257
  yield __classPrivateFieldGet(JsonRpcEngine, _a, "m", _JsonRpcEngine_processRequest).call(JsonRpcEngine, req, res, __classPrivateFieldGet(this, _JsonRpcEngine_middleware, "f"));
258
+ // TODO: Replace `any` with type
259
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
252
260
  }
253
261
  catch (_error) {
254
262
  // A request handler error, a re-thrown middleware error, or something
@@ -323,6 +331,8 @@ _a = JsonRpcEngine, _JsonRpcEngine_isDestroyed = new WeakMap(), _JsonRpcEngine_m
323
331
  };
324
332
  try {
325
333
  middleware(request, response, next, end);
334
+ // TODO: Replace `any` with type
335
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
326
336
  }
327
337
  catch (error) {
328
338
  end(error);
@@ -1 +1 @@
1
- {"version":3,"file":"JsonRpcEngine.js","sourceRoot":"","sources":["../src/JsonRpcEngine.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,qDAAgF;AAChF,sFAA4D;AAU5D,2CAAgE;AA6BhE,MAAM,uBAAuB,GAC3B,qDAAqD,CAAC;AAmBxD;;;GAGG;AACH,MAAa,aAAc,SAAQ,4BAAgB;IAYjD;;;;;;;;;;OAUG;IACH,YAAY,EAAE,mBAAmB,KAAwB,EAAE;QACzD,KAAK,EAAE,CAAC;;QAvBV;;WAEG;QACH,qCAAe,KAAK,EAAC;QAErB,4CAAsD;QAEtD,qDAEc;QAeZ,uBAAA,IAAI,6BAAe,EAAE,MAAA,CAAC;QACtB,uBAAA,IAAI,sCAAwB,mBA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e,EAAE,CAC7B,CAAC;KACH;IAED,IAAI,CAAC,UAAU,EAAE;QACf,MAAM,IAAI,yBAAY,CACpB,uBAAU,CAAC,GAAG,CAAC,QAAQ,EACvB,0CAA0C,OAAO,CAAC,OAAO,CAAC,EAAE,EAC5D,EAAE,OAAO,EAAE,OAAe,EAAE,CAC7B,CAAC;KACH;AACH,CAAC;AAGH;;;;;GAKG;AACH,SAAS,OAAO,CAAC,OAAuB;IACtC,OAAO,IAAI,CAAC,SAAS,CAAC,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;AAC1C,CAAC","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 { hasProperty, isJsonRpcRequest } from '@metamask/utils';\n\nexport type JsonRpcEngineCallbackError = Error | SerializedJsonRpcError | null;\n\nexport type JsonRpcEngineReturnHandler = (\n done: (error?: JsonRpcEngineCallbackError) => void,\n) => void;\n\nexport type JsonRpcEngineNextCallback = (\n returnHandlerCallback?: JsonRpcEngineReturnHandler,\n) => void;\n\nexport type JsonRpcEngineEndCallback = (\n error?: JsonRpcEngineCallbackError,\n) => void;\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\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 * Give it a stack of middleware, pass it requests, and get back responses.\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() {\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(req: unknown, callback?: any) {\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(req, callback);\n }\n return this.#handleBatch(req);\n }\n\n if (callback) {\n return this.#handle(req as JsonRpcRequest, callback);\n }\n return this._promiseHandle(req as JsonRpcRequest);\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 as JsonRpcEngineCallbackError);\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: any) {\n return handlerCallback(error);\n }\n return handlerCallback();\n });\n } catch (error: any) {\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<Json>[]>;\n\n /**\n * Like _handle, but for batch requests.\n */\n #handleBatch(\n reqs: (JsonRpcRequest | JsonRpcNotification)[],\n callback: (error: unknown, responses?: JsonRpcResponse<Json>[]) => 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<Json>[]) => void,\n ): Promise<JsonRpcResponse<Json>[] | 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<Json>[] = [\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 !== undefined,\n ) as JsonRpcResponse<Json>[];\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<Json> | 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 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<Json>) => 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 as Json },\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 }\n\n // Handle notifications.\n // We can't use isJsonRpcNotification here because that narrows callerReq to\n // \"never\" after the if clause for unknown reasons.\n if (this.#notificationHandler && !isJsonRpcRequest(callerReq)) {\n try {\n await this.#notificationHandler(callerReq);\n } catch (error) {\n return callback(error);\n }\n return callback(null);\n }\n\n let error: JsonRpcEngineCallbackError = null;\n\n // Handle requests.\n // Typecast: Permit missing id's for backwards compatibility.\n const req = { ...(callerReq as JsonRpcRequest) };\n const res: PendingJsonRpcResponse<Json> = {\n id: req.id,\n jsonrpc: req.jsonrpc,\n };\n\n try {\n await JsonRpcEngine.#processRequest(req, res, this.#middleware);\n } catch (_error: any) {\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 if (!res.error) {\n res.error = serializeError(error);\n }\n }\n\n return callback(error, res as JsonRpcResponse<Json>);\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<Json>,\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/no-throw-literal\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<Json>,\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 exection,\n * and a boolean indicating whether the request should end.\n */\n static async #runMiddleware(\n request: JsonRpcRequest,\n response: PendingJsonRpcResponse<Json>,\n middleware: JsonRpcMiddleware<JsonRpcParams, Json>,\n returnHandlers: JsonRpcEngineReturnHandler[],\n ): Promise<[unknown, boolean]> {\n return new Promise((resolve) => {\n const end: JsonRpcEngineEndCallback = (error?: unknown) => {\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${jsonify(\n request,\n )}`,\n { request: request as Json },\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: any) {\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 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<Json>,\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${jsonify(\n request,\n )}`,\n { request: request as Json },\n );\n }\n\n if (!isComplete) {\n throw new JsonRpcError(\n errorCodes.rpc.internal,\n `JsonRpcEngine: Nothing ended request:\\n${jsonify(request)}`,\n { request: request as Json },\n );\n }\n }\n}\n\n/**\n * JSON-stringifies a request object.\n *\n * @param request - The request object to JSON-stringify.\n * @returns The JSON-stringified request object.\n */\nfunction jsonify(request: JsonRpcRequest): string {\n return JSON.stringify(request, null, 2);\n}\n"]}
1
+ {"version":3,"file":"JsonRpcEngine.js","sourceRoot":"","sources":["../src/JsonRpcEngine.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,qDAAgF;AAChF,sFAA4D;AAU5D,2CAAgE;AA6BhE,MAAM,uBAAuB,GAC3B,qDAAqD,CAAC;AAmBxD;;;GAGG;AACH,MAAa,aAAc,SAAQ,4BAAgB;IAYjD;;;;;;;;;;OAUG;IACH,YAAY,EAAE,mBAAmB,KAAwB,EAAE;QACzD,KAAK,EAAE,CAAC;;QAvBV;;WAEG;QACH,qCAAe,KAAK,EAAC;QAErB,4CAAsD;QAEtD,qDAEc;QAeZ,uBAAA,IAAI,6BAAe,EAAE,MAAA,CAAC;QACtB,uBAAA,IAAI,sCAAwB,mBAAmB,MAAA,CAAC;IAClD,CAAC;IAWD;;;;OAIG;IACH,OAAO;QACL,uBAAA,IAAI,iCAAY,CAAC,OAAO,CACtB,CAAC,UAAkD,EAAE,EAAE;YACrD;YACE,gEAAgE;YAChE,iBAAiB;YACjB,SAAS,IAAI,UAAU;gBACvB,OAAO,UAAU,CAAC,OAAO,KAAK,UAAU,EACxC;gBACA,mEAAmE;gBACnE,UAAU,CAAC,OAAO,EAAE,CAAC;aACtB;QACH,CAAC,CACF,CAAC;QACF,uBAAA,IAAI,6BAAe,EAAE,MAAA,CAAC;QACtB,uBAAA,IAAI,8BAAgB,IAAI,MAAA,CAAC;IAC3B,CAAC;IAED;;;;OAIG;IACH,IAAI,CACF,UAA6C;QAE7C,uBAAA,IAAI,qEAAsB,MAA1B,IAAI,CAAwB,CAAC;QAC7B,uBAAA,IAAI,iCAAY,CAAC,IAAI,CAAC,UAAoD,CAAC,CAAC;IAC9E,CAAC;IAmED,gCAAgC;IAChC,8DAA8D;IAC9D,MAAM,CAAC,GAAY,EAAE,QAAc;QACjC,uBAAA,IAAI,qEAAsB,MAA1B,IAAI,CAAw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,GAAG,CAAC,KAAK,CAAC,CAAC;aACZ;QACH,CAAC,CAAC,CAAC;IACL,CAAC;gFASC,QAAsC;;QAEtC,KAAK,MAAM,OAAO,IAAI,QAAQ,EAAE;YAC9B,MAAM,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;gBAC1C,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;SACJ;IACH,CAAC;kFAYC,OAAuB,EACvB,QAAsC,EACtC,UAAmB;IAEnB,IAAI,CAAC,IAAA,mBAAW,EAAC,QAAQ,EAAE,QAAQ,CAAC,IAAI,CAAC,IAAA,mBAAW,EAAC,QAAQ,EAAE,OAAO,CAAC,EAAE;QACvE,MAAM,IAAI,yBAAY,CACpB,uBAAU,CAAC,GAAG,CAAC,QAAQ,EACvB,gEAAgE,OAAO,CACrE,OAAO,CACR,EAAE,EACH,EAAE,OAAO,EAAE,OAAe,EAAE,CAC7B,CAAC;KACH;IAED,IAAI,CAAC,UAAU,EAAE;QACf,MAAM,IAAI,yBAAY,CACpB,uBAAU,CAAC,GAAG,CAAC,QAAQ,EACvB,0CAA0C,OAAO,CAAC,OAAO,CAAC,EAAE,EAC5D,EAAE,OAAO,EAAE,OAAe,EAAE,CAC7B,CAAC;KACH;AACH,CAAC;AAGH;;;;;GAKG;AACH,SAAS,OAAO,CAAC,OAAuB;IACtC,OAAO,IAAI,CAAC,SAAS,CAAC,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;AAC1C,CAAC","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 { hasProperty, isJsonRpcRequest } from '@metamask/utils';\n\nexport type JsonRpcEngineCallbackError = Error | SerializedJsonRpcError | null;\n\nexport type JsonRpcEngineReturnHandler = (\n done: (error?: JsonRpcEngineCallbackError) => void,\n) => void;\n\nexport type JsonRpcEngineNextCallback = (\n returnHandlerCallback?: JsonRpcEngineReturnHandler,\n) => void;\n\nexport type JsonRpcEngineEndCallback = (\n error?: JsonRpcEngineCallbackError,\n) => void;\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\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 * Give it a stack of middleware, pass it requests, and get back responses.\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() {\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 // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n handle(req: unknown, callback?: any) {\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(req, callback);\n }\n return this.#handleBatch(req);\n }\n\n if (callback) {\n return this.#handle(req as JsonRpcRequest, callback);\n }\n return this._promiseHandle(req as JsonRpcRequest);\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 as JsonRpcEngineCallbackError);\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 // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (error: any) {\n return handlerCallback(error);\n }\n return handlerCallback();\n });\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (error: any) {\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<Json>[]>;\n\n /**\n * Like _handle, but for batch requests.\n */\n #handleBatch(\n reqs: (JsonRpcRequest | JsonRpcNotification)[],\n callback: (error: unknown, responses?: JsonRpcResponse<Json>[]) => 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<Json>[]) => void,\n ): Promise<JsonRpcResponse<Json>[] | 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<Json>[] = [\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 !== undefined,\n ) as JsonRpcResponse<Json>[];\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<Json> | 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 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<Json>) => 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 as Json },\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 }\n\n // Handle notifications.\n // We can't use isJsonRpcNotification here because that narrows callerReq to\n // \"never\" after the if clause for unknown reasons.\n if (this.#notificationHandler && !isJsonRpcRequest(callerReq)) {\n try {\n await this.#notificationHandler(callerReq);\n } catch (error) {\n return callback(error);\n }\n return callback(null);\n }\n\n let error: JsonRpcEngineCallbackError = null;\n\n // Handle requests.\n // Typecast: Permit missing id's for backwards compatibility.\n const req = { ...(callerReq as JsonRpcRequest) };\n const res: PendingJsonRpcResponse<Json> = {\n id: req.id,\n jsonrpc: req.jsonrpc,\n };\n\n try {\n await JsonRpcEngine.#processRequest(req, res, this.#middleware);\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (_error: any) {\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 if (!res.error) {\n res.error = serializeError(error);\n }\n }\n\n return callback(error, res as JsonRpcResponse<Json>);\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<Json>,\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/no-throw-literal\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<Json>,\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 exection,\n * and a boolean indicating whether the request should end.\n */\n static async #runMiddleware(\n request: JsonRpcRequest,\n response: PendingJsonRpcResponse<Json>,\n middleware: JsonRpcMiddleware<JsonRpcParams, Json>,\n returnHandlers: JsonRpcEngineReturnHandler[],\n ): Promise<[unknown, boolean]> {\n return new Promise((resolve) => {\n const end: JsonRpcEngineEndCallback = (error?: unknown) => {\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${jsonify(\n request,\n )}`,\n { request: request as Json },\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 // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (error: any) {\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 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<Json>,\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${jsonify(\n request,\n )}`,\n { request: request as Json },\n );\n }\n\n if (!isComplete) {\n throw new JsonRpcError(\n errorCodes.rpc.internal,\n `JsonRpcEngine: Nothing ended request:\\n${jsonify(request)}`,\n { request: request as Json },\n );\n }\n }\n}\n\n/**\n * JSON-stringifies a request object.\n *\n * @param request - The request object to JSON-stringify.\n * @returns The JSON-stringified request object.\n */\nfunction jsonify(request: JsonRpcRequest): string {\n return JSON.stringify(request, null, 2);\n}\n"]}
@@ -1 +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,EAAE,iB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AAM,CAAC,GACtD,iBAAiB,CAAC,MAAM,EAAE,MAAM,CAAC,CA+CnC"}
@@ -64,6 +64,8 @@ function createAsyncMiddleware(asyncMiddleware) {
64
64
  else {
65
65
  end(null);
66
66
  }
67
+ // TODO: Replace `any` with type
68
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
67
69
  }
68
70
  catch (error) {
69
71
  if (returnHandlerCallback) {
@@ -1 +1 @@
1
- {"version":3,"file":"createAsyncMiddleware.js","sourceRoot":"","sources":["../src/createAsyncMiddleware.ts"],"names":[],"mappings":";;;;;;;;;;;;AAsBA;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,SAAgB,qBAAqB,CAInC,eAAuD;IAEvD,kEAAkE;IAClE,OAAO,CAAO,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,GAAS,EAAE;YAC3B,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,CAAA,CAAC;QAEF,IAAI;YACF,MAAM,eAAe,CAAC,OAAO,EAAE,QAAQ,EAAE,SAAS,CAAC,CAAC;YAEpD,IAAI,aAAa,EAAE;gBACjB,MAAM,WAAW,CAAC,CAAC,kDAAkD;gBACpE,qBAA+C,CAAC,IAAI,CAAC,CAAC;aACxD;iBAAM;gBACL,GAAG,CAAC,IAAI,CAAC,CAAC;aACX;SACF;QAAC,OAAO,KAAU,EAAE;YACnB,IAAI,qBAAqB,EAAE;gBACxB,qBAA+C,CAAC,KAAK,CAAC,CAAC;aACzD;iBAAM;gBACL,GAAG,CAAC,KAAK,CAAC,CAAC;aACZ;SACF;IACH,CAAC,CAAA,CAAC;AACJ,CAAC;AAlDD,sDAkDC","sourcesContent":["import type {\n Json,\n JsonRpcParams,\n JsonRpcRequest,\n PendingJsonRpcResponse,\n} from '@metamask/utils';\n\nimport type { JsonRpcMiddleware } from './JsonRpcEngine';\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 = (error: null | Error) => void;\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 * @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 () => {\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: any) {\n if (returnHandlerCallback) {\n (returnHandlerCallback as ReturnHandlerCallback)(error);\n } else {\n end(error);\n }\n }\n };\n}\n"]}
1
+ {"version":3,"file":"createAsyncMiddleware.js","sourceRoot":"","sources":["../src/createAsyncMiddleware.ts"],"names":[],"mappings":";;;;;;;;;;;;AAsBA;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,SAAgB,qBAAqB,CAInC,eAAuD;IAEvD,kEAAkE;IAClE,OAAO,CAAO,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,GAAS,EAAE;YAC3B,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,CAAA,CAAC;QAEF,IAAI;YACF,MAAM,eAAe,CAAC,OAAO,EAAE,QAAQ,EAAE,SAAS,CAAC,CAAC;YAEpD,IAAI,aAAa,EAAE;gBACjB,MAAM,WAAW,CAAC,CAAC,kDAAkD;gBACpE,qBAA+C,CAAC,IAAI,CAAC,CAAC;aACxD;iBAAM;gBACL,GAAG,CAAC,IAAI,CAAC,CAAC;aACX;YACD,gCAAgC;YAChC,8DAA8D;SAC/D;QAAC,OAAO,KAAU,EAAE;YACnB,IAAI,qBAAqB,EAAE;gBACxB,qBAA+C,CAAC,KAAK,CAAC,CAAC;aACzD;iBAAM;gBACL,GAAG,CAAC,KAAK,CAAC,CAAC;aACZ;SACF;IACH,CAAC,CAAA,CAAC;AACJ,CAAC;AApDD,sDAoDC","sourcesContent":["import type {\n Json,\n JsonRpcParams,\n JsonRpcRequest,\n PendingJsonRpcResponse,\n} from '@metamask/utils';\n\nimport type { JsonRpcMiddleware } from './JsonRpcEngine';\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 = (error: null | Error) => void;\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 * @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 () => {\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 // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (error: any) {\n if (returnHandlerCallback) {\n (returnHandlerCallback as ReturnHandlerCallback)(error);\n } else {\n end(error);\n }\n }\n };\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metamask-previews/json-rpc-engine",
3
- "version": "7.3.0-preview.eb58a59",
3
+ "version": "7.3.1-preview.228ccaca",
4
4
  "description": "A tool for processing JSON-RPC messages",
5
5
  "keywords": [
6
6
  "MetaMask",
@@ -27,6 +27,7 @@
27
27
  "build": "tsc --project tsconfig.build.json",
28
28
  "build:clean": "rimraf dist && yarn build",
29
29
  "build:docs": "typedoc",
30
+ "changelog:update": "../../scripts/update-changelog.sh @metamask/json-rpc-engine --tag-prefix-before-package-rename json-rpc-engine@ --version-before-package-rename 6.1.0",
30
31
  "changelog:validate": "../../scripts/validate-changelog.sh @metamask/json-rpc-engine --tag-prefix-before-package-rename json-rpc-engine@ --version-before-package-rename 6.1.0",
31
32
  "lint": "yarn lint:eslint && yarn lint:misc --check && yarn lint:dependencies && yarn lint:changelog",
32
33
  "lint:changelog": "auto-changelog validate",
@@ -47,10 +48,9 @@
47
48
  },
48
49
  "devDependencies": {
49
50
  "@lavamoat/allow-scripts": "^2.3.1",
50
- "@metamask/auto-changelog": "^3.4.3",
51
+ "@metamask/auto-changelog": "^3.4.4",
51
52
  "@types/jest": "^27.4.1",
52
53
  "deepmerge": "^4.2.2",
53
- "depcheck": "^1.4.3",
54
54
  "jest": "^27.5.1",
55
55
  "jest-it-up": "^2.0.2",
56
56
  "ts-jest": "^27.1.4",