@metamask/snaps-controllers 9.9.0 → 9.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/CHANGELOG.md +9 -1
  2. package/dist/cronjob/CronjobController.cjs +34 -21
  3. package/dist/cronjob/CronjobController.cjs.map +1 -1
  4. package/dist/cronjob/CronjobController.mjs +34 -21
  5. package/dist/cronjob/CronjobController.mjs.map +1 -1
  6. package/dist/insights/SnapInsightsController.cjs +144 -194
  7. package/dist/insights/SnapInsightsController.cjs.map +1 -1
  8. package/dist/insights/SnapInsightsController.mjs +143 -193
  9. package/dist/insights/SnapInsightsController.mjs.map +1 -1
  10. package/dist/interface/SnapInterfaceController.cjs +65 -90
  11. package/dist/interface/SnapInterfaceController.cjs.map +1 -1
  12. package/dist/interface/SnapInterfaceController.mjs +65 -90
  13. package/dist/interface/SnapInterfaceController.mjs.map +1 -1
  14. package/dist/interface/utils.cjs +6 -2
  15. package/dist/interface/utils.cjs.map +1 -1
  16. package/dist/interface/utils.d.cts.map +1 -1
  17. package/dist/interface/utils.d.mts.map +1 -1
  18. package/dist/interface/utils.mjs +6 -2
  19. package/dist/interface/utils.mjs.map +1 -1
  20. package/dist/services/AbstractExecutionService.cjs +77 -71
  21. package/dist/services/AbstractExecutionService.cjs.map +1 -1
  22. package/dist/services/AbstractExecutionService.mjs +77 -71
  23. package/dist/services/AbstractExecutionService.mjs.map +1 -1
  24. package/dist/services/ProxyPostMessageStream.cjs +26 -19
  25. package/dist/services/ProxyPostMessageStream.cjs.map +1 -1
  26. package/dist/services/ProxyPostMessageStream.mjs +26 -19
  27. package/dist/services/ProxyPostMessageStream.mjs.map +1 -1
  28. package/dist/services/iframe/IframeExecutionService.cjs +4 -2
  29. package/dist/services/iframe/IframeExecutionService.cjs.map +1 -1
  30. package/dist/services/iframe/IframeExecutionService.d.cts.map +1 -1
  31. package/dist/services/iframe/IframeExecutionService.d.mts.map +1 -1
  32. package/dist/services/iframe/IframeExecutionService.mjs +4 -2
  33. package/dist/services/iframe/IframeExecutionService.mjs.map +1 -1
  34. package/dist/services/offscreen/OffscreenExecutionService.cjs +16 -3
  35. package/dist/services/offscreen/OffscreenExecutionService.cjs.map +1 -1
  36. package/dist/services/offscreen/OffscreenExecutionService.mjs +16 -3
  37. package/dist/services/offscreen/OffscreenExecutionService.mjs.map +1 -1
  38. package/dist/services/proxy/ProxyExecutionService.cjs +17 -4
  39. package/dist/services/proxy/ProxyExecutionService.cjs.map +1 -1
  40. package/dist/services/proxy/ProxyExecutionService.mjs +17 -4
  41. package/dist/services/proxy/ProxyExecutionService.mjs.map +1 -1
  42. package/dist/services/webview/WebViewExecutionService.cjs +23 -9
  43. package/dist/services/webview/WebViewExecutionService.cjs.map +1 -1
  44. package/dist/services/webview/WebViewExecutionService.mjs +23 -9
  45. package/dist/services/webview/WebViewExecutionService.mjs.map +1 -1
  46. package/dist/services/webview/WebViewMessageStream.cjs +25 -12
  47. package/dist/services/webview/WebViewMessageStream.cjs.map +1 -1
  48. package/dist/services/webview/WebViewMessageStream.mjs +25 -12
  49. package/dist/services/webview/WebViewMessageStream.mjs.map +1 -1
  50. package/dist/services/webworker/WebWorkerExecutionService.cjs +27 -10
  51. package/dist/services/webworker/WebWorkerExecutionService.cjs.map +1 -1
  52. package/dist/services/webworker/WebWorkerExecutionService.mjs +27 -10
  53. package/dist/services/webworker/WebWorkerExecutionService.mjs.map +1 -1
  54. package/dist/snaps/RequestQueue.cjs +0 -2
  55. package/dist/snaps/RequestQueue.cjs.map +1 -1
  56. package/dist/snaps/RequestQueue.mjs +0 -2
  57. package/dist/snaps/RequestQueue.mjs.map +1 -1
  58. package/dist/snaps/SnapController.cjs +1001 -1141
  59. package/dist/snaps/SnapController.cjs.map +1 -1
  60. package/dist/snaps/SnapController.mjs +1000 -1140
  61. package/dist/snaps/SnapController.mjs.map +1 -1
  62. package/dist/snaps/Timer.cjs +0 -1
  63. package/dist/snaps/Timer.cjs.map +1 -1
  64. package/dist/snaps/Timer.mjs +0 -1
  65. package/dist/snaps/Timer.mjs.map +1 -1
  66. package/dist/snaps/location/http.cjs +7 -11
  67. package/dist/snaps/location/http.cjs.map +1 -1
  68. package/dist/snaps/location/http.mjs +7 -11
  69. package/dist/snaps/location/http.mjs.map +1 -1
  70. package/dist/snaps/location/local.cjs +17 -4
  71. package/dist/snaps/location/local.cjs.map +1 -1
  72. package/dist/snaps/location/local.mjs +17 -4
  73. package/dist/snaps/location/local.mjs.map +1 -1
  74. package/dist/snaps/location/npm.cjs +37 -25
  75. package/dist/snaps/location/npm.cjs.map +1 -1
  76. package/dist/snaps/location/npm.mjs +37 -25
  77. package/dist/snaps/location/npm.mjs.map +1 -1
  78. package/dist/snaps/registry/json.cjs +173 -172
  79. package/dist/snaps/registry/json.cjs.map +1 -1
  80. package/dist/snaps/registry/json.mjs +172 -171
  81. package/dist/snaps/registry/json.mjs.map +1 -1
  82. package/package.json +5 -5
@@ -1,3 +1,15 @@
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 _AbstractExecutionService_instances, _AbstractExecutionService_snapRpcHooks, _AbstractExecutionService_snapToJobMap, _AbstractExecutionService_jobToSnapMap, _AbstractExecutionService_messenger, _AbstractExecutionService_initTimeout, _AbstractExecutionService_pingTimeout, _AbstractExecutionService_terminationTimeout, _AbstractExecutionService_usePing, _AbstractExecutionService_removeSnapHooks, _AbstractExecutionService_createSnapHooks, _AbstractExecutionService_mapSnapAndJob, _AbstractExecutionService_removeSnapAndJobMapping;
1
13
  function $importDefault(module) {
2
14
  if (module?.__esModule) {
3
15
  return module.default;
@@ -18,29 +30,26 @@ import { Timer } from "../snaps/Timer.mjs";
18
30
  import { hasTimedOut, withTimeout } from "../utils.mjs";
19
31
  const controllerName = 'ExecutionService';
20
32
  export class AbstractExecutionService {
21
- #snapRpcHooks;
22
- // Cannot be hash private yet because of tests.
23
- jobs;
24
- // Cannot be hash private yet because of tests.
25
- setupSnapProvider;
26
- #snapToJobMap;
27
- #jobToSnapMap;
28
- #messenger;
29
- #initTimeout;
30
- #pingTimeout;
31
- #terminationTimeout;
32
- #usePing;
33
33
  constructor({ setupSnapProvider, messenger, initTimeout = inMilliseconds(60, Duration.Second), pingTimeout = inMilliseconds(2, Duration.Second), terminationTimeout = inMilliseconds(1, Duration.Second), usePing = true, }) {
34
- this.#snapRpcHooks = new Map();
34
+ _AbstractExecutionService_instances.add(this);
35
+ _AbstractExecutionService_snapRpcHooks.set(this, void 0);
36
+ _AbstractExecutionService_snapToJobMap.set(this, void 0);
37
+ _AbstractExecutionService_jobToSnapMap.set(this, void 0);
38
+ _AbstractExecutionService_messenger.set(this, void 0);
39
+ _AbstractExecutionService_initTimeout.set(this, void 0);
40
+ _AbstractExecutionService_pingTimeout.set(this, void 0);
41
+ _AbstractExecutionService_terminationTimeout.set(this, void 0);
42
+ _AbstractExecutionService_usePing.set(this, void 0);
43
+ __classPrivateFieldSet(this, _AbstractExecutionService_snapRpcHooks, new Map(), "f");
35
44
  this.jobs = new Map();
36
45
  this.setupSnapProvider = setupSnapProvider;
37
- this.#snapToJobMap = new Map();
38
- this.#jobToSnapMap = new Map();
39
- this.#messenger = messenger;
40
- this.#initTimeout = initTimeout;
41
- this.#pingTimeout = pingTimeout;
42
- this.#terminationTimeout = terminationTimeout;
43
- this.#usePing = usePing;
46
+ __classPrivateFieldSet(this, _AbstractExecutionService_snapToJobMap, new Map(), "f");
47
+ __classPrivateFieldSet(this, _AbstractExecutionService_jobToSnapMap, new Map(), "f");
48
+ __classPrivateFieldSet(this, _AbstractExecutionService_messenger, messenger, "f");
49
+ __classPrivateFieldSet(this, _AbstractExecutionService_initTimeout, initTimeout, "f");
50
+ __classPrivateFieldSet(this, _AbstractExecutionService_pingTimeout, pingTimeout, "f");
51
+ __classPrivateFieldSet(this, _AbstractExecutionService_terminationTimeout, terminationTimeout, "f");
52
+ __classPrivateFieldSet(this, _AbstractExecutionService_usePing, usePing, "f");
44
53
  this.registerMessageHandlers();
45
54
  }
46
55
  /**
@@ -48,10 +57,10 @@ export class AbstractExecutionService {
48
57
  * actions.
49
58
  */
50
59
  registerMessageHandlers() {
51
- this.#messenger.registerActionHandler(`${controllerName}:handleRpcRequest`, async (snapId, options) => this.handleRpcRequest(snapId, options));
52
- this.#messenger.registerActionHandler(`${controllerName}:executeSnap`, async (data) => this.executeSnap(data));
53
- this.#messenger.registerActionHandler(`${controllerName}:terminateSnap`, async (snapId) => this.terminateSnap(snapId));
54
- this.#messenger.registerActionHandler(`${controllerName}:terminateAllSnaps`, async () => this.terminateAllSnaps());
60
+ __classPrivateFieldGet(this, _AbstractExecutionService_messenger, "f").registerActionHandler(`${controllerName}:handleRpcRequest`, async (snapId, options) => this.handleRpcRequest(snapId, options));
61
+ __classPrivateFieldGet(this, _AbstractExecutionService_messenger, "f").registerActionHandler(`${controllerName}:executeSnap`, async (data) => this.executeSnap(data));
62
+ __classPrivateFieldGet(this, _AbstractExecutionService_messenger, "f").registerActionHandler(`${controllerName}:terminateSnap`, async (snapId) => this.terminateSnap(snapId));
63
+ __classPrivateFieldGet(this, _AbstractExecutionService_messenger, "f").registerActionHandler(`${controllerName}:terminateAllSnaps`, async () => this.terminateAllSnaps());
55
64
  }
56
65
  /**
57
66
  * Terminates the job with the specified ID and deletes all its associated
@@ -73,7 +82,7 @@ export class AbstractExecutionService {
73
82
  method: 'terminate',
74
83
  params: [],
75
84
  id: nanoid(),
76
- }), this.#terminationTimeout);
85
+ }), __classPrivateFieldGet(this, _AbstractExecutionService_terminationTimeout, "f"));
77
86
  if (result === hasTimedOut || result !== 'OK') {
78
87
  // We tried to shutdown gracefully but failed. This probably means the Snap is in infinite loop and
79
88
  // hogging down the whole JS process.
@@ -97,7 +106,7 @@ export class AbstractExecutionService {
97
106
  });
98
107
  this.terminateJob(jobWrapper);
99
108
  this.jobs.delete(jobId);
100
- this.#removeSnapAndJobMapping(jobId);
109
+ __classPrivateFieldGet(this, _AbstractExecutionService_instances, "m", _AbstractExecutionService_removeSnapAndJobMapping).call(this, jobId);
101
110
  log(`Job "${jobId}" terminated.`);
102
111
  }
103
112
  /**
@@ -152,16 +161,16 @@ export class AbstractExecutionService {
152
161
  return;
153
162
  }
154
163
  // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
155
- const snapId = this.#jobToSnapMap.get(jobId);
164
+ const snapId = __classPrivateFieldGet(this, _AbstractExecutionService_jobToSnapMap, "f").get(jobId);
156
165
  if (message.method === 'OutboundRequest') {
157
- this.#messenger.publish('ExecutionService:outboundRequest', snapId);
166
+ __classPrivateFieldGet(this, _AbstractExecutionService_messenger, "f").publish('ExecutionService:outboundRequest', snapId);
158
167
  }
159
168
  else if (message.method === 'OutboundResponse') {
160
- this.#messenger.publish('ExecutionService:outboundResponse', snapId);
169
+ __classPrivateFieldGet(this, _AbstractExecutionService_messenger, "f").publish('ExecutionService:outboundResponse', snapId);
161
170
  }
162
171
  else if (message.method === 'UnhandledError') {
163
172
  if (isObject(message.params) && message.params.error) {
164
- this.#messenger.publish('ExecutionService:unhandledError', snapId, message.params.error);
173
+ __classPrivateFieldGet(this, _AbstractExecutionService_messenger, "f").publish('ExecutionService:unhandledError', snapId, message.params.error);
165
174
  commandStream.removeListener('data', notificationHandler);
166
175
  }
167
176
  else {
@@ -193,14 +202,14 @@ export class AbstractExecutionService {
193
202
  * @param snapId - The ID of the snap to terminate.
194
203
  */
195
204
  async terminateSnap(snapId) {
196
- const jobId = this.#snapToJobMap.get(snapId);
205
+ const jobId = __classPrivateFieldGet(this, _AbstractExecutionService_snapToJobMap, "f").get(snapId);
197
206
  if (jobId) {
198
207
  await this.terminate(jobId);
199
208
  }
200
209
  }
201
210
  async terminateAllSnaps() {
202
211
  await Promise.all([...this.jobs.keys()].map(async (jobId) => this.terminate(jobId)));
203
- this.#snapRpcHooks.clear();
212
+ __classPrivateFieldGet(this, _AbstractExecutionService_snapRpcHooks, "f").clear();
204
213
  }
205
214
  /**
206
215
  * Gets the RPC request handler for the given snap.
@@ -209,7 +218,7 @@ export class AbstractExecutionService {
209
218
  * @returns The RPC request handler for the snap.
210
219
  */
211
220
  getRpcRequestHandler(snapId) {
212
- return this.#snapRpcHooks.get(snapId);
221
+ return __classPrivateFieldGet(this, _AbstractExecutionService_snapRpcHooks, "f").get(snapId);
213
222
  }
214
223
  /**
215
224
  * Initializes and executes a snap, setting up the communication channels to the snap etc.
@@ -222,22 +231,22 @@ export class AbstractExecutionService {
222
231
  * @throws If the execution service returns an error or execution times out.
223
232
  */
224
233
  async executeSnap({ snapId, sourceCode, endowments, }) {
225
- if (this.#snapToJobMap.has(snapId)) {
234
+ if (__classPrivateFieldGet(this, _AbstractExecutionService_snapToJobMap, "f").has(snapId)) {
226
235
  throw new Error(`Snap "${snapId}" is already being executed.`);
227
236
  }
228
237
  const jobId = nanoid();
229
- const timer = new Timer(this.#initTimeout);
238
+ const timer = new Timer(__classPrivateFieldGet(this, _AbstractExecutionService_initTimeout, "f"));
230
239
  // This may resolve even if the environment has failed to start up fully
231
240
  const job = await this.initJob(jobId, timer);
232
- this.#mapSnapAndJob(snapId, job.id);
241
+ __classPrivateFieldGet(this, _AbstractExecutionService_instances, "m", _AbstractExecutionService_mapSnapAndJob).call(this, snapId, job.id);
233
242
  // Certain environments use ping as part of their initialization and thus can skip it here
234
- if (this.#usePing) {
243
+ if (__classPrivateFieldGet(this, _AbstractExecutionService_usePing, "f")) {
235
244
  // Ping the worker to ensure that it started up
236
245
  const pingResult = await withTimeout(this.command(job.id, {
237
246
  jsonrpc: '2.0',
238
247
  method: 'ping',
239
248
  id: nanoid(),
240
- }), this.#pingTimeout);
249
+ }), __classPrivateFieldGet(this, _AbstractExecutionService_pingTimeout, "f"));
241
250
  if (pingResult === hasTimedOut) {
242
251
  throw new Error('The Snaps execution environment failed to start.');
243
252
  }
@@ -254,7 +263,7 @@ export class AbstractExecutionService {
254
263
  if (result === hasTimedOut) {
255
264
  throw new Error(`${snapId} failed to start.`);
256
265
  }
257
- this.#createSnapHooks(snapId, job.id);
266
+ __classPrivateFieldGet(this, _AbstractExecutionService_instances, "m", _AbstractExecutionService_createSnapHooks).call(this, snapId, job.id);
258
267
  return result;
259
268
  }
260
269
  // Cannot be hash private yet because of tests.
@@ -273,38 +282,6 @@ export class AbstractExecutionService {
273
282
  }
274
283
  return response.result;
275
284
  }
276
- #removeSnapHooks(snapId) {
277
- this.#snapRpcHooks.delete(snapId);
278
- }
279
- #createSnapHooks(snapId, workerId) {
280
- const rpcHook = async ({ origin, handler, request }) => {
281
- return await this.command(workerId, {
282
- id: nanoid(),
283
- jsonrpc: '2.0',
284
- method: 'snapRpc',
285
- params: {
286
- origin,
287
- handler,
288
- request: request,
289
- target: snapId,
290
- },
291
- });
292
- };
293
- this.#snapRpcHooks.set(snapId, rpcHook);
294
- }
295
- #mapSnapAndJob(snapId, jobId) {
296
- this.#snapToJobMap.set(snapId, jobId);
297
- this.#jobToSnapMap.set(jobId, snapId);
298
- }
299
- #removeSnapAndJobMapping(jobId) {
300
- const snapId = this.#jobToSnapMap.get(jobId);
301
- if (!snapId) {
302
- throw new Error(`job: "${jobId}" has no mapped snap.`);
303
- }
304
- this.#jobToSnapMap.delete(jobId);
305
- this.#snapToJobMap.delete(snapId);
306
- this.#removeSnapHooks(snapId);
307
- }
308
285
  /**
309
286
  * Handle RPC request.
310
287
  *
@@ -320,6 +297,35 @@ export class AbstractExecutionService {
320
297
  return rpcRequestHandler(options);
321
298
  }
322
299
  }
300
+ _AbstractExecutionService_snapRpcHooks = new WeakMap(), _AbstractExecutionService_snapToJobMap = new WeakMap(), _AbstractExecutionService_jobToSnapMap = new WeakMap(), _AbstractExecutionService_messenger = new WeakMap(), _AbstractExecutionService_initTimeout = new WeakMap(), _AbstractExecutionService_pingTimeout = new WeakMap(), _AbstractExecutionService_terminationTimeout = new WeakMap(), _AbstractExecutionService_usePing = new WeakMap(), _AbstractExecutionService_instances = new WeakSet(), _AbstractExecutionService_removeSnapHooks = function _AbstractExecutionService_removeSnapHooks(snapId) {
301
+ __classPrivateFieldGet(this, _AbstractExecutionService_snapRpcHooks, "f").delete(snapId);
302
+ }, _AbstractExecutionService_createSnapHooks = function _AbstractExecutionService_createSnapHooks(snapId, workerId) {
303
+ const rpcHook = async ({ origin, handler, request }) => {
304
+ return await this.command(workerId, {
305
+ id: nanoid(),
306
+ jsonrpc: '2.0',
307
+ method: 'snapRpc',
308
+ params: {
309
+ origin,
310
+ handler,
311
+ request: request,
312
+ target: snapId,
313
+ },
314
+ });
315
+ };
316
+ __classPrivateFieldGet(this, _AbstractExecutionService_snapRpcHooks, "f").set(snapId, rpcHook);
317
+ }, _AbstractExecutionService_mapSnapAndJob = function _AbstractExecutionService_mapSnapAndJob(snapId, jobId) {
318
+ __classPrivateFieldGet(this, _AbstractExecutionService_snapToJobMap, "f").set(snapId, jobId);
319
+ __classPrivateFieldGet(this, _AbstractExecutionService_jobToSnapMap, "f").set(jobId, snapId);
320
+ }, _AbstractExecutionService_removeSnapAndJobMapping = function _AbstractExecutionService_removeSnapAndJobMapping(jobId) {
321
+ const snapId = __classPrivateFieldGet(this, _AbstractExecutionService_jobToSnapMap, "f").get(jobId);
322
+ if (!snapId) {
323
+ throw new Error(`job: "${jobId}" has no mapped snap.`);
324
+ }
325
+ __classPrivateFieldGet(this, _AbstractExecutionService_jobToSnapMap, "f").delete(jobId);
326
+ __classPrivateFieldGet(this, _AbstractExecutionService_snapToJobMap, "f").delete(snapId);
327
+ __classPrivateFieldGet(this, _AbstractExecutionService_instances, "m", _AbstractExecutionService_removeSnapHooks).call(this, snapId);
328
+ };
323
329
  /**
324
330
  * Sets up stream multiplexing for the given stream.
325
331
  *
@@ -1 +1 @@
1
- {"version":3,"file":"AbstractExecutionService.mjs","sourceRoot":"","sources":["../../src/services/AbstractExecutionService.ts"],"names":[],"mappings":";;;;;;AAAA,OAAO,EAAE,aAAa,EAAE,kCAAkC;AAC1D,OAAO,EAAE,sBAAsB,EAAE,6CAA6C;AAC9E,OAAO,gBAAe,mCAAmC;;AAEzD,OAAO,EAAE,YAAY,EAAE,6BAA6B;AAEpD,OAAO,EAAE,iBAAiB,EAAE,QAAQ,EAAE,8BAA8B;AAMpE,OAAO,EACL,QAAQ,EACR,sBAAsB,EACtB,cAAc,EACd,gBAAgB,EAChB,qBAAqB,EACrB,QAAQ,EACT,wBAAwB;AACzB,OAAO,EAAE,MAAM,EAAE,eAAe;AAChC,OAAO,EAAE,QAAQ,EAAE,wBAAwB;AAG3C,OAAO,EAAE,GAAG,EAAE,uBAAmB;AACjC,OAAO,EAAE,KAAK,EAAE,2BAAuB;AACvC,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,qBAAiB;AAQpD,MAAM,cAAc,GAAG,kBAAkB,CAAC;AA6B1C,MAAM,OAAgB,wBAAwB;IAG5C,aAAa,CAA2B;IAExC,+CAA+C;IACrC,IAAI,CAA+B;IAE7C,+CAA+C;IAC9B,iBAAiB,CAAoB;IAEtD,aAAa,CAAsB;IAEnC,aAAa,CAAsB;IAEnC,UAAU,CAA4B;IAEtC,YAAY,CAAS;IAErB,YAAY,CAAS;IAErB,mBAAmB,CAAS;IAE5B,QAAQ,CAAU;IAElB,YAAY,EACV,iBAAiB,EACjB,SAAS,EACT,WAAW,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,CAAC;QAE5D,IAAI,CAAC,iBAAiB,EAAE,CAAC;YACvB,MAAM,IAAI,KAAK,CACb,oEAAoE,MAAM,IAAI,CAC/E,CAAC;QACJ,CAAC;QAED,OAAO,iBAAiB,CAAC,OAAO,CAAC,CAAC;IACpC,CAAC;CACF;AAED;;;;;;GAMG;AACH,MAAM,UAAU,cAAc,CAC5B,gBAAwB,EACxB,UAAkB;IAElB,MAAM,GAAG,GAAG,IAAI,eAAe,EAAE,CAAC;IAClC,QAAQ,CAAC,gBAAgB,EAAE,GAAG,EAAE,gBAAgB,EAAE,CAAC,KAAK,EAAE,EAAE;QAC1D,IAAI,KAAK,EAAE,CAAC;YACV,UAAU;gBACR,CAAC,CAAC,QAAQ,CAAC,IAAI,UAAU,mBAAmB,EAAE,KAAK,CAAC;gBACpD,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;QACtB,CAAC;IACH,CAAC,CAAC,CAAC;IACH,OAAO,GAAG,CAAC;AACb,CAAC","sourcesContent":["import { JsonRpcEngine } from '@metamask/json-rpc-engine';\nimport { createStreamMiddleware } from '@metamask/json-rpc-middleware-stream';\nimport ObjectMultiplex from '@metamask/object-multiplex';\nimport type { BasePostMessageStream } from '@metamask/post-message-stream';\nimport { JsonRpcError } from '@metamask/rpc-errors';\nimport type { SnapRpcHook, SnapRpcHookArgs } from '@metamask/snaps-utils';\nimport { SNAP_STREAM_NAMES, logError } from '@metamask/snaps-utils';\nimport type {\n Json,\n JsonRpcNotification,\n JsonRpcRequest,\n} from '@metamask/utils';\nimport {\n Duration,\n assertIsJsonRpcRequest,\n inMilliseconds,\n isJsonRpcFailure,\n isJsonRpcNotification,\n isObject,\n} from '@metamask/utils';\nimport { nanoid } from 'nanoid';\nimport { pipeline } from 'readable-stream';\nimport type { Duplex } from 'readable-stream';\n\nimport { log } from '../logging';\nimport { Timer } from '../snaps/Timer';\nimport { hasTimedOut, withTimeout } from '../utils';\nimport type {\n ExecutionService,\n ExecutionServiceMessenger,\n SnapErrorJson,\n SnapExecutionData,\n} from './ExecutionService';\n\nconst controllerName = 'ExecutionService';\n\nexport type SetupSnapProvider = (snapId: string, stream: Duplex) => void;\n\nexport type ExecutionServiceArgs = {\n setupSnapProvider: SetupSnapProvider;\n messenger: ExecutionServiceMessenger;\n initTimeout?: number;\n pingTimeout?: number;\n terminationTimeout?: number;\n usePing?: boolean;\n};\n\nexport type JobStreams = {\n command: Duplex;\n rpc: Duplex;\n _connection: BasePostMessageStream;\n};\n\nexport type Job<WorkerType> = {\n id: string;\n streams: JobStreams;\n rpcEngine: JsonRpcEngine;\n worker: WorkerType;\n};\n\nexport type TerminateJobArgs<WorkerType> = Partial<Job<WorkerType>> &\n Pick<Job<WorkerType>, 'id'>;\n\nexport abstract class AbstractExecutionService<WorkerType>\n implements ExecutionService\n{\n #snapRpcHooks: Map<string, SnapRpcHook>;\n\n // Cannot be hash private yet because of tests.\n protected jobs: Map<string, Job<WorkerType>>;\n\n // Cannot be hash private yet because of tests.\n private readonly setupSnapProvider: SetupSnapProvider;\n\n #snapToJobMap: Map<string, string>;\n\n #jobToSnapMap: Map<string, string>;\n\n #messenger: ExecutionServiceMessenger;\n\n #initTimeout: number;\n\n #pingTimeout: number;\n\n #terminationTimeout: number;\n\n #usePing: boolean;\n\n constructor({\n setupSnapProvider,\n messenger,\n initTimeout = inMilliseconds(60, Duration.Second),\n pingTimeout = inMilliseconds(2, Duration.Second),\n terminationTimeout = inMilliseconds(1, Duration.Second),\n usePing = true,\n }: ExecutionServiceArgs) {\n this.#snapRpcHooks = new Map();\n this.jobs = new Map();\n this.setupSnapProvider = setupSnapProvider;\n this.#snapToJobMap = new Map();\n this.#jobToSnapMap = new Map();\n this.#messenger = messenger;\n this.#initTimeout = initTimeout;\n this.#pingTimeout = pingTimeout;\n this.#terminationTimeout = terminationTimeout;\n this.#usePing = usePing;\n\n this.registerMessageHandlers();\n }\n\n /**\n * Constructor helper for registering the controller's messaging system\n * actions.\n */\n private registerMessageHandlers(): void {\n this.#messenger.registerActionHandler(\n `${controllerName}:handleRpcRequest`,\n async (snapId: string, options: SnapRpcHookArgs) =>\n this.handleRpcRequest(snapId, options),\n );\n\n this.#messenger.registerActionHandler(\n `${controllerName}:executeSnap`,\n async (data: SnapExecutionData) => this.executeSnap(data),\n );\n\n this.#messenger.registerActionHandler(\n `${controllerName}:terminateSnap`,\n async (snapId: string) => this.terminateSnap(snapId),\n );\n\n this.#messenger.registerActionHandler(\n `${controllerName}:terminateAllSnaps`,\n async () => this.terminateAllSnaps(),\n );\n }\n\n /**\n * Performs additional necessary work during job termination. **MUST** be\n * implemented by concrete implementations. See\n * {@link AbstractExecutionService.terminate} for details.\n *\n * @param job - The object corresponding to the job to be terminated.\n */\n protected abstract terminateJob(job: TerminateJobArgs<WorkerType>): void;\n\n /**\n * Terminates the job with the specified ID and deletes all its associated\n * data. Any subsequent messages targeting the job will fail with an error.\n * Throws an error if the specified job does not exist, or if termination\n * fails unexpectedly.\n *\n * @param jobId - The id of the job to be terminated.\n */\n public async terminate(jobId: string): Promise<void> {\n const jobWrapper = this.jobs.get(jobId);\n if (!jobWrapper) {\n throw new Error(`Job with id \"${jobId}\" not found.`);\n }\n\n try {\n // Ping worker and tell it to run teardown, continue with termination if it takes too long\n const result = await withTimeout(\n this.command(jobId, {\n jsonrpc: '2.0',\n method: 'terminate',\n params: [],\n id: nanoid(),\n }),\n this.#terminationTimeout,\n );\n\n if (result === hasTimedOut || result !== 'OK') {\n // We tried to shutdown gracefully but failed. This probably means the Snap is in infinite loop and\n // hogging down the whole JS process.\n // TODO(ritave): It might be doing weird things such as posting a lot of setTimeouts. Add a test to ensure that this behaviour\n // doesn't leak into other workers. Especially important in IframeExecutionEnvironment since they all share the same\n // JS process.\n logError(`Job \"${jobId}\" failed to terminate gracefully.`, result);\n }\n } catch {\n // Ignore\n }\n\n Object.values(jobWrapper.streams).forEach((stream) => {\n try {\n !stream.destroyed && stream.destroy();\n stream.removeAllListeners();\n } catch (error) {\n logError('Error while destroying stream', error);\n }\n });\n\n this.terminateJob(jobWrapper);\n\n this.jobs.delete(jobId);\n this.#removeSnapAndJobMapping(jobId);\n log(`Job \"${jobId}\" terminated.`);\n }\n\n /**\n * Initiates a job for a snap.\n *\n * @param jobId - The ID of the job to initiate.\n * @param timer - The timer to use for timeouts.\n * @returns Information regarding the created job.\n * @throws If the execution service returns an error or execution times out.\n */\n protected async initJob(\n jobId: string,\n timer: Timer,\n ): Promise<Job<WorkerType>> {\n const { streams, worker } = await this.initStreams(jobId, timer);\n const rpcEngine = new JsonRpcEngine();\n\n const jsonRpcConnection = createStreamMiddleware();\n\n pipeline(\n jsonRpcConnection.stream,\n streams.command,\n jsonRpcConnection.stream,\n (error) => {\n if (error) {\n logError(`Command stream failure.`, error);\n }\n },\n );\n\n rpcEngine.push(jsonRpcConnection.middleware);\n\n const envMetadata = {\n id: jobId,\n streams,\n rpcEngine,\n worker,\n };\n this.jobs.set(jobId, envMetadata);\n\n return envMetadata;\n }\n\n /**\n * Sets up the streams for an initiated job.\n *\n * @param jobId - The id of the job.\n * @param timer - The timer to use for timeouts.\n * @returns The streams to communicate with the worker and the worker itself.\n * @throws If the execution service returns an error or execution times out.\n */\n protected async initStreams(\n jobId: string,\n timer: Timer,\n ): Promise<{ streams: JobStreams; worker: WorkerType }> {\n const result = await withTimeout(this.initEnvStream(jobId), timer);\n\n if (result === hasTimedOut) {\n // For certain environments, such as the iframe we may have already created the worker and wish to terminate it.\n this.terminateJob({ id: jobId });\n throw new Error('The Snaps execution environment failed to start.');\n }\n\n const { worker, stream: envStream } = result;\n const mux = setupMultiplex(envStream, `Job: \"${jobId}\"`);\n const commandStream = mux.createStream(SNAP_STREAM_NAMES.COMMAND);\n\n // Handle out-of-band errors, i.e. errors thrown from the snap outside of the req/res cycle.\n // Also keep track of outbound request/responses\n const notificationHandler = (\n message:\n | JsonRpcRequest\n | JsonRpcNotification<Json[] | Record<string, Json>>,\n ) => {\n if (!isJsonRpcNotification(message)) {\n return;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const snapId = this.#jobToSnapMap.get(jobId)!;\n if (message.method === 'OutboundRequest') {\n this.#messenger.publish('ExecutionService:outboundRequest', snapId);\n } else if (message.method === 'OutboundResponse') {\n this.#messenger.publish('ExecutionService:outboundResponse', snapId);\n } else if (message.method === 'UnhandledError') {\n if (isObject(message.params) && message.params.error) {\n this.#messenger.publish(\n 'ExecutionService:unhandledError',\n snapId,\n message.params.error as SnapErrorJson,\n );\n commandStream.removeListener('data', notificationHandler);\n } else {\n logError(\n new Error(\n `Received malformed \"${message.method}\" command stream notification.`,\n ),\n );\n }\n } else {\n logError(\n new Error(\n `Received unexpected command stream notification \"${message.method}\".`,\n ),\n );\n }\n };\n\n commandStream.on('data', notificationHandler);\n const rpcStream = mux.createStream(SNAP_STREAM_NAMES.JSON_RPC);\n\n // Typecast: stream type mismatch\n return {\n streams: {\n command: commandStream,\n rpc: rpcStream,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n _connection: envStream,\n },\n worker,\n };\n }\n\n /**\n * Abstract function implemented by implementing class that spins up a new worker for a job.\n *\n * Depending on the execution environment, this may run forever if the Snap fails to start up properly, therefore any call to this function should be wrapped in a timeout.\n */\n protected abstract initEnvStream(jobId: string): Promise<{\n worker: WorkerType;\n stream: BasePostMessageStream;\n }>;\n\n /**\n * Terminates the Snap with the specified ID. May throw an error if\n * termination unexpectedly fails, but will not fail if no job for the snap\n * with the specified ID is found.\n *\n * @param snapId - The ID of the snap to terminate.\n */\n async terminateSnap(snapId: string) {\n const jobId = this.#snapToJobMap.get(snapId);\n if (jobId) {\n await this.terminate(jobId);\n }\n }\n\n async terminateAllSnaps() {\n await Promise.all(\n [...this.jobs.keys()].map(async (jobId) => this.terminate(jobId)),\n );\n this.#snapRpcHooks.clear();\n }\n\n /**\n * Gets the RPC request handler for the given snap.\n *\n * @param snapId - The id of the Snap whose message handler to get.\n * @returns The RPC request handler for the snap.\n */\n private getRpcRequestHandler(snapId: string) {\n return this.#snapRpcHooks.get(snapId);\n }\n\n /**\n * Initializes and executes a snap, setting up the communication channels to the snap etc.\n *\n * @param snapData - Data needed for Snap execution.\n * @param snapData.snapId - The ID of the Snap to execute.\n * @param snapData.sourceCode - The source code of the Snap to execute.\n * @param snapData.endowments - The endowments available to the executing Snap.\n * @returns A string `OK` if execution succeeded.\n * @throws If the execution service returns an error or execution times out.\n */\n async executeSnap({\n snapId,\n sourceCode,\n endowments,\n }: SnapExecutionData): Promise<string> {\n if (this.#snapToJobMap.has(snapId)) {\n throw new Error(`Snap \"${snapId}\" is already being executed.`);\n }\n\n const jobId = nanoid();\n const timer = new Timer(this.#initTimeout);\n\n // This may resolve even if the environment has failed to start up fully\n const job = await this.initJob(jobId, timer);\n\n this.#mapSnapAndJob(snapId, job.id);\n\n // Certain environments use ping as part of their initialization and thus can skip it here\n if (this.#usePing) {\n // Ping the worker to ensure that it started up\n const pingResult = await withTimeout(\n this.command(job.id, {\n jsonrpc: '2.0',\n method: 'ping',\n id: nanoid(),\n }),\n this.#pingTimeout,\n );\n\n if (pingResult === hasTimedOut) {\n throw new Error('The Snaps execution environment failed to start.');\n }\n }\n\n const rpcStream = job.streams.rpc;\n\n this.setupSnapProvider(snapId, rpcStream);\n\n const remainingTime = timer.remaining;\n\n const result = await withTimeout(\n this.command(job.id, {\n jsonrpc: '2.0',\n method: 'executeSnap',\n params: { snapId, sourceCode, endowments },\n id: nanoid(),\n }),\n remainingTime,\n );\n\n if (result === hasTimedOut) {\n throw new Error(`${snapId} failed to start.`);\n }\n\n this.#createSnapHooks(snapId, job.id);\n return result as string;\n }\n\n // Cannot be hash private yet because of tests.\n private async command(\n jobId: string,\n message: JsonRpcRequest,\n ): Promise<Json | undefined> {\n assertIsJsonRpcRequest(message);\n\n const job = this.jobs.get(jobId);\n if (!job) {\n throw new Error(`Job with id \"${jobId}\" not found.`);\n }\n\n log('Parent: Sending Command', message);\n // eslint is blocking `await` usage even though `handle` overload returns a promise.\n // eslint-disable-next-line @typescript-eslint/await-thenable\n const response = await job.rpcEngine.handle(message);\n\n if (isJsonRpcFailure(response)) {\n throw new JsonRpcError(\n response.error.code,\n response.error.message,\n response.error.data,\n );\n }\n\n return response.result;\n }\n\n #removeSnapHooks(snapId: string) {\n this.#snapRpcHooks.delete(snapId);\n }\n\n #createSnapHooks(snapId: string, workerId: string) {\n const rpcHook = async ({ origin, handler, request }: SnapRpcHookArgs) => {\n return await this.command(workerId, {\n id: nanoid(),\n jsonrpc: '2.0',\n method: 'snapRpc',\n params: {\n origin,\n handler,\n request: request as JsonRpcRequest,\n target: snapId,\n },\n });\n };\n\n this.#snapRpcHooks.set(snapId, rpcHook);\n }\n\n #mapSnapAndJob(snapId: string, jobId: string): void {\n this.#snapToJobMap.set(snapId, jobId);\n this.#jobToSnapMap.set(jobId, snapId);\n }\n\n #removeSnapAndJobMapping(jobId: string): void {\n const snapId = this.#jobToSnapMap.get(jobId);\n if (!snapId) {\n throw new Error(`job: \"${jobId}\" has no mapped snap.`);\n }\n\n this.#jobToSnapMap.delete(jobId);\n this.#snapToJobMap.delete(snapId);\n this.#removeSnapHooks(snapId);\n }\n\n /**\n * Handle RPC request.\n *\n * @param snapId - The ID of the recipient snap.\n * @param options - Bag of options to pass to the RPC handler.\n * @returns Promise that can handle the request.\n */\n public async handleRpcRequest(\n snapId: string,\n options: SnapRpcHookArgs,\n ): Promise<unknown> {\n const rpcRequestHandler = this.getRpcRequestHandler(snapId);\n\n if (!rpcRequestHandler) {\n throw new Error(\n `Snap execution service returned no RPC handler for running snap \"${snapId}\".`,\n );\n }\n\n return rpcRequestHandler(options);\n }\n}\n\n/**\n * Sets up stream multiplexing for the given stream.\n *\n * @param connectionStream - The stream to mux.\n * @param streamName - The name of the stream, for identification in errors.\n * @returns The multiplexed stream.\n */\nexport function setupMultiplex(\n connectionStream: Duplex,\n streamName: string,\n): ObjectMultiplex {\n const mux = new ObjectMultiplex();\n pipeline(connectionStream, mux, connectionStream, (error) => {\n if (error) {\n streamName\n ? logError(`\"${streamName}\" stream failure.`, error)\n : logError(error);\n }\n });\n return mux;\n}\n"]}
1
+ {"version":3,"file":"AbstractExecutionService.mjs","sourceRoot":"","sources":["../../src/services/AbstractExecutionService.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAAA,OAAO,EAAE,aAAa,EAAE,kCAAkC;AAC1D,OAAO,EAAE,sBAAsB,EAAE,6CAA6C;AAC9E,OAAO,gBAAe,mCAAmC;;AAEzD,OAAO,EAAE,YAAY,EAAE,6BAA6B;AAEpD,OAAO,EAAE,iBAAiB,EAAE,QAAQ,EAAE,8BAA8B;AAMpE,OAAO,EACL,QAAQ,EACR,sBAAsB,EACtB,cAAc,EACd,gBAAgB,EAChB,qBAAqB,EACrB,QAAQ,EACT,wBAAwB;AACzB,OAAO,EAAE,MAAM,EAAE,eAAe;AAChC,OAAO,EAAE,QAAQ,EAAE,wBAAwB;AAG3C,OAAO,EAAE,GAAG,EAAE,uBAAmB;AACjC,OAAO,EAAE,KAAK,EAAE,2BAAuB;AACvC,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,qBAAiB;AAQpD,MAAM,cAAc,GAAG,kBAAkB,CAAC;AA6B1C,MAAM,OAAgB,wBAAwB;IAyB5C,YAAY,EACV,iBAAiB,EACjB,SAAS,EACT,WAAW,GAAG,cAAc,CAAC,EAAE,EAAE,QAAQ,CAAC,MAAM,CAAC,EACjD,WAAW,GAAG,cAAc,CAAC,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,EAChD,kBAAkB,GAAG,cAAc,CAAC,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,EACvD,OAAO,GAAG,IAAI,GACO;;QA7BvB,yDAAwC;QAQxC,yDAAmC;QAEnC,yDAAmC;QAEnC,sDAAsC;QAEtC,wDAAqB;QAErB,wDAAqB;QAErB,+DAA4B;QAE5B,oDAAkB;QAUhB,uBAAA,IAAI,0CAAiB,IAAI,GAAG,EAAE,MAAA,CAAC;QAC/B,IAAI,CAAC,IAAI,GAA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U,cAAc,CAC5B,gBAAwB,EACxB,UAAkB;IAElB,MAAM,GAAG,GAAG,IAAI,eAAe,EAAE,CAAC;IAClC,QAAQ,CAAC,gBAAgB,EAAE,GAAG,EAAE,gBAAgB,EAAE,CAAC,KAAK,EAAE,EAAE;QAC1D,IAAI,KAAK,EAAE,CAAC;YACV,UAAU;gBACR,CAAC,CAAC,QAAQ,CAAC,IAAI,UAAU,mBAAmB,EAAE,KAAK,CAAC;gBACpD,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;QACtB,CAAC;IACH,CAAC,CAAC,CAAC;IACH,OAAO,GAAG,CAAC;AACb,CAAC","sourcesContent":["import { JsonRpcEngine } from '@metamask/json-rpc-engine';\nimport { createStreamMiddleware } from '@metamask/json-rpc-middleware-stream';\nimport ObjectMultiplex from '@metamask/object-multiplex';\nimport type { BasePostMessageStream } from '@metamask/post-message-stream';\nimport { JsonRpcError } from '@metamask/rpc-errors';\nimport type { SnapRpcHook, SnapRpcHookArgs } from '@metamask/snaps-utils';\nimport { SNAP_STREAM_NAMES, logError } from '@metamask/snaps-utils';\nimport type {\n Json,\n JsonRpcNotification,\n JsonRpcRequest,\n} from '@metamask/utils';\nimport {\n Duration,\n assertIsJsonRpcRequest,\n inMilliseconds,\n isJsonRpcFailure,\n isJsonRpcNotification,\n isObject,\n} from '@metamask/utils';\nimport { nanoid } from 'nanoid';\nimport { pipeline } from 'readable-stream';\nimport type { Duplex } from 'readable-stream';\n\nimport { log } from '../logging';\nimport { Timer } from '../snaps/Timer';\nimport { hasTimedOut, withTimeout } from '../utils';\nimport type {\n ExecutionService,\n ExecutionServiceMessenger,\n SnapErrorJson,\n SnapExecutionData,\n} from './ExecutionService';\n\nconst controllerName = 'ExecutionService';\n\nexport type SetupSnapProvider = (snapId: string, stream: Duplex) => void;\n\nexport type ExecutionServiceArgs = {\n setupSnapProvider: SetupSnapProvider;\n messenger: ExecutionServiceMessenger;\n initTimeout?: number;\n pingTimeout?: number;\n terminationTimeout?: number;\n usePing?: boolean;\n};\n\nexport type JobStreams = {\n command: Duplex;\n rpc: Duplex;\n _connection: BasePostMessageStream;\n};\n\nexport type Job<WorkerType> = {\n id: string;\n streams: JobStreams;\n rpcEngine: JsonRpcEngine;\n worker: WorkerType;\n};\n\nexport type TerminateJobArgs<WorkerType> = Partial<Job<WorkerType>> &\n Pick<Job<WorkerType>, 'id'>;\n\nexport abstract class AbstractExecutionService<WorkerType>\n implements ExecutionService\n{\n #snapRpcHooks: Map<string, SnapRpcHook>;\n\n // Cannot be hash private yet because of tests.\n protected jobs: Map<string, Job<WorkerType>>;\n\n // Cannot be hash private yet because of tests.\n private readonly setupSnapProvider: SetupSnapProvider;\n\n #snapToJobMap: Map<string, string>;\n\n #jobToSnapMap: Map<string, string>;\n\n #messenger: ExecutionServiceMessenger;\n\n #initTimeout: number;\n\n #pingTimeout: number;\n\n #terminationTimeout: number;\n\n #usePing: boolean;\n\n constructor({\n setupSnapProvider,\n messenger,\n initTimeout = inMilliseconds(60, Duration.Second),\n pingTimeout = inMilliseconds(2, Duration.Second),\n terminationTimeout = inMilliseconds(1, Duration.Second),\n usePing = true,\n }: ExecutionServiceArgs) {\n this.#snapRpcHooks = new Map();\n this.jobs = new Map();\n this.setupSnapProvider = setupSnapProvider;\n this.#snapToJobMap = new Map();\n this.#jobToSnapMap = new Map();\n this.#messenger = messenger;\n this.#initTimeout = initTimeout;\n this.#pingTimeout = pingTimeout;\n this.#terminationTimeout = terminationTimeout;\n this.#usePing = usePing;\n\n this.registerMessageHandlers();\n }\n\n /**\n * Constructor helper for registering the controller's messaging system\n * actions.\n */\n private registerMessageHandlers(): void {\n this.#messenger.registerActionHandler(\n `${controllerName}:handleRpcRequest`,\n async (snapId: string, options: SnapRpcHookArgs) =>\n this.handleRpcRequest(snapId, options),\n );\n\n this.#messenger.registerActionHandler(\n `${controllerName}:executeSnap`,\n async (data: SnapExecutionData) => this.executeSnap(data),\n );\n\n this.#messenger.registerActionHandler(\n `${controllerName}:terminateSnap`,\n async (snapId: string) => this.terminateSnap(snapId),\n );\n\n this.#messenger.registerActionHandler(\n `${controllerName}:terminateAllSnaps`,\n async () => this.terminateAllSnaps(),\n );\n }\n\n /**\n * Performs additional necessary work during job termination. **MUST** be\n * implemented by concrete implementations. See\n * {@link AbstractExecutionService.terminate} for details.\n *\n * @param job - The object corresponding to the job to be terminated.\n */\n protected abstract terminateJob(job: TerminateJobArgs<WorkerType>): void;\n\n /**\n * Terminates the job with the specified ID and deletes all its associated\n * data. Any subsequent messages targeting the job will fail with an error.\n * Throws an error if the specified job does not exist, or if termination\n * fails unexpectedly.\n *\n * @param jobId - The id of the job to be terminated.\n */\n public async terminate(jobId: string): Promise<void> {\n const jobWrapper = this.jobs.get(jobId);\n if (!jobWrapper) {\n throw new Error(`Job with id \"${jobId}\" not found.`);\n }\n\n try {\n // Ping worker and tell it to run teardown, continue with termination if it takes too long\n const result = await withTimeout(\n this.command(jobId, {\n jsonrpc: '2.0',\n method: 'terminate',\n params: [],\n id: nanoid(),\n }),\n this.#terminationTimeout,\n );\n\n if (result === hasTimedOut || result !== 'OK') {\n // We tried to shutdown gracefully but failed. This probably means the Snap is in infinite loop and\n // hogging down the whole JS process.\n // TODO(ritave): It might be doing weird things such as posting a lot of setTimeouts. Add a test to ensure that this behaviour\n // doesn't leak into other workers. Especially important in IframeExecutionEnvironment since they all share the same\n // JS process.\n logError(`Job \"${jobId}\" failed to terminate gracefully.`, result);\n }\n } catch {\n // Ignore\n }\n\n Object.values(jobWrapper.streams).forEach((stream) => {\n try {\n !stream.destroyed && stream.destroy();\n stream.removeAllListeners();\n } catch (error) {\n logError('Error while destroying stream', error);\n }\n });\n\n this.terminateJob(jobWrapper);\n\n this.jobs.delete(jobId);\n this.#removeSnapAndJobMapping(jobId);\n log(`Job \"${jobId}\" terminated.`);\n }\n\n /**\n * Initiates a job for a snap.\n *\n * @param jobId - The ID of the job to initiate.\n * @param timer - The timer to use for timeouts.\n * @returns Information regarding the created job.\n * @throws If the execution service returns an error or execution times out.\n */\n protected async initJob(\n jobId: string,\n timer: Timer,\n ): Promise<Job<WorkerType>> {\n const { streams, worker } = await this.initStreams(jobId, timer);\n const rpcEngine = new JsonRpcEngine();\n\n const jsonRpcConnection = createStreamMiddleware();\n\n pipeline(\n jsonRpcConnection.stream,\n streams.command,\n jsonRpcConnection.stream,\n (error) => {\n if (error) {\n logError(`Command stream failure.`, error);\n }\n },\n );\n\n rpcEngine.push(jsonRpcConnection.middleware);\n\n const envMetadata = {\n id: jobId,\n streams,\n rpcEngine,\n worker,\n };\n this.jobs.set(jobId, envMetadata);\n\n return envMetadata;\n }\n\n /**\n * Sets up the streams for an initiated job.\n *\n * @param jobId - The id of the job.\n * @param timer - The timer to use for timeouts.\n * @returns The streams to communicate with the worker and the worker itself.\n * @throws If the execution service returns an error or execution times out.\n */\n protected async initStreams(\n jobId: string,\n timer: Timer,\n ): Promise<{ streams: JobStreams; worker: WorkerType }> {\n const result = await withTimeout(this.initEnvStream(jobId), timer);\n\n if (result === hasTimedOut) {\n // For certain environments, such as the iframe we may have already created the worker and wish to terminate it.\n this.terminateJob({ id: jobId });\n throw new Error('The Snaps execution environment failed to start.');\n }\n\n const { worker, stream: envStream } = result;\n const mux = setupMultiplex(envStream, `Job: \"${jobId}\"`);\n const commandStream = mux.createStream(SNAP_STREAM_NAMES.COMMAND);\n\n // Handle out-of-band errors, i.e. errors thrown from the snap outside of the req/res cycle.\n // Also keep track of outbound request/responses\n const notificationHandler = (\n message:\n | JsonRpcRequest\n | JsonRpcNotification<Json[] | Record<string, Json>>,\n ) => {\n if (!isJsonRpcNotification(message)) {\n return;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const snapId = this.#jobToSnapMap.get(jobId)!;\n if (message.method === 'OutboundRequest') {\n this.#messenger.publish('ExecutionService:outboundRequest', snapId);\n } else if (message.method === 'OutboundResponse') {\n this.#messenger.publish('ExecutionService:outboundResponse', snapId);\n } else if (message.method === 'UnhandledError') {\n if (isObject(message.params) && message.params.error) {\n this.#messenger.publish(\n 'ExecutionService:unhandledError',\n snapId,\n message.params.error as SnapErrorJson,\n );\n commandStream.removeListener('data', notificationHandler);\n } else {\n logError(\n new Error(\n `Received malformed \"${message.method}\" command stream notification.`,\n ),\n );\n }\n } else {\n logError(\n new Error(\n `Received unexpected command stream notification \"${message.method}\".`,\n ),\n );\n }\n };\n\n commandStream.on('data', notificationHandler);\n const rpcStream = mux.createStream(SNAP_STREAM_NAMES.JSON_RPC);\n\n // Typecast: stream type mismatch\n return {\n streams: {\n command: commandStream,\n rpc: rpcStream,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n _connection: envStream,\n },\n worker,\n };\n }\n\n /**\n * Abstract function implemented by implementing class that spins up a new worker for a job.\n *\n * Depending on the execution environment, this may run forever if the Snap fails to start up properly, therefore any call to this function should be wrapped in a timeout.\n */\n protected abstract initEnvStream(jobId: string): Promise<{\n worker: WorkerType;\n stream: BasePostMessageStream;\n }>;\n\n /**\n * Terminates the Snap with the specified ID. May throw an error if\n * termination unexpectedly fails, but will not fail if no job for the snap\n * with the specified ID is found.\n *\n * @param snapId - The ID of the snap to terminate.\n */\n async terminateSnap(snapId: string) {\n const jobId = this.#snapToJobMap.get(snapId);\n if (jobId) {\n await this.terminate(jobId);\n }\n }\n\n async terminateAllSnaps() {\n await Promise.all(\n [...this.jobs.keys()].map(async (jobId) => this.terminate(jobId)),\n );\n this.#snapRpcHooks.clear();\n }\n\n /**\n * Gets the RPC request handler for the given snap.\n *\n * @param snapId - The id of the Snap whose message handler to get.\n * @returns The RPC request handler for the snap.\n */\n private getRpcRequestHandler(snapId: string) {\n return this.#snapRpcHooks.get(snapId);\n }\n\n /**\n * Initializes and executes a snap, setting up the communication channels to the snap etc.\n *\n * @param snapData - Data needed for Snap execution.\n * @param snapData.snapId - The ID of the Snap to execute.\n * @param snapData.sourceCode - The source code of the Snap to execute.\n * @param snapData.endowments - The endowments available to the executing Snap.\n * @returns A string `OK` if execution succeeded.\n * @throws If the execution service returns an error or execution times out.\n */\n async executeSnap({\n snapId,\n sourceCode,\n endowments,\n }: SnapExecutionData): Promise<string> {\n if (this.#snapToJobMap.has(snapId)) {\n throw new Error(`Snap \"${snapId}\" is already being executed.`);\n }\n\n const jobId = nanoid();\n const timer = new Timer(this.#initTimeout);\n\n // This may resolve even if the environment has failed to start up fully\n const job = await this.initJob(jobId, timer);\n\n this.#mapSnapAndJob(snapId, job.id);\n\n // Certain environments use ping as part of their initialization and thus can skip it here\n if (this.#usePing) {\n // Ping the worker to ensure that it started up\n const pingResult = await withTimeout(\n this.command(job.id, {\n jsonrpc: '2.0',\n method: 'ping',\n id: nanoid(),\n }),\n this.#pingTimeout,\n );\n\n if (pingResult === hasTimedOut) {\n throw new Error('The Snaps execution environment failed to start.');\n }\n }\n\n const rpcStream = job.streams.rpc;\n\n this.setupSnapProvider(snapId, rpcStream);\n\n const remainingTime = timer.remaining;\n\n const result = await withTimeout(\n this.command(job.id, {\n jsonrpc: '2.0',\n method: 'executeSnap',\n params: { snapId, sourceCode, endowments },\n id: nanoid(),\n }),\n remainingTime,\n );\n\n if (result === hasTimedOut) {\n throw new Error(`${snapId} failed to start.`);\n }\n\n this.#createSnapHooks(snapId, job.id);\n return result as string;\n }\n\n // Cannot be hash private yet because of tests.\n private async command(\n jobId: string,\n message: JsonRpcRequest,\n ): Promise<Json | undefined> {\n assertIsJsonRpcRequest(message);\n\n const job = this.jobs.get(jobId);\n if (!job) {\n throw new Error(`Job with id \"${jobId}\" not found.`);\n }\n\n log('Parent: Sending Command', message);\n // eslint is blocking `await` usage even though `handle` overload returns a promise.\n // eslint-disable-next-line @typescript-eslint/await-thenable\n const response = await job.rpcEngine.handle(message);\n\n if (isJsonRpcFailure(response)) {\n throw new JsonRpcError(\n response.error.code,\n response.error.message,\n response.error.data,\n );\n }\n\n return response.result;\n }\n\n #removeSnapHooks(snapId: string) {\n this.#snapRpcHooks.delete(snapId);\n }\n\n #createSnapHooks(snapId: string, workerId: string) {\n const rpcHook = async ({ origin, handler, request }: SnapRpcHookArgs) => {\n return await this.command(workerId, {\n id: nanoid(),\n jsonrpc: '2.0',\n method: 'snapRpc',\n params: {\n origin,\n handler,\n request: request as JsonRpcRequest,\n target: snapId,\n },\n });\n };\n\n this.#snapRpcHooks.set(snapId, rpcHook);\n }\n\n #mapSnapAndJob(snapId: string, jobId: string): void {\n this.#snapToJobMap.set(snapId, jobId);\n this.#jobToSnapMap.set(jobId, snapId);\n }\n\n #removeSnapAndJobMapping(jobId: string): void {\n const snapId = this.#jobToSnapMap.get(jobId);\n if (!snapId) {\n throw new Error(`job: \"${jobId}\" has no mapped snap.`);\n }\n\n this.#jobToSnapMap.delete(jobId);\n this.#snapToJobMap.delete(snapId);\n this.#removeSnapHooks(snapId);\n }\n\n /**\n * Handle RPC request.\n *\n * @param snapId - The ID of the recipient snap.\n * @param options - Bag of options to pass to the RPC handler.\n * @returns Promise that can handle the request.\n */\n public async handleRpcRequest(\n snapId: string,\n options: SnapRpcHookArgs,\n ): Promise<unknown> {\n const rpcRequestHandler = this.getRpcRequestHandler(snapId);\n\n if (!rpcRequestHandler) {\n throw new Error(\n `Snap execution service returned no RPC handler for running snap \"${snapId}\".`,\n );\n }\n\n return rpcRequestHandler(options);\n }\n}\n\n/**\n * Sets up stream multiplexing for the given stream.\n *\n * @param connectionStream - The stream to mux.\n * @param streamName - The name of the stream, for identification in errors.\n * @returns The multiplexed stream.\n */\nexport function setupMultiplex(\n connectionStream: Duplex,\n streamName: string,\n): ObjectMultiplex {\n const mux = new ObjectMultiplex();\n pipeline(connectionStream, mux, connectionStream, (error) => {\n if (error) {\n streamName\n ? logError(`\"${streamName}\" stream failure.`, error)\n : logError(error);\n }\n });\n return mux;\n}\n"]}
@@ -1,4 +1,16 @@
1
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 _ProxyPostMessageStream_instances, _ProxyPostMessageStream_stream, _ProxyPostMessageStream_jobId, _ProxyPostMessageStream_onData;
2
14
  Object.defineProperty(exports, "__esModule", { value: true });
3
15
  exports.ProxyPostMessageStream = void 0;
4
16
  const post_message_stream_1 = require("@metamask/post-message-stream");
@@ -7,8 +19,6 @@ const post_message_stream_1 = require("@metamask/post-message-stream");
7
19
  * over the underlying stream.
8
20
  */
9
21
  class ProxyPostMessageStream extends post_message_stream_1.BasePostMessageStream {
10
- #stream;
11
- #jobId;
12
22
  /**
13
23
  * Initializes a new `ProxyPostMessageStream` instance.
14
24
  *
@@ -18,21 +28,12 @@ class ProxyPostMessageStream extends post_message_stream_1.BasePostMessageStream
18
28
  */
19
29
  constructor({ stream, jobId }) {
20
30
  super();
21
- this.#stream = stream;
22
- this.#jobId = jobId;
23
- this.#stream.on('data', this.#onData.bind(this));
24
- }
25
- /**
26
- * Handle incoming data from the underlying stream. This checks that the job
27
- * ID matches the expected job ID, and pushes the data to the stream if so.
28
- *
29
- * @param data - The data to handle.
30
- */
31
- #onData(data) {
32
- if (data.jobId !== this.#jobId) {
33
- return;
34
- }
35
- this.push(data.data);
31
+ _ProxyPostMessageStream_instances.add(this);
32
+ _ProxyPostMessageStream_stream.set(this, void 0);
33
+ _ProxyPostMessageStream_jobId.set(this, void 0);
34
+ __classPrivateFieldSet(this, _ProxyPostMessageStream_stream, stream, "f");
35
+ __classPrivateFieldSet(this, _ProxyPostMessageStream_jobId, jobId, "f");
36
+ __classPrivateFieldGet(this, _ProxyPostMessageStream_stream, "f").on('data', __classPrivateFieldGet(this, _ProxyPostMessageStream_instances, "m", _ProxyPostMessageStream_onData).bind(this));
36
37
  }
37
38
  /**
38
39
  * Write data to the underlying stream. This wraps the data in an object with
@@ -41,11 +42,17 @@ class ProxyPostMessageStream extends post_message_stream_1.BasePostMessageStream
41
42
  * @param data - The data to write.
42
43
  */
43
44
  _postMessage(data) {
44
- this.#stream.write({
45
- jobId: this.#jobId,
45
+ __classPrivateFieldGet(this, _ProxyPostMessageStream_stream, "f").write({
46
+ jobId: __classPrivateFieldGet(this, _ProxyPostMessageStream_jobId, "f"),
46
47
  data,
47
48
  });
48
49
  }
49
50
  }
50
51
  exports.ProxyPostMessageStream = ProxyPostMessageStream;
52
+ _ProxyPostMessageStream_stream = new WeakMap(), _ProxyPostMessageStream_jobId = new WeakMap(), _ProxyPostMessageStream_instances = new WeakSet(), _ProxyPostMessageStream_onData = function _ProxyPostMessageStream_onData(data) {
53
+ if (data.jobId !== __classPrivateFieldGet(this, _ProxyPostMessageStream_jobId, "f")) {
54
+ return;
55
+ }
56
+ this.push(data.data);
57
+ };
51
58
  //# sourceMappingURL=ProxyPostMessageStream.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"ProxyPostMessageStream.cjs","sourceRoot":"","sources":["../../src/services/ProxyPostMessageStream.ts"],"names":[],"mappings":";;;AAAA,uEAAsE;AAetE;;;GAGG;AACH,MAAa,sBAAuB,SAAQ,2CAAqB;IACtD,OAAO,CAAwB;IAE/B,MAAM,CAAS;IAExB;;;;;;OAMG;IACH,YAAY,EAAE,MAAM,EAAE,KAAK,EAA8B;QACvD,KAAK,EAAE,CAAC;QAER,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC;QACtB,IAAI,CAAC,MAAM,GAAG,KAAK,CAAC;QAEpB,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,MAAM,EAAE,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;IACnD,CAAC;IAED;;;;;OAKG;IACH,OAAO,CAAC,IAAsB;QAC5B,IAAI,IAAI,CAAC,KAAK,KAAK,IAAI,CAAC,MAAM,EAAE,CAAC;YAC/B,OAAO;QACT,CAAC;QAED,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACvB,CAAC;IAED;;;;;OAKG;IACH,YAAY,CAAC,IAAsB;QACjC,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC;YACjB,KAAK,EAAE,IAAI,CAAC,MAAM;YAClB,IAAI;SACL,CAAC,CAAC;IACL,CAAC;CACF;AA/CD,wDA+CC","sourcesContent":["import { BasePostMessageStream } from '@metamask/post-message-stream';\nimport type { JsonRpcRequest } from '@metamask/utils';\n\nexport type ProxyPostMessageStreamArgs = {\n stream: BasePostMessageStream;\n jobId: string;\n extra?: Record<string, unknown>;\n};\n\nexport type ProxyPostMessage = {\n jobId: string;\n data: JsonRpcRequest;\n extra?: Record<string, unknown>;\n};\n\n/**\n * A post message stream that wraps messages in a job ID, before sending them\n * over the underlying stream.\n */\nexport class ProxyPostMessageStream extends BasePostMessageStream {\n readonly #stream: BasePostMessageStream;\n\n readonly #jobId: string;\n\n /**\n * Initializes a new `ProxyPostMessageStream` instance.\n *\n * @param args - The constructor arguments.\n * @param args.stream - The underlying stream to use for communication.\n * @param args.jobId - The ID of the job this stream is associated with.\n */\n constructor({ stream, jobId }: ProxyPostMessageStreamArgs) {\n super();\n\n this.#stream = stream;\n this.#jobId = jobId;\n\n this.#stream.on('data', this.#onData.bind(this));\n }\n\n /**\n * Handle incoming data from the underlying stream. This checks that the job\n * ID matches the expected job ID, and pushes the data to the stream if so.\n *\n * @param data - The data to handle.\n */\n #onData(data: ProxyPostMessage) {\n if (data.jobId !== this.#jobId) {\n return;\n }\n\n this.push(data.data);\n }\n\n /**\n * Write data to the underlying stream. This wraps the data in an object with\n * the job ID.\n *\n * @param data - The data to write.\n */\n _postMessage(data: ProxyPostMessage) {\n this.#stream.write({\n jobId: this.#jobId,\n data,\n });\n }\n}\n"]}
1
+ {"version":3,"file":"ProxyPostMessageStream.cjs","sourceRoot":"","sources":["../../src/services/ProxyPostMessageStream.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,uEAAsE;AAetE;;;GAGG;AACH,MAAa,sBAAuB,SAAQ,2CAAqB;IAK/D;;;;;;OAMG;IACH,YAAY,EAAE,MAAM,EAAE,KAAK,EAA8B;QACvD,KAAK,EAAE,CAAC;;QAZD,iDAA+B;QAE/B,gDAAe;QAYtB,uBAAA,IAAI,kCAAW,MAAM,MAAA,CAAC;QACtB,uBAAA,IAAI,iCAAU,KAAK,MAAA,CAAC;QAEpB,uBAAA,IAAI,sCAAQ,CAAC,EAAE,CAAC,MAAM,EAAE,uBAAA,IAAI,yEAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;IACnD,CAAC;IAgBD;;;;;OAKG;IACH,YAAY,CAAC,IAAsB;QACjC,uBAAA,IAAI,sCAAQ,CAAC,KAAK,CAAC;YACjB,KAAK,EAAE,uBAAA,IAAI,qCAAO;YAClB,IAAI;SACL,CAAC,CAAC;IACL,CAAC;CACF;AA/CD,wDA+CC;2NApBS,IAAsB;IAC5B,IAAI,IAAI,CAAC,KAAK,KAAK,uBAAA,IAAI,qCAAO,EAAE,CAAC;QAC/B,OAAO;IACT,CAAC;IAED,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AACvB,CAAC","sourcesContent":["import { BasePostMessageStream } from '@metamask/post-message-stream';\nimport type { JsonRpcRequest } from '@metamask/utils';\n\nexport type ProxyPostMessageStreamArgs = {\n stream: BasePostMessageStream;\n jobId: string;\n extra?: Record<string, unknown>;\n};\n\nexport type ProxyPostMessage = {\n jobId: string;\n data: JsonRpcRequest;\n extra?: Record<string, unknown>;\n};\n\n/**\n * A post message stream that wraps messages in a job ID, before sending them\n * over the underlying stream.\n */\nexport class ProxyPostMessageStream extends BasePostMessageStream {\n readonly #stream: BasePostMessageStream;\n\n readonly #jobId: string;\n\n /**\n * Initializes a new `ProxyPostMessageStream` instance.\n *\n * @param args - The constructor arguments.\n * @param args.stream - The underlying stream to use for communication.\n * @param args.jobId - The ID of the job this stream is associated with.\n */\n constructor({ stream, jobId }: ProxyPostMessageStreamArgs) {\n super();\n\n this.#stream = stream;\n this.#jobId = jobId;\n\n this.#stream.on('data', this.#onData.bind(this));\n }\n\n /**\n * Handle incoming data from the underlying stream. This checks that the job\n * ID matches the expected job ID, and pushes the data to the stream if so.\n *\n * @param data - The data to handle.\n */\n #onData(data: ProxyPostMessage) {\n if (data.jobId !== this.#jobId) {\n return;\n }\n\n this.push(data.data);\n }\n\n /**\n * Write data to the underlying stream. This wraps the data in an object with\n * the job ID.\n *\n * @param data - The data to write.\n */\n _postMessage(data: ProxyPostMessage) {\n this.#stream.write({\n jobId: this.#jobId,\n data,\n });\n }\n}\n"]}
@@ -1,3 +1,15 @@
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 _ProxyPostMessageStream_instances, _ProxyPostMessageStream_stream, _ProxyPostMessageStream_jobId, _ProxyPostMessageStream_onData;
1
13
  import $metamaskpostmessagestream from "@metamask/post-message-stream";
2
14
  const { BasePostMessageStream } = $metamaskpostmessagestream;
3
15
  /**
@@ -5,8 +17,6 @@ const { BasePostMessageStream } = $metamaskpostmessagestream;
5
17
  * over the underlying stream.
6
18
  */
7
19
  export class ProxyPostMessageStream extends BasePostMessageStream {
8
- #stream;
9
- #jobId;
10
20
  /**
11
21
  * Initializes a new `ProxyPostMessageStream` instance.
12
22
  *
@@ -16,21 +26,12 @@ export class ProxyPostMessageStream extends BasePostMessageStream {
16
26
  */
17
27
  constructor({ stream, jobId }) {
18
28
  super();
19
- this.#stream = stream;
20
- this.#jobId = jobId;
21
- this.#stream.on('data', this.#onData.bind(this));
22
- }
23
- /**
24
- * Handle incoming data from the underlying stream. This checks that the job
25
- * ID matches the expected job ID, and pushes the data to the stream if so.
26
- *
27
- * @param data - The data to handle.
28
- */
29
- #onData(data) {
30
- if (data.jobId !== this.#jobId) {
31
- return;
32
- }
33
- this.push(data.data);
29
+ _ProxyPostMessageStream_instances.add(this);
30
+ _ProxyPostMessageStream_stream.set(this, void 0);
31
+ _ProxyPostMessageStream_jobId.set(this, void 0);
32
+ __classPrivateFieldSet(this, _ProxyPostMessageStream_stream, stream, "f");
33
+ __classPrivateFieldSet(this, _ProxyPostMessageStream_jobId, jobId, "f");
34
+ __classPrivateFieldGet(this, _ProxyPostMessageStream_stream, "f").on('data', __classPrivateFieldGet(this, _ProxyPostMessageStream_instances, "m", _ProxyPostMessageStream_onData).bind(this));
34
35
  }
35
36
  /**
36
37
  * Write data to the underlying stream. This wraps the data in an object with
@@ -39,10 +40,16 @@ export class ProxyPostMessageStream extends BasePostMessageStream {
39
40
  * @param data - The data to write.
40
41
  */
41
42
  _postMessage(data) {
42
- this.#stream.write({
43
- jobId: this.#jobId,
43
+ __classPrivateFieldGet(this, _ProxyPostMessageStream_stream, "f").write({
44
+ jobId: __classPrivateFieldGet(this, _ProxyPostMessageStream_jobId, "f"),
44
45
  data,
45
46
  });
46
47
  }
47
48
  }
49
+ _ProxyPostMessageStream_stream = new WeakMap(), _ProxyPostMessageStream_jobId = new WeakMap(), _ProxyPostMessageStream_instances = new WeakSet(), _ProxyPostMessageStream_onData = function _ProxyPostMessageStream_onData(data) {
50
+ if (data.jobId !== __classPrivateFieldGet(this, _ProxyPostMessageStream_jobId, "f")) {
51
+ return;
52
+ }
53
+ this.push(data.data);
54
+ };
48
55
  //# sourceMappingURL=ProxyPostMessageStream.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"ProxyPostMessageStream.mjs","sourceRoot":"","sources":["../../src/services/ProxyPostMessageStream.ts"],"names":[],"mappings":";;AAeA;;;GAGG;AACH,MAAM,OAAO,sBAAuB,SAAQ,qBAAqB;IACtD,OAAO,CAAwB;IAE/B,MAAM,CAAS;IAExB;;;;;;OAMG;IACH,YAAY,EAAE,MAAM,EAAE,KAAK,EAA8B;QACvD,KAAK,EAAE,CAAC;QAER,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC;QACtB,IAAI,CAAC,MAAM,GAAG,KAAK,CAAC;QAEpB,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,MAAM,EAAE,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;IACnD,CAAC;IAED;;;;;OAKG;IACH,OAAO,CAAC,IAAsB;QAC5B,IAAI,IAAI,CAAC,KAAK,KAAK,IAAI,CAAC,MAAM,EAAE,CAAC;YAC/B,OAAO;QACT,CAAC;QAED,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACvB,CAAC;IAED;;;;;OAKG;IACH,YAAY,CAAC,IAAsB;QACjC,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC;YACjB,KAAK,EAAE,IAAI,CAAC,MAAM;YAClB,IAAI;SACL,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["import { BasePostMessageStream } from '@metamask/post-message-stream';\nimport type { JsonRpcRequest } from '@metamask/utils';\n\nexport type ProxyPostMessageStreamArgs = {\n stream: BasePostMessageStream;\n jobId: string;\n extra?: Record<string, unknown>;\n};\n\nexport type ProxyPostMessage = {\n jobId: string;\n data: JsonRpcRequest;\n extra?: Record<string, unknown>;\n};\n\n/**\n * A post message stream that wraps messages in a job ID, before sending them\n * over the underlying stream.\n */\nexport class ProxyPostMessageStream extends BasePostMessageStream {\n readonly #stream: BasePostMessageStream;\n\n readonly #jobId: string;\n\n /**\n * Initializes a new `ProxyPostMessageStream` instance.\n *\n * @param args - The constructor arguments.\n * @param args.stream - The underlying stream to use for communication.\n * @param args.jobId - The ID of the job this stream is associated with.\n */\n constructor({ stream, jobId }: ProxyPostMessageStreamArgs) {\n super();\n\n this.#stream = stream;\n this.#jobId = jobId;\n\n this.#stream.on('data', this.#onData.bind(this));\n }\n\n /**\n * Handle incoming data from the underlying stream. This checks that the job\n * ID matches the expected job ID, and pushes the data to the stream if so.\n *\n * @param data - The data to handle.\n */\n #onData(data: ProxyPostMessage) {\n if (data.jobId !== this.#jobId) {\n return;\n }\n\n this.push(data.data);\n }\n\n /**\n * Write data to the underlying stream. This wraps the data in an object with\n * the job ID.\n *\n * @param data - The data to write.\n */\n _postMessage(data: ProxyPostMessage) {\n this.#stream.write({\n jobId: this.#jobId,\n data,\n });\n }\n}\n"]}
1
+ {"version":3,"file":"ProxyPostMessageStream.mjs","sourceRoot":"","sources":["../../src/services/ProxyPostMessageStream.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AAeA;;;GAGG;AACH,MAAM,OAAO,sBAAuB,SAAQ,qBAAqB;IAK/D;;;;;;OAMG;IACH,YAAY,EAAE,MAAM,EAAE,KAAK,EAA8B;QACvD,KAAK,EAAE,CAAC;;QAZD,iDAA+B;QAE/B,gDAAe;QAYtB,uBAAA,IAAI,kCAAW,MAAM,MAAA,CAAC;QACtB,uBAAA,IAAI,iCAAU,KAAK,MAAA,CAAC;QAEpB,uBAAA,IAAI,sCAAQ,CAAC,EAAE,CAAC,MAAM,EAAE,uBAAA,IAAI,yEAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;IACnD,CAAC;IAgBD;;;;;OAKG;IACH,YAAY,CAAC,IAAsB;QACjC,uBAAA,IAAI,sCAAQ,CAAC,KAAK,CAAC;YACjB,KAAK,EAAE,uBAAA,IAAI,qCAAO;YAClB,IAAI;SACL,CAAC,CAAC;IACL,CAAC;CACF;2NApBS,IAAsB;IAC5B,IAAI,IAAI,CAAC,KAAK,KAAK,uBAAA,IAAI,qCAAO,EAAE,CAAC;QAC/B,OAAO;IACT,CAAC;IAED,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AACvB,CAAC","sourcesContent":["import { BasePostMessageStream } from '@metamask/post-message-stream';\nimport type { JsonRpcRequest } from '@metamask/utils';\n\nexport type ProxyPostMessageStreamArgs = {\n stream: BasePostMessageStream;\n jobId: string;\n extra?: Record<string, unknown>;\n};\n\nexport type ProxyPostMessage = {\n jobId: string;\n data: JsonRpcRequest;\n extra?: Record<string, unknown>;\n};\n\n/**\n * A post message stream that wraps messages in a job ID, before sending them\n * over the underlying stream.\n */\nexport class ProxyPostMessageStream extends BasePostMessageStream {\n readonly #stream: BasePostMessageStream;\n\n readonly #jobId: string;\n\n /**\n * Initializes a new `ProxyPostMessageStream` instance.\n *\n * @param args - The constructor arguments.\n * @param args.stream - The underlying stream to use for communication.\n * @param args.jobId - The ID of the job this stream is associated with.\n */\n constructor({ stream, jobId }: ProxyPostMessageStreamArgs) {\n super();\n\n this.#stream = stream;\n this.#jobId = jobId;\n\n this.#stream.on('data', this.#onData.bind(this));\n }\n\n /**\n * Handle incoming data from the underlying stream. This checks that the job\n * ID matches the expected job ID, and pushes the data to the stream if so.\n *\n * @param data - The data to handle.\n */\n #onData(data: ProxyPostMessage) {\n if (data.jobId !== this.#jobId) {\n return;\n }\n\n this.push(data.data);\n }\n\n /**\n * Write data to the underlying stream. This wraps the data in an object with\n * the job ID.\n *\n * @param data - The data to write.\n */\n _postMessage(data: ProxyPostMessage) {\n this.#stream.write({\n jobId: this.#jobId,\n data,\n });\n }\n}\n"]}
@@ -5,7 +5,6 @@ const post_message_stream_1 = require("@metamask/post-message-stream");
5
5
  const snaps_utils_1 = require("@metamask/snaps-utils");
6
6
  const AbstractExecutionService_1 = require("../AbstractExecutionService.cjs");
7
7
  class IframeExecutionService extends AbstractExecutionService_1.AbstractExecutionService {
8
- iframeUrl;
9
8
  constructor({ iframeUrl, messenger, setupSnapProvider, }) {
10
9
  super({
11
10
  messenger,
@@ -17,7 +16,10 @@ class IframeExecutionService extends AbstractExecutionService_1.AbstractExecutio
17
16
  document.getElementById(jobWrapper.id)?.remove();
18
17
  }
19
18
  async initEnvStream(jobId) {
20
- const iframeWindow = await (0, snaps_utils_1.createWindow)(this.iframeUrl.toString(), jobId);
19
+ const iframeWindow = await (0, snaps_utils_1.createWindow)({
20
+ uri: this.iframeUrl.toString(),
21
+ id: jobId,
22
+ });
21
23
  const stream = new post_message_stream_1.WindowPostMessageStream({
22
24
  name: 'parent',
23
25
  target: 'child',
@@ -1 +1 @@
1
- {"version":3,"file":"IframeExecutionService.cjs","sourceRoot":"","sources":["../../../src/services/iframe/IframeExecutionService.ts"],"names":[],"mappings":";;;AACA,uEAAwE;AACxE,uDAAqD;AAMrD,8EAAuE;AAMvE,MAAa,sBAAuB,SAAQ,mDAAgC;IACnE,SAAS,CAAM;IAEtB,YAAY,EACV,SAAS,EACT,SAAS,EACT,iBAAiB,GACqB;QACtC,KAAK,CAAC;YACJ,SAAS;YACT,iBAAiB;SAClB,CAAC,CAAC;QACH,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;IAC7B,CAAC;IAES,YAAY,CAAC,UAAoC;QACzD,QAAQ,CAAC,cAAc,CAAC,UAAU,CAAC,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC;IACnD,CAAC;IAES,KAAK,CAAC,aAAa,CAAC,KAAa;QAIzC,MAAM,YAAY,GAAG,MAAM,IAAA,0BAAY,EAAC,IAAI,CAAC,SAAS,CAAC,QAAQ,EAAE,EAAE,KAAK,CAAC,CAAC;QAE1E,MAAM,MAAM,GAAG,IAAI,6CAAuB,CAAC;YACzC,IAAI,EAAE,QAAQ;YACd,MAAM,EAAE,OAAO;YACf,YAAY,EAAE,YAAY;YAC1B,YAAY,EAAE,GAAG;SAClB,CAAC,CAAC;QAEH,OAAO,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,EAAE,CAAC;IAC1C,CAAC;CACF;AAlCD,wDAkCC","sourcesContent":["import type { BasePostMessageStream } from '@metamask/post-message-stream';\nimport { WindowPostMessageStream } from '@metamask/post-message-stream';\nimport { createWindow } from '@metamask/snaps-utils';\n\nimport type {\n ExecutionServiceArgs,\n TerminateJobArgs,\n} from '../AbstractExecutionService';\nimport { AbstractExecutionService } from '../AbstractExecutionService';\n\ntype IframeExecutionEnvironmentServiceArgs = {\n iframeUrl: URL;\n} & ExecutionServiceArgs;\n\nexport class IframeExecutionService extends AbstractExecutionService<Window> {\n public iframeUrl: URL;\n\n constructor({\n iframeUrl,\n messenger,\n setupSnapProvider,\n }: IframeExecutionEnvironmentServiceArgs) {\n super({\n messenger,\n setupSnapProvider,\n });\n this.iframeUrl = iframeUrl;\n }\n\n protected terminateJob(jobWrapper: TerminateJobArgs<Window>): void {\n document.getElementById(jobWrapper.id)?.remove();\n }\n\n protected async initEnvStream(jobId: string): Promise<{\n worker: Window;\n stream: BasePostMessageStream;\n }> {\n const iframeWindow = await createWindow(this.iframeUrl.toString(), jobId);\n\n const stream = new WindowPostMessageStream({\n name: 'parent',\n target: 'child',\n targetWindow: iframeWindow,\n targetOrigin: '*',\n });\n\n return { worker: iframeWindow, stream };\n }\n}\n"]}
1
+ {"version":3,"file":"IframeExecutionService.cjs","sourceRoot":"","sources":["../../../src/services/iframe/IframeExecutionService.ts"],"names":[],"mappings":";;;AACA,uEAAwE;AACxE,uDAAqD;AAMrD,8EAAuE;AAMvE,MAAa,sBAAuB,SAAQ,mDAAgC;IAG1E,YAAY,EACV,SAAS,EACT,SAAS,EACT,iBAAiB,GACqB;QACtC,KAAK,CAAC;YACJ,SAAS;YACT,iBAAiB;SAClB,CAAC,CAAC;QACH,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;IAC7B,CAAC;IAES,YAAY,CAAC,UAAoC;QACzD,QAAQ,CAAC,cAAc,CAAC,UAAU,CAAC,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC;IACnD,CAAC;IAES,KAAK,CAAC,aAAa,CAAC,KAAa;QAIzC,MAAM,YAAY,GAAG,MAAM,IAAA,0BAAY,EAAC;YACtC,GAAG,EAAE,IAAI,CAAC,SAAS,CAAC,QAAQ,EAAE;YAC9B,EAAE,EAAE,KAAK;SACV,CAAC,CAAC;QAEH,MAAM,MAAM,GAAG,IAAI,6CAAuB,CAAC;YACzC,IAAI,EAAE,QAAQ;YACd,MAAM,EAAE,OAAO;YACf,YAAY,EAAE,YAAY;YAC1B,YAAY,EAAE,GAAG;SAClB,CAAC,CAAC;QAEH,OAAO,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,EAAE,CAAC;IAC1C,CAAC;CACF;AArCD,wDAqCC","sourcesContent":["import type { BasePostMessageStream } from '@metamask/post-message-stream';\nimport { WindowPostMessageStream } from '@metamask/post-message-stream';\nimport { createWindow } from '@metamask/snaps-utils';\n\nimport type {\n ExecutionServiceArgs,\n TerminateJobArgs,\n} from '../AbstractExecutionService';\nimport { AbstractExecutionService } from '../AbstractExecutionService';\n\ntype IframeExecutionEnvironmentServiceArgs = {\n iframeUrl: URL;\n} & ExecutionServiceArgs;\n\nexport class IframeExecutionService extends AbstractExecutionService<Window> {\n public iframeUrl: URL;\n\n constructor({\n iframeUrl,\n messenger,\n setupSnapProvider,\n }: IframeExecutionEnvironmentServiceArgs) {\n super({\n messenger,\n setupSnapProvider,\n });\n this.iframeUrl = iframeUrl;\n }\n\n protected terminateJob(jobWrapper: TerminateJobArgs<Window>): void {\n document.getElementById(jobWrapper.id)?.remove();\n }\n\n protected async initEnvStream(jobId: string): Promise<{\n worker: Window;\n stream: BasePostMessageStream;\n }> {\n const iframeWindow = await createWindow({\n uri: this.iframeUrl.toString(),\n id: jobId,\n });\n\n const stream = new WindowPostMessageStream({\n name: 'parent',\n target: 'child',\n targetWindow: iframeWindow,\n targetOrigin: '*',\n });\n\n return { worker: iframeWindow, stream };\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"IframeExecutionService.d.cts","sourceRoot":"","sources":["../../../src/services/iframe/IframeExecutionService.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,qBAAqB,EAAE,sCAAsC;AAI3E,OAAO,KAAK,EACV,oBAAoB,EACpB,gBAAgB,EACjB,wCAAoC;AACrC,OAAO,EAAE,wBAAwB,EAAE,wCAAoC;AAEvE,KAAK,qCAAqC,GAAG;IAC3C,SAAS,EAAE,GAAG,CAAC;CAChB,GAAG,oBAAoB,CAAC;AAEzB,qBAAa,sBAAuB,SAAQ,wBAAwB,CAAC,MAAM,CAAC;IACnE,SAAS,EAAE,GAAG,CAAC;gBAEV,EACV,SAAS,EACT,SAAS,EACT,iBAAiB,GAClB,EAAE,qCAAqC;IAQxC,SAAS,CAAC,YAAY,CAAC,UAAU,EAAE,gBAAgB,CAAC,MAAM,CAAC,GAAG,IAAI;cAIlD,aAAa,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC;QACpD,MAAM,EAAE,MAAM,CAAC;QACf,MAAM,EAAE,qBAAqB,CAAC;KAC/B,CAAC;CAYH"}
1
+ {"version":3,"file":"IframeExecutionService.d.cts","sourceRoot":"","sources":["../../../src/services/iframe/IframeExecutionService.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,qBAAqB,EAAE,sCAAsC;AAI3E,OAAO,KAAK,EACV,oBAAoB,EACpB,gBAAgB,EACjB,wCAAoC;AACrC,OAAO,EAAE,wBAAwB,EAAE,wCAAoC;AAEvE,KAAK,qCAAqC,GAAG;IAC3C,SAAS,EAAE,GAAG,CAAC;CAChB,GAAG,oBAAoB,CAAC;AAEzB,qBAAa,sBAAuB,SAAQ,wBAAwB,CAAC,MAAM,CAAC;IACnE,SAAS,EAAE,GAAG,CAAC;gBAEV,EACV,SAAS,EACT,SAAS,EACT,iBAAiB,GAClB,EAAE,qCAAqC;IAQxC,SAAS,CAAC,YAAY,CAAC,UAAU,EAAE,gBAAgB,CAAC,MAAM,CAAC,GAAG,IAAI;cAIlD,aAAa,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC;QACpD,MAAM,EAAE,MAAM,CAAC;QACf,MAAM,EAAE,qBAAqB,CAAC;KAC/B,CAAC;CAeH"}
@@ -1 +1 @@
1
- {"version":3,"file":"IframeExecutionService.d.mts","sourceRoot":"","sources":["../../../src/services/iframe/IframeExecutionService.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,qBAAqB,EAAE,sCAAsC;AAI3E,OAAO,KAAK,EACV,oBAAoB,EACpB,gBAAgB,EACjB,wCAAoC;AACrC,OAAO,EAAE,wBAAwB,EAAE,wCAAoC;AAEvE,KAAK,qCAAqC,GAAG;IAC3C,SAAS,EAAE,GAAG,CAAC;CAChB,GAAG,oBAAoB,CAAC;AAEzB,qBAAa,sBAAuB,SAAQ,wBAAwB,CAAC,MAAM,CAAC;IACnE,SAAS,EAAE,GAAG,CAAC;gBAEV,EACV,SAAS,EACT,SAAS,EACT,iBAAiB,GAClB,EAAE,qCAAqC;IAQxC,SAAS,CAAC,YAAY,CAAC,UAAU,EAAE,gBAAgB,CAAC,MAAM,CAAC,GAAG,IAAI;cAIlD,aAAa,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC;QACpD,MAAM,EAAE,MAAM,CAAC;QACf,MAAM,EAAE,qBAAqB,CAAC;KAC/B,CAAC;CAYH"}
1
+ {"version":3,"file":"IframeExecutionService.d.mts","sourceRoot":"","sources":["../../../src/services/iframe/IframeExecutionService.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,qBAAqB,EAAE,sCAAsC;AAI3E,OAAO,KAAK,EACV,oBAAoB,EACpB,gBAAgB,EACjB,wCAAoC;AACrC,OAAO,EAAE,wBAAwB,EAAE,wCAAoC;AAEvE,KAAK,qCAAqC,GAAG;IAC3C,SAAS,EAAE,GAAG,CAAC;CAChB,GAAG,oBAAoB,CAAC;AAEzB,qBAAa,sBAAuB,SAAQ,wBAAwB,CAAC,MAAM,CAAC;IACnE,SAAS,EAAE,GAAG,CAAC;gBAEV,EACV,SAAS,EACT,SAAS,EACT,iBAAiB,GAClB,EAAE,qCAAqC;IAQxC,SAAS,CAAC,YAAY,CAAC,UAAU,EAAE,gBAAgB,CAAC,MAAM,CAAC,GAAG,IAAI;cAIlD,aAAa,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC;QACpD,MAAM,EAAE,MAAM,CAAC;QACf,MAAM,EAAE,qBAAqB,CAAC;KAC/B,CAAC;CAeH"}