@metamask-previews/eth-json-rpc-provider 6.0.1-preview-5bb6dba48 → 6.0.1-preview-d8fceeabc

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
@@ -7,6 +7,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ### Added
11
+
12
+ - Add `MockInternalProvider`, which can be substituted for `InternalProvider` in tests, while providing the ability to assert requests and inject canned responses ([#10099](https://github.com/MetaMask/core/pull/10099))
13
+ - Also add `MockInternalProviderStub` type
14
+
10
15
  ### Changed
11
16
 
12
17
  - 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))
package/dist/index.cjs CHANGED
@@ -14,9 +14,11 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.SafeEventEmitterProvider = exports.InternalProvider = void 0;
17
+ exports.SafeEventEmitterProvider = exports.InternalProvider = exports.MockInternalProvider = void 0;
18
18
  const internal_provider_js_1 = require("./internal-provider.cjs");
19
19
  Object.defineProperty(exports, "InternalProvider", { enumerable: true, get: function () { return internal_provider_js_1.InternalProvider; } });
20
+ var mock_internal_provider_js_1 = require("./mock-internal-provider.cjs");
21
+ Object.defineProperty(exports, "MockInternalProvider", { enumerable: true, get: function () { return mock_internal_provider_js_1.MockInternalProvider; } });
20
22
  __exportStar(require("./provider-from-middleware.cjs"), exports);
21
23
  const SafeEventEmitterProvider = internal_provider_js_1.InternalProvider;
22
24
  exports.SafeEventEmitterProvider = SafeEventEmitterProvider;
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAAA,kEAA0D;AAUjD,iGAVA,uCAAgB,OAUA;AARzB,iEAA8C;AAM9C,MAAM,wBAAwB,GAAG,uCAAgB,CAAC;AAEvB,4DAAwB","sourcesContent":["import { InternalProvider } from './internal-provider.js';\n\nexport * from './provider-from-middleware.js';\n\n/**\n * @deprecated Use {@link InternalProvider} instead.\n */\ntype SafeEventEmitterProvider = InternalProvider;\nconst SafeEventEmitterProvider = InternalProvider;\n\nexport { InternalProvider, SafeEventEmitterProvider };\n"]}
1
+ {"version":3,"file":"index.cjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAAA,kEAA0D;AAajD,iGAbA,uCAAgB,OAaA;AAXzB,0EAAmE;AAA1D,iIAAA,oBAAoB,OAAA;AAG7B,iEAA8C;AAM9C,MAAM,wBAAwB,GAAG,uCAAgB,CAAC;AAEvB,4DAAwB","sourcesContent":["import { InternalProvider } from './internal-provider.js';\n\nexport { MockInternalProvider } from './mock-internal-provider.js';\nexport type { MockInternalProviderStub } from './mock-internal-provider.js';\n\nexport * from './provider-from-middleware.js';\n\n/**\n * @deprecated Use {@link InternalProvider} instead.\n */\ntype SafeEventEmitterProvider = InternalProvider;\nconst SafeEventEmitterProvider = InternalProvider;\n\nexport { InternalProvider, SafeEventEmitterProvider };\n"]}
package/dist/index.d.cts CHANGED
@@ -1,4 +1,6 @@
1
1
  import { InternalProvider } from "./internal-provider.cjs";
2
+ export { MockInternalProvider } from "./mock-internal-provider.cjs";
3
+ export type { MockInternalProviderStub } from "./mock-internal-provider.cjs";
2
4
  export * from "./provider-from-middleware.cjs";
3
5
  /**
4
6
  * @deprecated Use {@link InternalProvider} instead.
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.cts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,gCAA+B;AAE1D,+CAA8C;AAE9C;;GAEG;AACH,KAAK,wBAAwB,GAAG,gBAAgB,CAAC;AACjD,QAAA,MAAM,wBAAwB,yBAAmB,CAAC;AAElD,OAAO,EAAE,gBAAgB,EAAE,wBAAwB,EAAE,CAAC"}
1
+ {"version":3,"file":"index.d.cts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,gCAA+B;AAE1D,OAAO,EAAE,oBAAoB,EAAE,qCAAoC;AACnE,YAAY,EAAE,wBAAwB,EAAE,qCAAoC;AAE5E,+CAA8C;AAE9C;;GAEG;AACH,KAAK,wBAAwB,GAAG,gBAAgB,CAAC;AACjD,QAAA,MAAM,wBAAwB,yBAAmB,CAAC;AAElD,OAAO,EAAE,gBAAgB,EAAE,wBAAwB,EAAE,CAAC"}
package/dist/index.d.mts CHANGED
@@ -1,4 +1,6 @@
1
1
  import { InternalProvider } from "./internal-provider.mjs";
2
+ export { MockInternalProvider } from "./mock-internal-provider.mjs";
3
+ export type { MockInternalProviderStub } from "./mock-internal-provider.mjs";
2
4
  export * from "./provider-from-middleware.mjs";
3
5
  /**
4
6
  * @deprecated Use {@link InternalProvider} instead.
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,gCAA+B;AAE1D,+CAA8C;AAE9C;;GAEG;AACH,KAAK,wBAAwB,GAAG,gBAAgB,CAAC;AACjD,QAAA,MAAM,wBAAwB,yBAAmB,CAAC;AAElD,OAAO,EAAE,gBAAgB,EAAE,wBAAwB,EAAE,CAAC"}
1
+ {"version":3,"file":"index.d.mts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,gCAA+B;AAE1D,OAAO,EAAE,oBAAoB,EAAE,qCAAoC;AACnE,YAAY,EAAE,wBAAwB,EAAE,qCAAoC;AAE5E,+CAA8C;AAE9C;;GAEG;AACH,KAAK,wBAAwB,GAAG,gBAAgB,CAAC;AACjD,QAAA,MAAM,wBAAwB,yBAAmB,CAAC;AAElD,OAAO,EAAE,gBAAgB,EAAE,wBAAwB,EAAE,CAAC"}
package/dist/index.mjs CHANGED
@@ -1,4 +1,5 @@
1
1
  import { InternalProvider } from "./internal-provider.mjs";
2
+ export { MockInternalProvider } from "./mock-internal-provider.mjs";
2
3
  export * from "./provider-from-middleware.mjs";
3
4
  const SafeEventEmitterProvider = InternalProvider;
4
5
  export { InternalProvider, SafeEventEmitterProvider };
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,gCAA+B;AAE1D,+CAA8C;AAM9C,MAAM,wBAAwB,GAAG,gBAAgB,CAAC;AAElD,OAAO,EAAE,gBAAgB,EAAE,wBAAwB,EAAE,CAAC","sourcesContent":["import { InternalProvider } from './internal-provider.js';\n\nexport * from './provider-from-middleware.js';\n\n/**\n * @deprecated Use {@link InternalProvider} instead.\n */\ntype SafeEventEmitterProvider = InternalProvider;\nconst SafeEventEmitterProvider = InternalProvider;\n\nexport { InternalProvider, SafeEventEmitterProvider };\n"]}
1
+ {"version":3,"file":"index.mjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,gCAA+B;AAE1D,OAAO,EAAE,oBAAoB,EAAE,qCAAoC;AAGnE,+CAA8C;AAM9C,MAAM,wBAAwB,GAAG,gBAAgB,CAAC;AAElD,OAAO,EAAE,gBAAgB,EAAE,wBAAwB,EAAE,CAAC","sourcesContent":["import { InternalProvider } from './internal-provider.js';\n\nexport { MockInternalProvider } from './mock-internal-provider.js';\nexport type { MockInternalProviderStub } from './mock-internal-provider.js';\n\nexport * from './provider-from-middleware.js';\n\n/**\n * @deprecated Use {@link InternalProvider} instead.\n */\ntype SafeEventEmitterProvider = InternalProvider;\nconst SafeEventEmitterProvider = InternalProvider;\n\nexport { InternalProvider, SafeEventEmitterProvider };\n"]}
@@ -0,0 +1,172 @@
1
+ "use strict";
2
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
3
+ if (kind === "m") throw new TypeError("Private method is not writable");
4
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
5
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
6
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
7
+ };
8
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
9
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
10
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
11
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
12
+ };
13
+ var _MockInternalProvider_instances, _MockInternalProvider_originalStubs, _MockInternalProvider_stubs, _MockInternalProvider_handleSend, _MockInternalProvider_handleRequest;
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.MockInternalProvider = void 0;
16
+ const v2_1 = require("@metamask/json-rpc-engine/v2");
17
+ const utils_1 = require("@metamask/utils");
18
+ const lodash_1 = require("lodash");
19
+ const internal_provider_js_1 = require("./internal-provider.cjs");
20
+ // Store this in case it gets stubbed later
21
+ const originalSetTimeout = setTimeout;
22
+ /**
23
+ * An implementation of the provider that NetworkController exposes, which is
24
+ * actually an instance of InternalProvider (from the
25
+ * `@metamask/eth-json-rpc-provider` package). Hence it supports the same
26
+ * interface as InternalProvider, except that fake responses for any RPC
27
+ * methods that are accessed can be supplied via an API that is more succinct
28
+ * than using Jest's mocking API.
29
+ */
30
+ // NOTE: We shouldn't need to extend from the "real" provider here, but
31
+ // we'd need a `InternalProvider` _interface_ and that doesn't exist (at
32
+ // least not yet).
33
+ class MockInternalProvider extends internal_provider_js_1.InternalProvider {
34
+ /**
35
+ * Makes a new instance of the fake provider.
36
+ *
37
+ * @param options - The options.
38
+ * @param options.stubs - A set of objects that allow specifying the behavior
39
+ * of specific invocations of `request` matching a `method`.
40
+ */
41
+ constructor({ stubs = [] } = {}) {
42
+ super({
43
+ engine: v2_1.JsonRpcEngineV2.create({
44
+ middleware: [
45
+ () => {
46
+ throw new Error('MockInternalProvider received unstubbed method call');
47
+ },
48
+ ],
49
+ }),
50
+ });
51
+ _MockInternalProvider_instances.add(this);
52
+ _MockInternalProvider_originalStubs.set(this, void 0);
53
+ _MockInternalProvider_stubs.set(this, void 0);
54
+ this.request = (payload) => {
55
+ return new Promise((resolve, reject) => {
56
+ __classPrivateFieldGet(this, _MockInternalProvider_instances, "m", _MockInternalProvider_handleSend).call(this, payload, (error, providerRes) => {
57
+ if (error) {
58
+ // Error is `unknown`.
59
+ // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors
60
+ reject(error);
61
+ }
62
+ else {
63
+ resolve(providerRes.result);
64
+ }
65
+ });
66
+ });
67
+ };
68
+ this.sendAsync = (payload,
69
+ // This is copied from the implementation for InternalProvider.
70
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
71
+ callback) => {
72
+ return __classPrivateFieldGet(this, _MockInternalProvider_instances, "m", _MockInternalProvider_handleSend).call(this, payload, callback);
73
+ };
74
+ this.send = (req,
75
+ // This is copied from the implementation for InternalProvider.
76
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
77
+ callback) => {
78
+ return __classPrivateFieldGet(this, _MockInternalProvider_instances, "m", _MockInternalProvider_handleSend).call(this, req, callback);
79
+ };
80
+ __classPrivateFieldSet(this, _MockInternalProvider_originalStubs, stubs, "f");
81
+ __classPrivateFieldSet(this, _MockInternalProvider_stubs, __classPrivateFieldGet(this, _MockInternalProvider_originalStubs, "f").slice(), "f");
82
+ this.calledStubs = [];
83
+ }
84
+ }
85
+ exports.MockInternalProvider = MockInternalProvider;
86
+ _MockInternalProvider_originalStubs = new WeakMap(), _MockInternalProvider_stubs = new WeakMap(), _MockInternalProvider_instances = new WeakSet(), _MockInternalProvider_handleSend = function _MockInternalProvider_handleSend(req,
87
+ // This is copied from the implementation for InternalProvider.
88
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
89
+ callback) {
90
+ if (Array.isArray(req)) {
91
+ throw new Error("Arrays aren't supported");
92
+ }
93
+ const index = __classPrivateFieldGet(this, _MockInternalProvider_stubs, "f").findIndex((stub) => {
94
+ return (stub.request.method === req.method &&
95
+ (!(0, utils_1.hasProperty)(stub.request, 'params') ||
96
+ (0, lodash_1.isEqual)(stub.request.params, req.params)));
97
+ });
98
+ if (index === -1) {
99
+ const matchingCalledStubs = this.calledStubs.filter((stub) => {
100
+ return (stub.request.method === req.method &&
101
+ (!(0, utils_1.hasProperty)(stub.request, 'params') ||
102
+ (0, lodash_1.isEqual)(stub.request.params, req.params)));
103
+ });
104
+ let message = `Could not find any stubs matching: ${JSON.stringify(req)}`;
105
+ if (matchingCalledStubs.length > 0) {
106
+ message += `\n\nIt appears the following stubs were defined, but have been called already:\n\n${JSON.stringify(matchingCalledStubs)}`;
107
+ }
108
+ throw new Error(message);
109
+ }
110
+ else {
111
+ // We just verified that we can find this index.
112
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
113
+ const stub = __classPrivateFieldGet(this, _MockInternalProvider_stubs, "f")[index];
114
+ if (stub.discardAfterMatching !== false) {
115
+ __classPrivateFieldGet(this, _MockInternalProvider_stubs, "f").splice(index, 1);
116
+ }
117
+ if (stub.delay) {
118
+ originalSetTimeout(() => {
119
+ // TODO: Either fix this lint violation or explain why it's necessary to ignore.
120
+ // eslint-disable-next-line @typescript-eslint/no-floating-promises
121
+ __classPrivateFieldGet(this, _MockInternalProvider_instances, "m", _MockInternalProvider_handleRequest).call(this, stub, callback);
122
+ }, stub.delay);
123
+ }
124
+ else {
125
+ // TODO: Either fix this lint violation or explain why it's necessary to ignore.
126
+ // eslint-disable-next-line @typescript-eslint/no-floating-promises
127
+ __classPrivateFieldGet(this, _MockInternalProvider_instances, "m", _MockInternalProvider_handleRequest).call(this, stub, callback);
128
+ }
129
+ this.calledStubs.push({ ...stub });
130
+ }
131
+ }, _MockInternalProvider_handleRequest = async function _MockInternalProvider_handleRequest(stub, callback) {
132
+ if (stub.beforeCompleting) {
133
+ await stub.beforeCompleting();
134
+ }
135
+ // We need to narrow the type.
136
+ // eslint-disable-next-line no-restricted-syntax
137
+ if ('implementation' in stub) {
138
+ stub.implementation();
139
+ // We need to narrow the type.
140
+ // eslint-disable-next-line no-restricted-syntax
141
+ }
142
+ else if ('response' in stub) {
143
+ // We need to narrow the type.
144
+ // eslint-disable-next-line no-restricted-syntax
145
+ if ('result' in stub.response) {
146
+ return callback(null, {
147
+ jsonrpc: '2.0',
148
+ id: 1,
149
+ result: stub.response.result,
150
+ });
151
+ // We need to narrow the type.
152
+ // eslint-disable-next-line no-restricted-syntax
153
+ }
154
+ else if ('error' in stub.response) {
155
+ return callback(null, {
156
+ jsonrpc: '2.0',
157
+ id: 1,
158
+ error: {
159
+ code: -999,
160
+ message: stub.response.error,
161
+ },
162
+ });
163
+ }
164
+ // We need to narrow the type.
165
+ // eslint-disable-next-line no-restricted-syntax
166
+ }
167
+ else if ('error' in stub) {
168
+ return callback(stub.error);
169
+ }
170
+ return undefined;
171
+ };
172
+ //# sourceMappingURL=mock-internal-provider.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mock-internal-provider.cjs","sourceRoot":"","sources":["../src/mock-internal-provider.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,qDAA+D;AAM/D,2CAA8C;AAS9C,mCAAiC;AAEjC,kEAA0D;AAE1D,2CAA2C;AAC3C,MAAM,kBAAkB,GAAG,UAAU,CAAC;AA0FtC;;;;;;;GAOG;AACH,uEAAuE;AACvE,wEAAwE;AACxE,kBAAkB;AAClB,MAAa,oBAAqB,SAAQ,uCAAyB;IAOjE;;;;;;OAMG;IAC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,EAAE,CAAC;YAC9B,OAAO,QAAQ,CAAC,IAAI,EAAE;gBACpB,OAAO,EAAE,KAAK;gBACd,EAAE,EAAE,CAAC;gBACL,MAAM,EAAE,IAAI,CAAC,QAAQ,CAAC,MAAM;aAC7B,CAAC,CAAC;YACH,8BAA8B;YAC9B,gDAAgD;QAClD,CAAC;aAAM,IAAI,OAAO,IAAI,IAAI,CAAC,QAAQ,EAAE,CAAC;YACpC,OAAO,QAAQ,CAAC,IAAI,EAAE;gBACpB,OAAO,EAAE,KAAK;gBACd,EAAE,EAAE,CAAC;gBACL,KAAK,EAAE;oBACL,IAAI,EAAE,CAAC,GAAG;oBACV,OAAO,EAAE,IAAI,CAAC,QAAQ,CAAC,KAAK;iBAC7B;aACF,CAAC,CAAC;QACL,CAAC;QACD,8BAA8B;QAC9B,gDAAgD;IAClD,CAAC;SAAM,IAAI,OAAO,IAAI,IAAI,EAAE,CAAC;QAC3B,OAAO,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IAC9B,CAAC;IAED,OAAO,SAAS,CAAC;AACnB,CAAC","sourcesContent":["import { JsonRpcEngineV2 } from '@metamask/json-rpc-engine/v2';\nimport type {\n JsonRpcMiddleware,\n MiddlewareContext,\n ResultConstraint,\n} from '@metamask/json-rpc-engine/v2';\nimport { hasProperty } from '@metamask/utils';\nimport type {\n Json,\n JsonRpcId,\n JsonRpcParams,\n JsonRpcRequest,\n JsonRpcResponse,\n JsonRpcVersion2,\n} from '@metamask/utils';\nimport { isEqual } from 'lodash';\n\nimport { InternalProvider } from './internal-provider.js';\n\n// Store this in case it gets stubbed later\nconst originalSetTimeout = setTimeout;\n\n/**\n * A JSON-RPC request conforming to the EIP-1193 specification.\n */\ntype Eip1193Request<Params extends JsonRpcParams> = {\n id?: JsonRpcId;\n jsonrpc?: JsonRpcVersion2;\n method: string;\n params?: Params;\n};\n\n/**\n * Represents the type of the `response` property in a fake provider stub.\n */\n// TODO: Replace `any` with type\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type MockInternalProviderResponse = { result: any } | { error: string };\n\n/**\n * An object that allows specifying the behavior of a specific invocation of\n * `request`. The `method` always identifies the stub, but the behavior\n * may be specified multiple ways: `request` can either return a promise or\n * throw an error, and if it returns a promise, that promise can either be\n * resolved with a response object or reject with an error.\n *\n * @property request - Looks for a request matching these specifications.\n * @property request.method - The RPC method to which this stub will be matched.\n * @property request.params - The params to which this stub will be matched.\n * @property response - Instructs `request` to return a promise that resolves\n * with a response object.\n * @property response.result - Specifies a successful response, with this as the\n * `result`.\n * @property response.error - Specifies an error response, with this as the\n * `error`.\n * @property error - Instructs `request` to return a promise that rejects with\n * this error.\n * @property implementation - Allows overriding `request` entirely. Useful if\n * you want it to throw an error.\n * @property delay - The amount of time that will pass after the callback is\n * called with the response.\n * @property discardAfterMatching - Usually after the stub matches a request, it\n * is discarded, but setting this to true prevents that from happening. True by\n * default.\n * @property beforeCompleting - Sometimes it is useful to do something after the\n * request is kicked off but before it ends (or, in terms of a `fetch` promise,\n * when the promise is initiated but before it is resolved). You can pass an\n * (async) function for this option to do this.\n */\nexport type MockInternalProviderStub = {\n request: {\n method: string;\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n params?: any[];\n };\n delay?: number;\n discardAfterMatching?: boolean;\n beforeCompleting?: () => void | Promise<void>;\n} & (\n | {\n response: MockInternalProviderResponse;\n }\n | {\n error: unknown;\n }\n | {\n implementation: () => void;\n }\n);\n\n/**\n * The set of options that the MockInternalProvider constructor takes.\n *\n * @property stubs - A set of objects that allow specifying the behavior\n * of specific invocations of `request` matching a `method`.\n */\ntype MockInternalProviderEngineOptions = {\n stubs?: MockInternalProviderStub[];\n};\n\ntype Context = MiddlewareContext<\n { origin: string; skipCache: boolean } & Record<string, unknown>\n>;\ntype Middleware = JsonRpcMiddleware<\n JsonRpcRequest,\n ResultConstraint<JsonRpcRequest>,\n Context\n>;\n\n/**\n * An implementation of the provider that NetworkController exposes, which is\n * actually an instance of InternalProvider (from the\n * `@metamask/eth-json-rpc-provider` package). Hence it supports the same\n * interface as InternalProvider, except that fake responses for any RPC\n * methods that are accessed can be supplied via an API that is more succinct\n * than using Jest's mocking API.\n */\n// NOTE: We shouldn't need to extend from the \"real\" provider here, but\n// we'd need a `InternalProvider` _interface_ and that doesn't exist (at\n// least not yet).\nexport class MockInternalProvider extends InternalProvider<Context> {\n calledStubs: MockInternalProviderStub[];\n\n readonly #originalStubs: MockInternalProviderStub[];\n\n readonly #stubs: MockInternalProviderStub[];\n\n /**\n * Makes a new instance of the fake provider.\n *\n * @param options - The options.\n * @param options.stubs - A set of objects that allow specifying the behavior\n * of specific invocations of `request` matching a `method`.\n */\n constructor({ stubs = [] }: MockInternalProviderEngineOptions = {}) {\n super({\n engine: JsonRpcEngineV2.create<Middleware>({\n middleware: [\n (): never => {\n throw new Error(\n 'MockInternalProvider received unstubbed method call',\n );\n },\n ],\n }),\n });\n this.#originalStubs = stubs;\n this.#stubs = this.#originalStubs.slice();\n this.calledStubs = [];\n }\n\n request = <Params extends JsonRpcParams, Result extends Json>(\n payload: Eip1193Request<Params>,\n ): Promise<Result> => {\n return new Promise((resolve, reject) => {\n this.#handleSend(payload, (error, providerRes) => {\n if (error) {\n // Error is `unknown`.\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors\n reject(error);\n } else {\n resolve(providerRes.result);\n }\n });\n });\n };\n\n sendAsync = <Params extends JsonRpcParams>(\n payload: Eip1193Request<Params>,\n // This is copied from the implementation for InternalProvider.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n callback: (error: unknown, providerRes?: any) => void,\n ): void => {\n return this.#handleSend(payload, callback);\n };\n\n send = <Params extends JsonRpcParams>(\n req: Eip1193Request<Params>,\n // This is copied from the implementation for InternalProvider.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n callback: (error: unknown, providerRes?: any) => void,\n ): void => {\n return this.#handleSend(req, callback);\n };\n\n #handleSend<Params extends JsonRpcParams>(\n req: Eip1193Request<Params>,\n // This is copied from the implementation for InternalProvider.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n callback: (error: unknown, providerRes?: any) => void,\n ): void {\n if (Array.isArray(req)) {\n throw new Error(\"Arrays aren't supported\");\n }\n\n const index = this.#stubs.findIndex((stub) => {\n return (\n stub.request.method === req.method &&\n (!hasProperty(stub.request, 'params') ||\n isEqual(stub.request.params, req.params))\n );\n });\n\n if (index === -1) {\n const matchingCalledStubs = this.calledStubs.filter((stub) => {\n return (\n stub.request.method === req.method &&\n (!hasProperty(stub.request, 'params') ||\n isEqual(stub.request.params, req.params))\n );\n });\n let message = `Could not find any stubs matching: ${JSON.stringify(req)}`;\n if (matchingCalledStubs.length > 0) {\n message += `\\n\\nIt appears the following stubs were defined, but have been called already:\\n\\n${JSON.stringify(\n matchingCalledStubs,\n )}`;\n }\n\n throw new Error(message);\n } else {\n // We just verified that we can find this index.\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const stub = this.#stubs[index]!;\n\n if (stub.discardAfterMatching !== false) {\n this.#stubs.splice(index, 1);\n }\n\n if (stub.delay) {\n originalSetTimeout(() => {\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.#handleRequest(stub, callback);\n }, stub.delay);\n } else {\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.#handleRequest(stub, callback);\n }\n\n this.calledStubs.push({ ...stub });\n }\n }\n\n async #handleRequest(\n stub: MockInternalProviderStub,\n callback: (error: unknown, response?: JsonRpcResponse) => void,\n ): Promise<void> {\n if (stub.beforeCompleting) {\n await stub.beforeCompleting();\n }\n\n // We need to narrow the type.\n // eslint-disable-next-line no-restricted-syntax\n if ('implementation' in stub) {\n stub.implementation();\n // We need to narrow the type.\n // eslint-disable-next-line no-restricted-syntax\n } else if ('response' in stub) {\n // We need to narrow the type.\n // eslint-disable-next-line no-restricted-syntax\n if ('result' in stub.response) {\n return callback(null, {\n jsonrpc: '2.0',\n id: 1,\n result: stub.response.result,\n });\n // We need to narrow the type.\n // eslint-disable-next-line no-restricted-syntax\n } else if ('error' in stub.response) {\n return callback(null, {\n jsonrpc: '2.0',\n id: 1,\n error: {\n code: -999,\n message: stub.response.error,\n },\n });\n }\n // We need to narrow the type.\n // eslint-disable-next-line no-restricted-syntax\n } else if ('error' in stub) {\n return callback(stub.error);\n }\n\n return undefined;\n }\n}\n"]}
@@ -0,0 +1,103 @@
1
+ import type { MiddlewareContext } from "@metamask/json-rpc-engine/v2";
2
+ import type { Json, JsonRpcId, JsonRpcParams, JsonRpcVersion2 } from "@metamask/utils";
3
+ import { InternalProvider } from "./internal-provider.cjs";
4
+ /**
5
+ * A JSON-RPC request conforming to the EIP-1193 specification.
6
+ */
7
+ type Eip1193Request<Params extends JsonRpcParams> = {
8
+ id?: JsonRpcId;
9
+ jsonrpc?: JsonRpcVersion2;
10
+ method: string;
11
+ params?: Params;
12
+ };
13
+ /**
14
+ * Represents the type of the `response` property in a fake provider stub.
15
+ */
16
+ export type MockInternalProviderResponse = {
17
+ result: any;
18
+ } | {
19
+ error: string;
20
+ };
21
+ /**
22
+ * An object that allows specifying the behavior of a specific invocation of
23
+ * `request`. The `method` always identifies the stub, but the behavior
24
+ * may be specified multiple ways: `request` can either return a promise or
25
+ * throw an error, and if it returns a promise, that promise can either be
26
+ * resolved with a response object or reject with an error.
27
+ *
28
+ * @property request - Looks for a request matching these specifications.
29
+ * @property request.method - The RPC method to which this stub will be matched.
30
+ * @property request.params - The params to which this stub will be matched.
31
+ * @property response - Instructs `request` to return a promise that resolves
32
+ * with a response object.
33
+ * @property response.result - Specifies a successful response, with this as the
34
+ * `result`.
35
+ * @property response.error - Specifies an error response, with this as the
36
+ * `error`.
37
+ * @property error - Instructs `request` to return a promise that rejects with
38
+ * this error.
39
+ * @property implementation - Allows overriding `request` entirely. Useful if
40
+ * you want it to throw an error.
41
+ * @property delay - The amount of time that will pass after the callback is
42
+ * called with the response.
43
+ * @property discardAfterMatching - Usually after the stub matches a request, it
44
+ * is discarded, but setting this to true prevents that from happening. True by
45
+ * default.
46
+ * @property beforeCompleting - Sometimes it is useful to do something after the
47
+ * request is kicked off but before it ends (or, in terms of a `fetch` promise,
48
+ * when the promise is initiated but before it is resolved). You can pass an
49
+ * (async) function for this option to do this.
50
+ */
51
+ export type MockInternalProviderStub = {
52
+ request: {
53
+ method: string;
54
+ params?: any[];
55
+ };
56
+ delay?: number;
57
+ discardAfterMatching?: boolean;
58
+ beforeCompleting?: () => void | Promise<void>;
59
+ } & ({
60
+ response: MockInternalProviderResponse;
61
+ } | {
62
+ error: unknown;
63
+ } | {
64
+ implementation: () => void;
65
+ });
66
+ /**
67
+ * The set of options that the MockInternalProvider constructor takes.
68
+ *
69
+ * @property stubs - A set of objects that allow specifying the behavior
70
+ * of specific invocations of `request` matching a `method`.
71
+ */
72
+ type MockInternalProviderEngineOptions = {
73
+ stubs?: MockInternalProviderStub[];
74
+ };
75
+ type Context = MiddlewareContext<{
76
+ origin: string;
77
+ skipCache: boolean;
78
+ } & Record<string, unknown>>;
79
+ /**
80
+ * An implementation of the provider that NetworkController exposes, which is
81
+ * actually an instance of InternalProvider (from the
82
+ * `@metamask/eth-json-rpc-provider` package). Hence it supports the same
83
+ * interface as InternalProvider, except that fake responses for any RPC
84
+ * methods that are accessed can be supplied via an API that is more succinct
85
+ * than using Jest's mocking API.
86
+ */
87
+ export declare class MockInternalProvider extends InternalProvider<Context> {
88
+ #private;
89
+ calledStubs: MockInternalProviderStub[];
90
+ /**
91
+ * Makes a new instance of the fake provider.
92
+ *
93
+ * @param options - The options.
94
+ * @param options.stubs - A set of objects that allow specifying the behavior
95
+ * of specific invocations of `request` matching a `method`.
96
+ */
97
+ constructor({ stubs }?: MockInternalProviderEngineOptions);
98
+ request: <Params extends JsonRpcParams, Result extends Json>(payload: Eip1193Request<Params>) => Promise<Result>;
99
+ sendAsync: <Params extends JsonRpcParams>(payload: Eip1193Request<Params>, callback: (error: unknown, providerRes?: any) => void) => void;
100
+ send: <Params extends JsonRpcParams>(req: Eip1193Request<Params>, callback: (error: unknown, providerRes?: any) => void) => void;
101
+ }
102
+ export {};
103
+ //# sourceMappingURL=mock-internal-provider.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mock-internal-provider.d.cts","sourceRoot":"","sources":["../src/mock-internal-provider.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAEV,iBAAiB,EAElB,qCAAqC;AAEtC,OAAO,KAAK,EACV,IAAI,EACJ,SAAS,EACT,aAAa,EAGb,eAAe,EAChB,wBAAwB;AAGzB,OAAO,EAAE,gBAAgB,EAAE,gCAA+B;AAK1D;;GAEG;AACH,KAAK,cAAc,CAAC,MAAM,SAAS,aAAa,IAAI;IAClD,EAAE,CAAC,EAAE,SAAS,CAAC;IACf,OAAO,CAAC,EAAE,eAAe,CAAC;IAC1B,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB,CAAC;AAEF;;GAEG;AAGH,MAAM,MAAM,4BAA4B,GAAG;IAAE,MAAM,EAAE,GAAG,CAAA;CAAE,GAAG;IAAE,KAAK,EAAE,MAAM,CAAA;CAAE,CAAC;AAE/E;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AACH,MAAM,MAAM,wBAAwB,GAAG;IACrC,OAAO,EAAE;QACP,MAAM,EAAE,MAAM,CAAC;QAGf,MAAM,CAAC,EAAE,GAAG,EAAE,CAAC;KAChB,CAAC;IACF,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,oBAAoB,CAAC,EAAE,OAAO,CAAC;IAC/B,gBAAgB,CAAC,EAAE,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CAC/C,GAAG,CACA;IACE,QAAQ,EAAE,4BAA4B,CAAC;CACxC,GACD;IACE,KAAK,EAAE,OAAO,CAAC;CAChB,GACD;IACE,cAAc,EAAE,MAAM,IAAI,CAAC;CAC5B,CACJ,CAAC;AAEF;;;;;GAKG;AACH,KAAK,iCAAiC,GAAG;IACvC,KAAK,CAAC,EAAE,wBAAwB,EAAE,CAAC;CACpC,CAAC;AAEF,KAAK,OAAO,GAAG,iBAAiB,CAC9B;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,OAAO,CAAA;CAAE,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CACjE,CAAC;AAOF;;;;;;;GAOG;AAIH,qBAAa,oBAAqB,SAAQ,gBAAgB,CAAC,OAAO,CAAC;;IACjE,WAAW,EAAE,wBAAwB,EAAE,CAAC;IAMxC;;;;;;OAMG;gBACS,EAAE,KAAU,EAAE,GAAE,iCAAsC;IAiBlE,OAAO,0GAcL;IAEF,SAAS,oFAIW,OAAO,gBAAgB,GAAG,KAAK,IAAI,KACpD,IAAI,CAEL;IAEF,IAAI,gFAIgB,OAAO,gBAAgB,GAAG,KAAK,IAAI,KACpD,IAAI,CAEL;CAwGH"}
@@ -0,0 +1,103 @@
1
+ import type { MiddlewareContext } from "@metamask/json-rpc-engine/v2";
2
+ import type { Json, JsonRpcId, JsonRpcParams, JsonRpcVersion2 } from "@metamask/utils";
3
+ import { InternalProvider } from "./internal-provider.mjs";
4
+ /**
5
+ * A JSON-RPC request conforming to the EIP-1193 specification.
6
+ */
7
+ type Eip1193Request<Params extends JsonRpcParams> = {
8
+ id?: JsonRpcId;
9
+ jsonrpc?: JsonRpcVersion2;
10
+ method: string;
11
+ params?: Params;
12
+ };
13
+ /**
14
+ * Represents the type of the `response` property in a fake provider stub.
15
+ */
16
+ export type MockInternalProviderResponse = {
17
+ result: any;
18
+ } | {
19
+ error: string;
20
+ };
21
+ /**
22
+ * An object that allows specifying the behavior of a specific invocation of
23
+ * `request`. The `method` always identifies the stub, but the behavior
24
+ * may be specified multiple ways: `request` can either return a promise or
25
+ * throw an error, and if it returns a promise, that promise can either be
26
+ * resolved with a response object or reject with an error.
27
+ *
28
+ * @property request - Looks for a request matching these specifications.
29
+ * @property request.method - The RPC method to which this stub will be matched.
30
+ * @property request.params - The params to which this stub will be matched.
31
+ * @property response - Instructs `request` to return a promise that resolves
32
+ * with a response object.
33
+ * @property response.result - Specifies a successful response, with this as the
34
+ * `result`.
35
+ * @property response.error - Specifies an error response, with this as the
36
+ * `error`.
37
+ * @property error - Instructs `request` to return a promise that rejects with
38
+ * this error.
39
+ * @property implementation - Allows overriding `request` entirely. Useful if
40
+ * you want it to throw an error.
41
+ * @property delay - The amount of time that will pass after the callback is
42
+ * called with the response.
43
+ * @property discardAfterMatching - Usually after the stub matches a request, it
44
+ * is discarded, but setting this to true prevents that from happening. True by
45
+ * default.
46
+ * @property beforeCompleting - Sometimes it is useful to do something after the
47
+ * request is kicked off but before it ends (or, in terms of a `fetch` promise,
48
+ * when the promise is initiated but before it is resolved). You can pass an
49
+ * (async) function for this option to do this.
50
+ */
51
+ export type MockInternalProviderStub = {
52
+ request: {
53
+ method: string;
54
+ params?: any[];
55
+ };
56
+ delay?: number;
57
+ discardAfterMatching?: boolean;
58
+ beforeCompleting?: () => void | Promise<void>;
59
+ } & ({
60
+ response: MockInternalProviderResponse;
61
+ } | {
62
+ error: unknown;
63
+ } | {
64
+ implementation: () => void;
65
+ });
66
+ /**
67
+ * The set of options that the MockInternalProvider constructor takes.
68
+ *
69
+ * @property stubs - A set of objects that allow specifying the behavior
70
+ * of specific invocations of `request` matching a `method`.
71
+ */
72
+ type MockInternalProviderEngineOptions = {
73
+ stubs?: MockInternalProviderStub[];
74
+ };
75
+ type Context = MiddlewareContext<{
76
+ origin: string;
77
+ skipCache: boolean;
78
+ } & Record<string, unknown>>;
79
+ /**
80
+ * An implementation of the provider that NetworkController exposes, which is
81
+ * actually an instance of InternalProvider (from the
82
+ * `@metamask/eth-json-rpc-provider` package). Hence it supports the same
83
+ * interface as InternalProvider, except that fake responses for any RPC
84
+ * methods that are accessed can be supplied via an API that is more succinct
85
+ * than using Jest's mocking API.
86
+ */
87
+ export declare class MockInternalProvider extends InternalProvider<Context> {
88
+ #private;
89
+ calledStubs: MockInternalProviderStub[];
90
+ /**
91
+ * Makes a new instance of the fake provider.
92
+ *
93
+ * @param options - The options.
94
+ * @param options.stubs - A set of objects that allow specifying the behavior
95
+ * of specific invocations of `request` matching a `method`.
96
+ */
97
+ constructor({ stubs }?: MockInternalProviderEngineOptions);
98
+ request: <Params extends JsonRpcParams, Result extends Json>(payload: Eip1193Request<Params>) => Promise<Result>;
99
+ sendAsync: <Params extends JsonRpcParams>(payload: Eip1193Request<Params>, callback: (error: unknown, providerRes?: any) => void) => void;
100
+ send: <Params extends JsonRpcParams>(req: Eip1193Request<Params>, callback: (error: unknown, providerRes?: any) => void) => void;
101
+ }
102
+ export {};
103
+ //# sourceMappingURL=mock-internal-provider.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mock-internal-provider.d.mts","sourceRoot":"","sources":["../src/mock-internal-provider.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAEV,iBAAiB,EAElB,qCAAqC;AAEtC,OAAO,KAAK,EACV,IAAI,EACJ,SAAS,EACT,aAAa,EAGb,eAAe,EAChB,wBAAwB;AAGzB,OAAO,EAAE,gBAAgB,EAAE,gCAA+B;AAK1D;;GAEG;AACH,KAAK,cAAc,CAAC,MAAM,SAAS,aAAa,IAAI;IAClD,EAAE,CAAC,EAAE,SAAS,CAAC;IACf,OAAO,CAAC,EAAE,eAAe,CAAC;IAC1B,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB,CAAC;AAEF;;GAEG;AAGH,MAAM,MAAM,4BAA4B,GAAG;IAAE,MAAM,EAAE,GAAG,CAAA;CAAE,GAAG;IAAE,KAAK,EAAE,MAAM,CAAA;CAAE,CAAC;AAE/E;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AACH,MAAM,MAAM,wBAAwB,GAAG;IACrC,OAAO,EAAE;QACP,MAAM,EAAE,MAAM,CAAC;QAGf,MAAM,CAAC,EAAE,GAAG,EAAE,CAAC;KAChB,CAAC;IACF,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,oBAAoB,CAAC,EAAE,OAAO,CAAC;IAC/B,gBAAgB,CAAC,EAAE,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CAC/C,GAAG,CACA;IACE,QAAQ,EAAE,4BAA4B,CAAC;CACxC,GACD;IACE,KAAK,EAAE,OAAO,CAAC;CAChB,GACD;IACE,cAAc,EAAE,MAAM,IAAI,CAAC;CAC5B,CACJ,CAAC;AAEF;;;;;GAKG;AACH,KAAK,iCAAiC,GAAG;IACvC,KAAK,CAAC,EAAE,wBAAwB,EAAE,CAAC;CACpC,CAAC;AAEF,KAAK,OAAO,GAAG,iBAAiB,CAC9B;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,OAAO,CAAA;CAAE,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CACjE,CAAC;AAOF;;;;;;;GAOG;AAIH,qBAAa,oBAAqB,SAAQ,gBAAgB,CAAC,OAAO,CAAC;;IACjE,WAAW,EAAE,wBAAwB,EAAE,CAAC;IAMxC;;;;;;OAMG;gBACS,EAAE,KAAU,EAAE,GAAE,iCAAsC;IAiBlE,OAAO,0GAcL;IAEF,SAAS,oFAIW,OAAO,gBAAgB,GAAG,KAAK,IAAI,KACpD,IAAI,CAEL;IAEF,IAAI,gFAIgB,OAAO,gBAAgB,GAAG,KAAK,IAAI,KACpD,IAAI,CAEL;CAwGH"}
@@ -0,0 +1,169 @@
1
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
2
+ if (kind === "m") throw new TypeError("Private method is not writable");
3
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
4
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
5
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
6
+ };
7
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
8
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
9
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
10
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
+ };
12
+ var _MockInternalProvider_instances, _MockInternalProvider_originalStubs, _MockInternalProvider_stubs, _MockInternalProvider_handleSend, _MockInternalProvider_handleRequest;
13
+ import { JsonRpcEngineV2 } from "@metamask/json-rpc-engine/v2";
14
+ import { hasProperty } from "@metamask/utils";
15
+ import $lodash from "lodash";
16
+ const { isEqual } = $lodash;
17
+ import { InternalProvider } from "./internal-provider.mjs";
18
+ // Store this in case it gets stubbed later
19
+ const originalSetTimeout = setTimeout;
20
+ /**
21
+ * An implementation of the provider that NetworkController exposes, which is
22
+ * actually an instance of InternalProvider (from the
23
+ * `@metamask/eth-json-rpc-provider` package). Hence it supports the same
24
+ * interface as InternalProvider, except that fake responses for any RPC
25
+ * methods that are accessed can be supplied via an API that is more succinct
26
+ * than using Jest's mocking API.
27
+ */
28
+ // NOTE: We shouldn't need to extend from the "real" provider here, but
29
+ // we'd need a `InternalProvider` _interface_ and that doesn't exist (at
30
+ // least not yet).
31
+ export class MockInternalProvider extends InternalProvider {
32
+ /**
33
+ * Makes a new instance of the fake provider.
34
+ *
35
+ * @param options - The options.
36
+ * @param options.stubs - A set of objects that allow specifying the behavior
37
+ * of specific invocations of `request` matching a `method`.
38
+ */
39
+ constructor({ stubs = [] } = {}) {
40
+ super({
41
+ engine: JsonRpcEngineV2.create({
42
+ middleware: [
43
+ () => {
44
+ throw new Error('MockInternalProvider received unstubbed method call');
45
+ },
46
+ ],
47
+ }),
48
+ });
49
+ _MockInternalProvider_instances.add(this);
50
+ _MockInternalProvider_originalStubs.set(this, void 0);
51
+ _MockInternalProvider_stubs.set(this, void 0);
52
+ this.request = (payload) => {
53
+ return new Promise((resolve, reject) => {
54
+ __classPrivateFieldGet(this, _MockInternalProvider_instances, "m", _MockInternalProvider_handleSend).call(this, payload, (error, providerRes) => {
55
+ if (error) {
56
+ // Error is `unknown`.
57
+ // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors
58
+ reject(error);
59
+ }
60
+ else {
61
+ resolve(providerRes.result);
62
+ }
63
+ });
64
+ });
65
+ };
66
+ this.sendAsync = (payload,
67
+ // This is copied from the implementation for InternalProvider.
68
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
69
+ callback) => {
70
+ return __classPrivateFieldGet(this, _MockInternalProvider_instances, "m", _MockInternalProvider_handleSend).call(this, payload, callback);
71
+ };
72
+ this.send = (req,
73
+ // This is copied from the implementation for InternalProvider.
74
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
75
+ callback) => {
76
+ return __classPrivateFieldGet(this, _MockInternalProvider_instances, "m", _MockInternalProvider_handleSend).call(this, req, callback);
77
+ };
78
+ __classPrivateFieldSet(this, _MockInternalProvider_originalStubs, stubs, "f");
79
+ __classPrivateFieldSet(this, _MockInternalProvider_stubs, __classPrivateFieldGet(this, _MockInternalProvider_originalStubs, "f").slice(), "f");
80
+ this.calledStubs = [];
81
+ }
82
+ }
83
+ _MockInternalProvider_originalStubs = new WeakMap(), _MockInternalProvider_stubs = new WeakMap(), _MockInternalProvider_instances = new WeakSet(), _MockInternalProvider_handleSend = function _MockInternalProvider_handleSend(req,
84
+ // This is copied from the implementation for InternalProvider.
85
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
86
+ callback) {
87
+ if (Array.isArray(req)) {
88
+ throw new Error("Arrays aren't supported");
89
+ }
90
+ const index = __classPrivateFieldGet(this, _MockInternalProvider_stubs, "f").findIndex((stub) => {
91
+ return (stub.request.method === req.method &&
92
+ (!hasProperty(stub.request, 'params') ||
93
+ isEqual(stub.request.params, req.params)));
94
+ });
95
+ if (index === -1) {
96
+ const matchingCalledStubs = this.calledStubs.filter((stub) => {
97
+ return (stub.request.method === req.method &&
98
+ (!hasProperty(stub.request, 'params') ||
99
+ isEqual(stub.request.params, req.params)));
100
+ });
101
+ let message = `Could not find any stubs matching: ${JSON.stringify(req)}`;
102
+ if (matchingCalledStubs.length > 0) {
103
+ message += `\n\nIt appears the following stubs were defined, but have been called already:\n\n${JSON.stringify(matchingCalledStubs)}`;
104
+ }
105
+ throw new Error(message);
106
+ }
107
+ else {
108
+ // We just verified that we can find this index.
109
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
110
+ const stub = __classPrivateFieldGet(this, _MockInternalProvider_stubs, "f")[index];
111
+ if (stub.discardAfterMatching !== false) {
112
+ __classPrivateFieldGet(this, _MockInternalProvider_stubs, "f").splice(index, 1);
113
+ }
114
+ if (stub.delay) {
115
+ originalSetTimeout(() => {
116
+ // TODO: Either fix this lint violation or explain why it's necessary to ignore.
117
+ // eslint-disable-next-line @typescript-eslint/no-floating-promises
118
+ __classPrivateFieldGet(this, _MockInternalProvider_instances, "m", _MockInternalProvider_handleRequest).call(this, stub, callback);
119
+ }, stub.delay);
120
+ }
121
+ else {
122
+ // TODO: Either fix this lint violation or explain why it's necessary to ignore.
123
+ // eslint-disable-next-line @typescript-eslint/no-floating-promises
124
+ __classPrivateFieldGet(this, _MockInternalProvider_instances, "m", _MockInternalProvider_handleRequest).call(this, stub, callback);
125
+ }
126
+ this.calledStubs.push({ ...stub });
127
+ }
128
+ }, _MockInternalProvider_handleRequest = async function _MockInternalProvider_handleRequest(stub, callback) {
129
+ if (stub.beforeCompleting) {
130
+ await stub.beforeCompleting();
131
+ }
132
+ // We need to narrow the type.
133
+ // eslint-disable-next-line no-restricted-syntax
134
+ if ('implementation' in stub) {
135
+ stub.implementation();
136
+ // We need to narrow the type.
137
+ // eslint-disable-next-line no-restricted-syntax
138
+ }
139
+ else if ('response' in stub) {
140
+ // We need to narrow the type.
141
+ // eslint-disable-next-line no-restricted-syntax
142
+ if ('result' in stub.response) {
143
+ return callback(null, {
144
+ jsonrpc: '2.0',
145
+ id: 1,
146
+ result: stub.response.result,
147
+ });
148
+ // We need to narrow the type.
149
+ // eslint-disable-next-line no-restricted-syntax
150
+ }
151
+ else if ('error' in stub.response) {
152
+ return callback(null, {
153
+ jsonrpc: '2.0',
154
+ id: 1,
155
+ error: {
156
+ code: -999,
157
+ message: stub.response.error,
158
+ },
159
+ });
160
+ }
161
+ // We need to narrow the type.
162
+ // eslint-disable-next-line no-restricted-syntax
163
+ }
164
+ else if ('error' in stub) {
165
+ return callback(stub.error);
166
+ }
167
+ return undefined;
168
+ };
169
+ //# sourceMappingURL=mock-internal-provider.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mock-internal-provider.mjs","sourceRoot":"","sources":["../src/mock-internal-provider.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EAAE,eAAe,EAAE,qCAAqC;AAM/D,OAAO,EAAE,WAAW,EAAE,wBAAwB;;;AAW9C,OAAO,EAAE,gBAAgB,EAAE,gCAA+B;AAE1D,2CAA2C;AAC3C,MAAM,kBAAkB,GAAG,UAAU,CAAC;AA0FtC;;;;;;;GAOG;AACH,uEAAuE;AACvE,wEAAwE;AACxE,kBAAkB;AAClB,MAAM,OAAO,oBAAqB,SAAQ,gBAAyB;IAOjE;;;;;;OAMG;IACH,YAAY,EAAE,KAAK,GAAG,EAAE,KAAwC,EAAE;QAChE,KAAK,CAAC;YACJ,MAAM,EAAE,eAAe,CAAC,MAAM,CAAa;gBACzC,UAAU,EAAE;oBACV,GAAU,EAAE;wBACV,MAAM,IAAI,KAAK,CACb,qDAAqD,CACtD,CAAC;oBACJ,CAAC;iBACF;aACF,CAAC;SACH,CAAC,CAAC;;QAtBI,sDAA2C;QAE3C,8CAAmC;QA0B5C,YAAO,GAAG,CACR,OAA+B,EACd,EAAE;YACnB,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE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IAAI,CAAC,QAAQ,CAAC,KAAK;iBAC7B;aACF,CAAC,CAAC;QACL,CAAC;QACD,8BAA8B;QAC9B,gDAAgD;IAClD,CAAC;SAAM,IAAI,OAAO,IAAI,IAAI,EAAE,CAAC;QAC3B,OAAO,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IAC9B,CAAC;IAED,OAAO,SAAS,CAAC;AACnB,CAAC","sourcesContent":["import { JsonRpcEngineV2 } from '@metamask/json-rpc-engine/v2';\nimport type {\n JsonRpcMiddleware,\n MiddlewareContext,\n ResultConstraint,\n} from '@metamask/json-rpc-engine/v2';\nimport { hasProperty } from '@metamask/utils';\nimport type {\n Json,\n JsonRpcId,\n JsonRpcParams,\n JsonRpcRequest,\n JsonRpcResponse,\n JsonRpcVersion2,\n} from '@metamask/utils';\nimport { isEqual } from 'lodash';\n\nimport { InternalProvider } from './internal-provider.js';\n\n// Store this in case it gets stubbed later\nconst originalSetTimeout = setTimeout;\n\n/**\n * A JSON-RPC request conforming to the EIP-1193 specification.\n */\ntype Eip1193Request<Params extends JsonRpcParams> = {\n id?: JsonRpcId;\n jsonrpc?: JsonRpcVersion2;\n method: string;\n params?: Params;\n};\n\n/**\n * Represents the type of the `response` property in a fake provider stub.\n */\n// TODO: Replace `any` with type\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type MockInternalProviderResponse = { result: any } | { error: string };\n\n/**\n * An object that allows specifying the behavior of a specific invocation of\n * `request`. The `method` always identifies the stub, but the behavior\n * may be specified multiple ways: `request` can either return a promise or\n * throw an error, and if it returns a promise, that promise can either be\n * resolved with a response object or reject with an error.\n *\n * @property request - Looks for a request matching these specifications.\n * @property request.method - The RPC method to which this stub will be matched.\n * @property request.params - The params to which this stub will be matched.\n * @property response - Instructs `request` to return a promise that resolves\n * with a response object.\n * @property response.result - Specifies a successful response, with this as the\n * `result`.\n * @property response.error - Specifies an error response, with this as the\n * `error`.\n * @property error - Instructs `request` to return a promise that rejects with\n * this error.\n * @property implementation - Allows overriding `request` entirely. Useful if\n * you want it to throw an error.\n * @property delay - The amount of time that will pass after the callback is\n * called with the response.\n * @property discardAfterMatching - Usually after the stub matches a request, it\n * is discarded, but setting this to true prevents that from happening. True by\n * default.\n * @property beforeCompleting - Sometimes it is useful to do something after the\n * request is kicked off but before it ends (or, in terms of a `fetch` promise,\n * when the promise is initiated but before it is resolved). You can pass an\n * (async) function for this option to do this.\n */\nexport type MockInternalProviderStub = {\n request: {\n method: string;\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n params?: any[];\n };\n delay?: number;\n discardAfterMatching?: boolean;\n beforeCompleting?: () => void | Promise<void>;\n} & (\n | {\n response: MockInternalProviderResponse;\n }\n | {\n error: unknown;\n }\n | {\n implementation: () => void;\n }\n);\n\n/**\n * The set of options that the MockInternalProvider constructor takes.\n *\n * @property stubs - A set of objects that allow specifying the behavior\n * of specific invocations of `request` matching a `method`.\n */\ntype MockInternalProviderEngineOptions = {\n stubs?: MockInternalProviderStub[];\n};\n\ntype Context = MiddlewareContext<\n { origin: string; skipCache: boolean } & Record<string, unknown>\n>;\ntype Middleware = JsonRpcMiddleware<\n JsonRpcRequest,\n ResultConstraint<JsonRpcRequest>,\n Context\n>;\n\n/**\n * An implementation of the provider that NetworkController exposes, which is\n * actually an instance of InternalProvider (from the\n * `@metamask/eth-json-rpc-provider` package). Hence it supports the same\n * interface as InternalProvider, except that fake responses for any RPC\n * methods that are accessed can be supplied via an API that is more succinct\n * than using Jest's mocking API.\n */\n// NOTE: We shouldn't need to extend from the \"real\" provider here, but\n// we'd need a `InternalProvider` _interface_ and that doesn't exist (at\n// least not yet).\nexport class MockInternalProvider extends InternalProvider<Context> {\n calledStubs: MockInternalProviderStub[];\n\n readonly #originalStubs: MockInternalProviderStub[];\n\n readonly #stubs: MockInternalProviderStub[];\n\n /**\n * Makes a new instance of the fake provider.\n *\n * @param options - The options.\n * @param options.stubs - A set of objects that allow specifying the behavior\n * of specific invocations of `request` matching a `method`.\n */\n constructor({ stubs = [] }: MockInternalProviderEngineOptions = {}) {\n super({\n engine: JsonRpcEngineV2.create<Middleware>({\n middleware: [\n (): never => {\n throw new Error(\n 'MockInternalProvider received unstubbed method call',\n );\n },\n ],\n }),\n });\n this.#originalStubs = stubs;\n this.#stubs = this.#originalStubs.slice();\n this.calledStubs = [];\n }\n\n request = <Params extends JsonRpcParams, Result extends Json>(\n payload: Eip1193Request<Params>,\n ): Promise<Result> => {\n return new Promise((resolve, reject) => {\n this.#handleSend(payload, (error, providerRes) => {\n if (error) {\n // Error is `unknown`.\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors\n reject(error);\n } else {\n resolve(providerRes.result);\n }\n });\n });\n };\n\n sendAsync = <Params extends JsonRpcParams>(\n payload: Eip1193Request<Params>,\n // This is copied from the implementation for InternalProvider.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n callback: (error: unknown, providerRes?: any) => void,\n ): void => {\n return this.#handleSend(payload, callback);\n };\n\n send = <Params extends JsonRpcParams>(\n req: Eip1193Request<Params>,\n // This is copied from the implementation for InternalProvider.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n callback: (error: unknown, providerRes?: any) => void,\n ): void => {\n return this.#handleSend(req, callback);\n };\n\n #handleSend<Params extends JsonRpcParams>(\n req: Eip1193Request<Params>,\n // This is copied from the implementation for InternalProvider.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n callback: (error: unknown, providerRes?: any) => void,\n ): void {\n if (Array.isArray(req)) {\n throw new Error(\"Arrays aren't supported\");\n }\n\n const index = this.#stubs.findIndex((stub) => {\n return (\n stub.request.method === req.method &&\n (!hasProperty(stub.request, 'params') ||\n isEqual(stub.request.params, req.params))\n );\n });\n\n if (index === -1) {\n const matchingCalledStubs = this.calledStubs.filter((stub) => {\n return (\n stub.request.method === req.method &&\n (!hasProperty(stub.request, 'params') ||\n isEqual(stub.request.params, req.params))\n );\n });\n let message = `Could not find any stubs matching: ${JSON.stringify(req)}`;\n if (matchingCalledStubs.length > 0) {\n message += `\\n\\nIt appears the following stubs were defined, but have been called already:\\n\\n${JSON.stringify(\n matchingCalledStubs,\n )}`;\n }\n\n throw new Error(message);\n } else {\n // We just verified that we can find this index.\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const stub = this.#stubs[index]!;\n\n if (stub.discardAfterMatching !== false) {\n this.#stubs.splice(index, 1);\n }\n\n if (stub.delay) {\n originalSetTimeout(() => {\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.#handleRequest(stub, callback);\n }, stub.delay);\n } else {\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.#handleRequest(stub, callback);\n }\n\n this.calledStubs.push({ ...stub });\n }\n }\n\n async #handleRequest(\n stub: MockInternalProviderStub,\n callback: (error: unknown, response?: JsonRpcResponse) => void,\n ): Promise<void> {\n if (stub.beforeCompleting) {\n await stub.beforeCompleting();\n }\n\n // We need to narrow the type.\n // eslint-disable-next-line no-restricted-syntax\n if ('implementation' in stub) {\n stub.implementation();\n // We need to narrow the type.\n // eslint-disable-next-line no-restricted-syntax\n } else if ('response' in stub) {\n // We need to narrow the type.\n // eslint-disable-next-line no-restricted-syntax\n if ('result' in stub.response) {\n return callback(null, {\n jsonrpc: '2.0',\n id: 1,\n result: stub.response.result,\n });\n // We need to narrow the type.\n // eslint-disable-next-line no-restricted-syntax\n } else if ('error' in stub.response) {\n return callback(null, {\n jsonrpc: '2.0',\n id: 1,\n error: {\n code: -999,\n message: stub.response.error,\n },\n });\n }\n // We need to narrow the type.\n // eslint-disable-next-line no-restricted-syntax\n } else if ('error' in stub) {\n return callback(stub.error);\n }\n\n return undefined;\n }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metamask-previews/eth-json-rpc-provider",
3
- "version": "6.0.1-preview-5bb6dba48",
3
+ "version": "6.0.1-preview-d8fceeabc",
4
4
  "description": "Create an Ethereum provider using a JSON-RPC engine or middleware",
5
5
  "keywords": [
6
6
  "Ethereum",
@@ -56,6 +56,8 @@
56
56
  "@metamask/json-rpc-engine": "^10.5.0",
57
57
  "@metamask/rpc-errors": "^7.0.2",
58
58
  "@metamask/utils": "^11.12.0",
59
+ "@types/lodash": "^4.14.191",
60
+ "lodash": "^4.17.21",
59
61
  "nanoid": "^3.3.8"
60
62
  },
61
63
  "devDependencies": {