@metamask/snaps-execution-environments 6.8.0 → 6.9.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.
@@ -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 _WebWorkerPool_instances, _WebWorkerPool_poolSize, _WebWorkerPool_stream, _WebWorkerPool_url, _WebWorkerPool_workerSourceURL, _WebWorkerPool_onData, _WebWorkerPool_initializeJob, _WebWorkerPool_terminateJob, _WebWorkerPool_getWorker, _WebWorkerPool_updatePool, _WebWorkerPool_createWorker, _WebWorkerPool_getWorkerURL;
2
14
  Object.defineProperty(exports, "__esModule", { value: true });
3
15
  exports.WebWorkerPool = void 0;
4
16
  const post_message_stream_1 = require("@metamask/post-message-stream");
@@ -14,12 +26,6 @@ const non_secure_1 = require("nanoid/non-secure");
14
26
  * executing the snap.
15
27
  */
16
28
  class WebWorkerPool {
17
- #poolSize;
18
- #stream;
19
- #url;
20
- pool = [];
21
- jobs = new Map();
22
- #workerSourceURL;
23
29
  /* istanbul ignore next - Constructor arguments. */
24
30
  static initialize(stream = new post_message_stream_1.WindowPostMessageStream({
25
31
  name: 'child',
@@ -30,142 +36,133 @@ class WebWorkerPool {
30
36
  return new WebWorkerPool(stream, url, poolSize);
31
37
  }
32
38
  constructor(stream, url, poolSize = 3) {
33
- this.#stream = stream;
34
- this.#url = url;
35
- this.#poolSize = poolSize;
36
- this.#stream.on('data', this.#onData.bind(this));
39
+ _WebWorkerPool_instances.add(this);
40
+ _WebWorkerPool_poolSize.set(this, void 0);
41
+ _WebWorkerPool_stream.set(this, void 0);
42
+ _WebWorkerPool_url.set(this, void 0);
43
+ this.pool = [];
44
+ this.jobs = new Map();
45
+ _WebWorkerPool_workerSourceURL.set(this, void 0);
46
+ __classPrivateFieldSet(this, _WebWorkerPool_stream, stream, "f");
47
+ __classPrivateFieldSet(this, _WebWorkerPool_url, url, "f");
48
+ __classPrivateFieldSet(this, _WebWorkerPool_poolSize, poolSize, "f");
49
+ __classPrivateFieldGet(this, _WebWorkerPool_stream, "f").on('data', __classPrivateFieldGet(this, _WebWorkerPool_instances, "m", _WebWorkerPool_onData).bind(this));
37
50
  }
38
- /**
39
- * Handle an incoming message from the `WebWorkerExecutionService`. This
40
- * assumes that the message contains a `jobId` property, and a JSON-RPC
41
- * request in the `data` property.
42
- *
43
- * @param data - The message data.
44
- * @param data.data - The JSON-RPC request.
45
- * @param data.jobId - The job ID.
46
- */
47
- #onData(data) {
48
- const { jobId, data: request } = data;
49
- const job = this.jobs.get(jobId);
50
- if (!job) {
51
- // This ensures that a job is initialized before it is used. To avoid
52
- // code duplication, we call the `#onData` method again, which will
53
- // run the rest of the logic after initialization.
54
- this.#initializeJob(jobId)
55
- .then(() => {
56
- this.#onData(data);
57
- })
58
- .catch((error) => {
59
- (0, snaps_utils_1.logError)('[Worker] Error initializing job:', error.toString());
60
- this.#stream.write({
61
- jobId,
51
+ }
52
+ exports.WebWorkerPool = WebWorkerPool;
53
+ _WebWorkerPool_poolSize = new WeakMap(), _WebWorkerPool_stream = new WeakMap(), _WebWorkerPool_url = new WeakMap(), _WebWorkerPool_workerSourceURL = new WeakMap(), _WebWorkerPool_instances = new WeakSet(), _WebWorkerPool_onData = function _WebWorkerPool_onData(data) {
54
+ const { jobId, data: request } = data;
55
+ const job = this.jobs.get(jobId);
56
+ if (!job) {
57
+ // This ensures that a job is initialized before it is used. To avoid
58
+ // code duplication, we call the `#onData` method again, which will
59
+ // run the rest of the logic after initialization.
60
+ __classPrivateFieldGet(this, _WebWorkerPool_instances, "m", _WebWorkerPool_initializeJob).call(this, jobId)
61
+ .then(() => {
62
+ __classPrivateFieldGet(this, _WebWorkerPool_instances, "m", _WebWorkerPool_onData).call(this, data);
63
+ })
64
+ .catch((error) => {
65
+ (0, snaps_utils_1.logError)('[Worker] Error initializing job:', error.toString());
66
+ __classPrivateFieldGet(this, _WebWorkerPool_stream, "f").write({
67
+ jobId,
68
+ data: {
69
+ name: 'command',
62
70
  data: {
63
- name: 'command',
64
- data: {
65
- jsonrpc: '2.0',
66
- id: request.id ?? null,
67
- error: {
68
- code: -32000,
69
- message: 'Internal error',
70
- },
71
+ jsonrpc: '2.0',
72
+ id: request.id ?? null,
73
+ error: {
74
+ code: -32000,
75
+ message: 'Internal error',
71
76
  },
72
77
  },
73
- });
78
+ },
74
79
  });
75
- return;
76
- }
77
- // This is a method specific to the `WebWorkerPool`, as the service itself
78
- // does not have access to the workers directly.
79
- if (request.method === 'terminateJob') {
80
- this.#terminateJob(jobId);
81
- return;
82
- }
83
- job.stream.write(request);
84
- }
85
- /**
86
- * Create a new worker and set up a stream to communicate with it.
87
- *
88
- * @param jobId - The job ID.
89
- * @returns The job.
90
- */
91
- async #initializeJob(jobId) {
92
- const worker = await this.#getWorker();
93
- const jobStream = new post_message_stream_1.WebWorkerParentPostMessageStream({
94
- worker,
95
80
  });
96
- // Write messages from the worker to the parent, wrapped with the job ID.
97
- jobStream.on('data', (data) => {
98
- this.#stream.write({ data, jobId });
99
- });
100
- const job = { id: jobId, worker, stream: jobStream };
101
- this.jobs.set(jobId, job);
102
- return job;
103
- }
104
- /**
105
- * Terminate the job with the given ID. This will close the worker and delete
106
- * the job from the internal job map.
107
- *
108
- * @param jobId - The job ID.
109
- */
110
- #terminateJob(jobId) {
111
- const job = this.jobs.get(jobId);
112
- (0, utils_1.assert)(job, `Job "${jobId}" not found.`);
113
- job.stream.destroy();
114
- job.worker.terminate();
115
- this.jobs.delete(jobId);
81
+ return;
116
82
  }
117
- /**
118
- * Get a worker from the pool. A new worker will be created automatically.
119
- *
120
- * @returns The worker.
121
- */
122
- async #getWorker() {
123
- // Lazily create the pool of workers.
124
- if (this.pool.length === 0) {
125
- await this.#updatePool();
126
- }
127
- const worker = this.pool.shift();
128
- (0, utils_1.assert)(worker, 'Worker not found.');
129
- await this.#updatePool();
130
- return worker;
83
+ // This is a method specific to the `WebWorkerPool`, as the service itself
84
+ // does not have access to the workers directly.
85
+ if (request.method === 'terminateJob') {
86
+ __classPrivateFieldGet(this, _WebWorkerPool_instances, "m", _WebWorkerPool_terminateJob).call(this, jobId);
87
+ return;
131
88
  }
132
- /**
133
- * Update the pool of workers. This will create new workers if the pool is
134
- * below the minimum size.
135
- */
136
- async #updatePool() {
137
- while (this.pool.length < this.#poolSize) {
138
- const worker = await this.#createWorker();
139
- this.pool.push(worker);
140
- }
89
+ job.stream.write(request);
90
+ }, _WebWorkerPool_initializeJob =
91
+ /**
92
+ * Create a new worker and set up a stream to communicate with it.
93
+ *
94
+ * @param jobId - The job ID.
95
+ * @returns The job.
96
+ */
97
+ async function _WebWorkerPool_initializeJob(jobId) {
98
+ const worker = await __classPrivateFieldGet(this, _WebWorkerPool_instances, "m", _WebWorkerPool_getWorker).call(this);
99
+ const jobStream = new post_message_stream_1.WebWorkerParentPostMessageStream({
100
+ worker,
101
+ });
102
+ // Write messages from the worker to the parent, wrapped with the job ID.
103
+ jobStream.on('data', (data) => {
104
+ __classPrivateFieldGet(this, _WebWorkerPool_stream, "f").write({ data, jobId });
105
+ });
106
+ const job = { id: jobId, worker, stream: jobStream };
107
+ this.jobs.set(jobId, job);
108
+ return job;
109
+ }, _WebWorkerPool_terminateJob = function _WebWorkerPool_terminateJob(jobId) {
110
+ const job = this.jobs.get(jobId);
111
+ (0, utils_1.assert)(job, `Job "${jobId}" not found.`);
112
+ job.stream.destroy();
113
+ job.worker.terminate();
114
+ this.jobs.delete(jobId);
115
+ }, _WebWorkerPool_getWorker =
116
+ /**
117
+ * Get a worker from the pool. A new worker will be created automatically.
118
+ *
119
+ * @returns The worker.
120
+ */
121
+ async function _WebWorkerPool_getWorker() {
122
+ // Lazily create the pool of workers.
123
+ if (this.pool.length === 0) {
124
+ await __classPrivateFieldGet(this, _WebWorkerPool_instances, "m", _WebWorkerPool_updatePool).call(this);
141
125
  }
142
- /**
143
- * Create a new worker. This will fetch the worker source if it has not
144
- * already been fetched.
145
- *
146
- * @returns The worker.
147
- */
148
- async #createWorker() {
149
- return new Worker(await this.#getWorkerURL(), {
150
- name: `worker-${(0, non_secure_1.nanoid)()}`,
151
- });
126
+ const worker = this.pool.shift();
127
+ (0, utils_1.assert)(worker, 'Worker not found.');
128
+ await __classPrivateFieldGet(this, _WebWorkerPool_instances, "m", _WebWorkerPool_updatePool).call(this);
129
+ return worker;
130
+ }, _WebWorkerPool_updatePool =
131
+ /**
132
+ * Update the pool of workers. This will create new workers if the pool is
133
+ * below the minimum size.
134
+ */
135
+ async function _WebWorkerPool_updatePool() {
136
+ while (this.pool.length < __classPrivateFieldGet(this, _WebWorkerPool_poolSize, "f")) {
137
+ const worker = await __classPrivateFieldGet(this, _WebWorkerPool_instances, "m", _WebWorkerPool_createWorker).call(this);
138
+ this.pool.push(worker);
152
139
  }
153
- /**
154
- * Get the URL of the worker source. This will fetch the worker source if it
155
- * has not already been fetched.
156
- *
157
- * @returns The worker source URL, as a `blob:` URL.
158
- */
159
- async #getWorkerURL() {
160
- if (this.#workerSourceURL) {
161
- return this.#workerSourceURL;
162
- }
163
- const blob = await fetch(this.#url)
164
- .then(async (response) => response.blob())
165
- .then(URL.createObjectURL.bind(URL));
166
- this.#workerSourceURL = blob;
167
- return blob;
140
+ }, _WebWorkerPool_createWorker =
141
+ /**
142
+ * Create a new worker. This will fetch the worker source if it has not
143
+ * already been fetched.
144
+ *
145
+ * @returns The worker.
146
+ */
147
+ async function _WebWorkerPool_createWorker() {
148
+ return new Worker(await __classPrivateFieldGet(this, _WebWorkerPool_instances, "m", _WebWorkerPool_getWorkerURL).call(this), {
149
+ name: `worker-${(0, non_secure_1.nanoid)()}`,
150
+ });
151
+ }, _WebWorkerPool_getWorkerURL =
152
+ /**
153
+ * Get the URL of the worker source. This will fetch the worker source if it
154
+ * has not already been fetched.
155
+ *
156
+ * @returns The worker source URL, as a `blob:` URL.
157
+ */
158
+ async function _WebWorkerPool_getWorkerURL() {
159
+ if (__classPrivateFieldGet(this, _WebWorkerPool_workerSourceURL, "f")) {
160
+ return __classPrivateFieldGet(this, _WebWorkerPool_workerSourceURL, "f");
168
161
  }
169
- }
170
- exports.WebWorkerPool = WebWorkerPool;
162
+ const blob = await fetch(__classPrivateFieldGet(this, _WebWorkerPool_url, "f"))
163
+ .then(async (response) => response.blob())
164
+ .then(URL.createObjectURL.bind(URL));
165
+ __classPrivateFieldSet(this, _WebWorkerPool_workerSourceURL, blob, "f");
166
+ return blob;
167
+ };
171
168
  //# sourceMappingURL=WebWorkerPool.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"WebWorkerPool.cjs","sourceRoot":"","sources":["../../../src/webworker/pool/WebWorkerPool.ts"],"names":[],"mappings":";;;AACA,uEAGuC;AACvC,uDAAiD;AAEjD,2CAAyC;AACzC,kDAA2C;AAQ3C;;;;;;;GAOG;AACH,MAAa,aAAa;IACf,SAAS,CAAC;IAEV,OAAO,CAAwB;IAE/B,IAAI,CAAS;IAEb,IAAI,GAAa,EAAE,CAAC;IAEpB,IAAI,GAA6B,IAAI,GAAG,EAAE,CAAC;IAEpD,gBAAgB,CAAU;IAE1B,mDAAmD;IACnD,MAAM,CAAC,UAAU,CACf,SAAgC,IAAI,6CAAuB,C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AC,IAAI,EAAE,CAAC;aACzC,IAAI,CAAC,GAAG,CAAC,eAAe,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;QAEvC,IAAI,CAAC,gBAAgB,GAAG,IAAI,CAAC;QAC7B,OAAO,IAAI,CAAC;IACd,CAAC;CACF;AA1LD,sCA0LC","sourcesContent":["import type { BasePostMessageStream } from '@metamask/post-message-stream';\nimport {\n WebWorkerParentPostMessageStream,\n WindowPostMessageStream,\n} from '@metamask/post-message-stream';\nimport { logError } from '@metamask/snaps-utils';\nimport type { JsonRpcRequest } from '@metamask/utils';\nimport { assert } from '@metamask/utils';\nimport { nanoid } from 'nanoid/non-secure';\n\ntype ExecutorJob = {\n id: string;\n worker: Worker;\n stream: WebWorkerParentPostMessageStream;\n};\n\n/**\n * A snap executor using the WebWorker API.\n *\n * This is not a traditional snap executor, as it does not execute snaps itself.\n * Instead, it creates a pool of webworkers for each snap execution, and sends\n * the snap execution request to the webworker. The webworker is responsible for\n * executing the snap.\n */\nexport class WebWorkerPool {\n readonly #poolSize;\n\n readonly #stream: BasePostMessageStream;\n\n readonly #url: string;\n\n readonly pool: Worker[] = [];\n\n readonly jobs: Map<string, ExecutorJob> = new Map();\n\n #workerSourceURL?: string;\n\n /* istanbul ignore next - Constructor arguments. */\n static initialize(\n stream: BasePostMessageStream = new WindowPostMessageStream({\n name: 'child',\n target: 'parent',\n targetWindow: self.parent,\n targetOrigin: '*',\n }),\n url = '../executor/bundle.js',\n poolSize?: number,\n ) {\n return new WebWorkerPool(stream, url, poolSize);\n }\n\n constructor(stream: BasePostMessageStream, url: string, poolSize = 3) {\n this.#stream = stream;\n this.#url = url;\n this.#poolSize = poolSize;\n\n this.#stream.on('data', this.#onData.bind(this));\n }\n\n /**\n * Handle an incoming message from the `WebWorkerExecutionService`. This\n * assumes that the message contains a `jobId` property, and a JSON-RPC\n * request in the `data` property.\n *\n * @param data - The message data.\n * @param data.data - The JSON-RPC request.\n * @param data.jobId - The job ID.\n */\n #onData(data: { data: JsonRpcRequest; jobId: string }) {\n const { jobId, data: request } = data;\n\n const job = this.jobs.get(jobId);\n if (!job) {\n // This ensures that a job is initialized before it is used. To avoid\n // code duplication, we call the `#onData` method again, which will\n // run the rest of the logic after initialization.\n this.#initializeJob(jobId)\n .then(() => {\n this.#onData(data);\n })\n .catch((error) => {\n logError('[Worker] Error initializing job:', error.toString());\n\n this.#stream.write({\n jobId,\n data: {\n name: 'command',\n data: {\n jsonrpc: '2.0',\n id: request.id ?? null,\n error: {\n code: -32000,\n message: 'Internal error',\n },\n },\n },\n });\n });\n\n return;\n }\n\n // This is a method specific to the `WebWorkerPool`, as the service itself\n // does not have access to the workers directly.\n if (request.method === 'terminateJob') {\n this.#terminateJob(jobId);\n return;\n }\n\n job.stream.write(request);\n }\n\n /**\n * Create a new worker and set up a stream to communicate with it.\n *\n * @param jobId - The job ID.\n * @returns The job.\n */\n async #initializeJob(jobId: string): Promise<ExecutorJob> {\n const worker = await this.#getWorker();\n const jobStream = new WebWorkerParentPostMessageStream({\n worker,\n });\n\n // Write messages from the worker to the parent, wrapped with the job ID.\n jobStream.on('data', (data) => {\n this.#stream.write({ data, jobId });\n });\n\n const job = { id: jobId, worker, stream: jobStream };\n this.jobs.set(jobId, job);\n return job;\n }\n\n /**\n * Terminate the job with the given ID. This will close the worker and delete\n * the job from the internal job map.\n *\n * @param jobId - The job ID.\n */\n #terminateJob(jobId: string) {\n const job = this.jobs.get(jobId);\n assert(job, `Job \"${jobId}\" not found.`);\n\n job.stream.destroy();\n job.worker.terminate();\n\n this.jobs.delete(jobId);\n }\n\n /**\n * Get a worker from the pool. A new worker will be created automatically.\n *\n * @returns The worker.\n */\n async #getWorker() {\n // Lazily create the pool of workers.\n if (this.pool.length === 0) {\n await this.#updatePool();\n }\n\n const worker = this.pool.shift();\n assert(worker, 'Worker not found.');\n\n await this.#updatePool();\n\n return worker;\n }\n\n /**\n * Update the pool of workers. This will create new workers if the pool is\n * below the minimum size.\n */\n async #updatePool() {\n while (this.pool.length < this.#poolSize) {\n const worker = await this.#createWorker();\n this.pool.push(worker);\n }\n }\n\n /**\n * Create a new worker. This will fetch the worker source if it has not\n * already been fetched.\n *\n * @returns The worker.\n */\n async #createWorker() {\n return new Worker(await this.#getWorkerURL(), {\n name: `worker-${nanoid()}`,\n });\n }\n\n /**\n * Get the URL of the worker source. This will fetch the worker source if it\n * has not already been fetched.\n *\n * @returns The worker source URL, as a `blob:` URL.\n */\n async #getWorkerURL() {\n if (this.#workerSourceURL) {\n return this.#workerSourceURL;\n }\n\n const blob = await fetch(this.#url)\n .then(async (response) => response.blob())\n .then(URL.createObjectURL.bind(URL));\n\n this.#workerSourceURL = blob;\n return blob;\n }\n}\n"]}
1
+ {"version":3,"file":"WebWorkerPool.cjs","sourceRoot":"","sources":["../../../src/webworker/pool/WebWorkerPool.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AACA,uEAGuC;AACvC,uDAAiD;AAEjD,2CAAyC;AACzC,kDAA2C;AAQ3C;;;;;;;GAOG;AACH,MAAa,aAAa;IAaxB,mDAAmD;IACnD,MAAM,CAAC,UAAU,CACf,SAAgC,IAAI,6CAAuB,CAAC;QAC1D,IAAI,EAAE,OAAO;QACb,MAAM,EAAE,QAAQ;QAChB,YAAY,EAAE,IAAI,CAAC,MAAM;QACzB,YAAY,EAAE,GAAG;KAClB,CAAC,EACF,GAAG,GAAG,uBAAuB,EAC7B,QAAiB;QAEjB,OAAO,IAAI,aAAa,CAAC,MAAM,EAAE,GAAG,EAAE,QAAQ,CAAC,CAAC;IAClD,CAAC;IAED,YAAY,MAA6B,EAAE,GAAW,EAAE,QAAQ,GAAG,CAAC;;QA1B3D,0CAAU;QAEV,wCAA+B;QAE/B,qCAAa;QAEb,SAAI,GAAa,EAAE,CAAC;QAEpB,SAAI,GAA6B,IAAI,GAAG,EAAE,CAAC;QAEpD,iDAA0B;QAiBxB,uBAAA,IAAI,yBAAW,MAAM,MAAA,CAAC;QACtB,uBAAA,IAAI,sBAAQ,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,GAAG,IAAI,CAAC,IAAI,CAAC,KAAK,EAAE,CAAC;IACjC,IAAA,cAAM,EAAC,MAAM,EAAE,mBAAmB,CAAC,CAAC;IAEpC,MAAM,uBAAA,IAAI,2DAAY,MAAhB,IAAI,CAAc,CAAC;IAEzB,OAAO,MAAM,CAAC;AAChB,CAAC;AAED;;;GAGG;AACH,KAAK;IACH,OAAO,IAAI,CAAC,IAAI,CAAC,MAAM,GAAG,uBAAA,IAAI,+BAAU,EAAE,CAAC;QACzC,MAAM,MAAM,GAAG,MAAM,uBAAA,IAAI,6DAAc,MAAlB,IAAI,CAAgB,CAAC;QAC1C,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IACzB,CAAC;AACH,CAAC;AAED;;;;;GAKG;AACH,KAAK;IACH,OAAO,IAAI,MAAM,CAAC,MAAM,uBAAA,IAAI,6DAAc,MAAlB,IAAI,CAAgB,EAAE;QAC5C,IAAI,EAAE,UAAU,IAAA,mBAAM,GAAE,EAAE;KAC3B,CAAC,CAAC;AACL,CAAC;AAED;;;;;GAKG;AACH,KAAK;IACH,IAAI,uBAAA,IAAI,sCAAiB,EAAE,CAAC;QAC1B,OAAO,uBAAA,IAAI,sCAAiB,CAAC;IAC/B,CAAC;IAED,MAAM,IAAI,GAAG,MAAM,KAAK,CAAC,uBAAA,IAAI,0BAAK,CAAC;SAChC,IAAI,CAAC,KAAK,EAAE,QAAQ,EAAE,EAAE,CAAC,QAAQ,CAAC,IAAI,EAAE,CAAC;SACzC,IAAI,CAAC,GAAG,CAAC,eAAe,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;IAEvC,uBAAA,IAAI,kCAAoB,IAAI,MAAA,CAAC;IAC7B,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import type { BasePostMessageStream } from '@metamask/post-message-stream';\nimport {\n WebWorkerParentPostMessageStream,\n WindowPostMessageStream,\n} from '@metamask/post-message-stream';\nimport { logError } from '@metamask/snaps-utils';\nimport type { JsonRpcRequest } from '@metamask/utils';\nimport { assert } from '@metamask/utils';\nimport { nanoid } from 'nanoid/non-secure';\n\ntype ExecutorJob = {\n id: string;\n worker: Worker;\n stream: WebWorkerParentPostMessageStream;\n};\n\n/**\n * A snap executor using the WebWorker API.\n *\n * This is not a traditional snap executor, as it does not execute snaps itself.\n * Instead, it creates a pool of webworkers for each snap execution, and sends\n * the snap execution request to the webworker. The webworker is responsible for\n * executing the snap.\n */\nexport class WebWorkerPool {\n readonly #poolSize;\n\n readonly #stream: BasePostMessageStream;\n\n readonly #url: string;\n\n readonly pool: Worker[] = [];\n\n readonly jobs: Map<string, ExecutorJob> = new Map();\n\n #workerSourceURL?: string;\n\n /* istanbul ignore next - Constructor arguments. */\n static initialize(\n stream: BasePostMessageStream = new WindowPostMessageStream({\n name: 'child',\n target: 'parent',\n targetWindow: self.parent,\n targetOrigin: '*',\n }),\n url = '../executor/bundle.js',\n poolSize?: number,\n ) {\n return new WebWorkerPool(stream, url, poolSize);\n }\n\n constructor(stream: BasePostMessageStream, url: string, poolSize = 3) {\n this.#stream = stream;\n this.#url = url;\n this.#poolSize = poolSize;\n\n this.#stream.on('data', this.#onData.bind(this));\n }\n\n /**\n * Handle an incoming message from the `WebWorkerExecutionService`. This\n * assumes that the message contains a `jobId` property, and a JSON-RPC\n * request in the `data` property.\n *\n * @param data - The message data.\n * @param data.data - The JSON-RPC request.\n * @param data.jobId - The job ID.\n */\n #onData(data: { data: JsonRpcRequest; jobId: string }) {\n const { jobId, data: request } = data;\n\n const job = this.jobs.get(jobId);\n if (!job) {\n // This ensures that a job is initialized before it is used. To avoid\n // code duplication, we call the `#onData` method again, which will\n // run the rest of the logic after initialization.\n this.#initializeJob(jobId)\n .then(() => {\n this.#onData(data);\n })\n .catch((error) => {\n logError('[Worker] Error initializing job:', error.toString());\n\n this.#stream.write({\n jobId,\n data: {\n name: 'command',\n data: {\n jsonrpc: '2.0',\n id: request.id ?? null,\n error: {\n code: -32000,\n message: 'Internal error',\n },\n },\n },\n });\n });\n\n return;\n }\n\n // This is a method specific to the `WebWorkerPool`, as the service itself\n // does not have access to the workers directly.\n if (request.method === 'terminateJob') {\n this.#terminateJob(jobId);\n return;\n }\n\n job.stream.write(request);\n }\n\n /**\n * Create a new worker and set up a stream to communicate with it.\n *\n * @param jobId - The job ID.\n * @returns The job.\n */\n async #initializeJob(jobId: string): Promise<ExecutorJob> {\n const worker = await this.#getWorker();\n const jobStream = new WebWorkerParentPostMessageStream({\n worker,\n });\n\n // Write messages from the worker to the parent, wrapped with the job ID.\n jobStream.on('data', (data) => {\n this.#stream.write({ data, jobId });\n });\n\n const job = { id: jobId, worker, stream: jobStream };\n this.jobs.set(jobId, job);\n return job;\n }\n\n /**\n * Terminate the job with the given ID. This will close the worker and delete\n * the job from the internal job map.\n *\n * @param jobId - The job ID.\n */\n #terminateJob(jobId: string) {\n const job = this.jobs.get(jobId);\n assert(job, `Job \"${jobId}\" not found.`);\n\n job.stream.destroy();\n job.worker.terminate();\n\n this.jobs.delete(jobId);\n }\n\n /**\n * Get a worker from the pool. A new worker will be created automatically.\n *\n * @returns The worker.\n */\n async #getWorker() {\n // Lazily create the pool of workers.\n if (this.pool.length === 0) {\n await this.#updatePool();\n }\n\n const worker = this.pool.shift();\n assert(worker, 'Worker not found.');\n\n await this.#updatePool();\n\n return worker;\n }\n\n /**\n * Update the pool of workers. This will create new workers if the pool is\n * below the minimum size.\n */\n async #updatePool() {\n while (this.pool.length < this.#poolSize) {\n const worker = await this.#createWorker();\n this.pool.push(worker);\n }\n }\n\n /**\n * Create a new worker. This will fetch the worker source if it has not\n * already been fetched.\n *\n * @returns The worker.\n */\n async #createWorker() {\n return new Worker(await this.#getWorkerURL(), {\n name: `worker-${nanoid()}`,\n });\n }\n\n /**\n * Get the URL of the worker source. This will fetch the worker source if it\n * has not already been fetched.\n *\n * @returns The worker source URL, as a `blob:` URL.\n */\n async #getWorkerURL() {\n if (this.#workerSourceURL) {\n return this.#workerSourceURL;\n }\n\n const blob = await fetch(this.#url)\n .then(async (response) => response.blob())\n .then(URL.createObjectURL.bind(URL));\n\n this.#workerSourceURL = blob;\n return blob;\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 _WebWorkerPool_instances, _WebWorkerPool_poolSize, _WebWorkerPool_stream, _WebWorkerPool_url, _WebWorkerPool_workerSourceURL, _WebWorkerPool_onData, _WebWorkerPool_initializeJob, _WebWorkerPool_terminateJob, _WebWorkerPool_getWorker, _WebWorkerPool_updatePool, _WebWorkerPool_createWorker, _WebWorkerPool_getWorkerURL;
1
13
  import $metamaskpostmessagestream from "@metamask/post-message-stream";
2
14
  const { WebWorkerParentPostMessageStream, WindowPostMessageStream } = $metamaskpostmessagestream;
3
15
  import { logError } from "@metamask/snaps-utils";
@@ -12,12 +24,6 @@ import { nanoid } from "nanoid/non-secure";
12
24
  * executing the snap.
13
25
  */
14
26
  export class WebWorkerPool {
15
- #poolSize;
16
- #stream;
17
- #url;
18
- pool = [];
19
- jobs = new Map();
20
- #workerSourceURL;
21
27
  /* istanbul ignore next - Constructor arguments. */
22
28
  static initialize(stream = new WindowPostMessageStream({
23
29
  name: 'child',
@@ -28,141 +34,132 @@ export class WebWorkerPool {
28
34
  return new WebWorkerPool(stream, url, poolSize);
29
35
  }
30
36
  constructor(stream, url, poolSize = 3) {
31
- this.#stream = stream;
32
- this.#url = url;
33
- this.#poolSize = poolSize;
34
- this.#stream.on('data', this.#onData.bind(this));
37
+ _WebWorkerPool_instances.add(this);
38
+ _WebWorkerPool_poolSize.set(this, void 0);
39
+ _WebWorkerPool_stream.set(this, void 0);
40
+ _WebWorkerPool_url.set(this, void 0);
41
+ this.pool = [];
42
+ this.jobs = new Map();
43
+ _WebWorkerPool_workerSourceURL.set(this, void 0);
44
+ __classPrivateFieldSet(this, _WebWorkerPool_stream, stream, "f");
45
+ __classPrivateFieldSet(this, _WebWorkerPool_url, url, "f");
46
+ __classPrivateFieldSet(this, _WebWorkerPool_poolSize, poolSize, "f");
47
+ __classPrivateFieldGet(this, _WebWorkerPool_stream, "f").on('data', __classPrivateFieldGet(this, _WebWorkerPool_instances, "m", _WebWorkerPool_onData).bind(this));
35
48
  }
36
- /**
37
- * Handle an incoming message from the `WebWorkerExecutionService`. This
38
- * assumes that the message contains a `jobId` property, and a JSON-RPC
39
- * request in the `data` property.
40
- *
41
- * @param data - The message data.
42
- * @param data.data - The JSON-RPC request.
43
- * @param data.jobId - The job ID.
44
- */
45
- #onData(data) {
46
- const { jobId, data: request } = data;
47
- const job = this.jobs.get(jobId);
48
- if (!job) {
49
- // This ensures that a job is initialized before it is used. To avoid
50
- // code duplication, we call the `#onData` method again, which will
51
- // run the rest of the logic after initialization.
52
- this.#initializeJob(jobId)
53
- .then(() => {
54
- this.#onData(data);
55
- })
56
- .catch((error) => {
57
- logError('[Worker] Error initializing job:', error.toString());
58
- this.#stream.write({
59
- jobId,
49
+ }
50
+ _WebWorkerPool_poolSize = new WeakMap(), _WebWorkerPool_stream = new WeakMap(), _WebWorkerPool_url = new WeakMap(), _WebWorkerPool_workerSourceURL = new WeakMap(), _WebWorkerPool_instances = new WeakSet(), _WebWorkerPool_onData = function _WebWorkerPool_onData(data) {
51
+ const { jobId, data: request } = data;
52
+ const job = this.jobs.get(jobId);
53
+ if (!job) {
54
+ // This ensures that a job is initialized before it is used. To avoid
55
+ // code duplication, we call the `#onData` method again, which will
56
+ // run the rest of the logic after initialization.
57
+ __classPrivateFieldGet(this, _WebWorkerPool_instances, "m", _WebWorkerPool_initializeJob).call(this, jobId)
58
+ .then(() => {
59
+ __classPrivateFieldGet(this, _WebWorkerPool_instances, "m", _WebWorkerPool_onData).call(this, data);
60
+ })
61
+ .catch((error) => {
62
+ logError('[Worker] Error initializing job:', error.toString());
63
+ __classPrivateFieldGet(this, _WebWorkerPool_stream, "f").write({
64
+ jobId,
65
+ data: {
66
+ name: 'command',
60
67
  data: {
61
- name: 'command',
62
- data: {
63
- jsonrpc: '2.0',
64
- id: request.id ?? null,
65
- error: {
66
- code: -32000,
67
- message: 'Internal error',
68
- },
68
+ jsonrpc: '2.0',
69
+ id: request.id ?? null,
70
+ error: {
71
+ code: -32000,
72
+ message: 'Internal error',
69
73
  },
70
74
  },
71
- });
75
+ },
72
76
  });
73
- return;
74
- }
75
- // This is a method specific to the `WebWorkerPool`, as the service itself
76
- // does not have access to the workers directly.
77
- if (request.method === 'terminateJob') {
78
- this.#terminateJob(jobId);
79
- return;
80
- }
81
- job.stream.write(request);
82
- }
83
- /**
84
- * Create a new worker and set up a stream to communicate with it.
85
- *
86
- * @param jobId - The job ID.
87
- * @returns The job.
88
- */
89
- async #initializeJob(jobId) {
90
- const worker = await this.#getWorker();
91
- const jobStream = new WebWorkerParentPostMessageStream({
92
- worker,
93
- });
94
- // Write messages from the worker to the parent, wrapped with the job ID.
95
- jobStream.on('data', (data) => {
96
- this.#stream.write({ data, jobId });
97
77
  });
98
- const job = { id: jobId, worker, stream: jobStream };
99
- this.jobs.set(jobId, job);
100
- return job;
78
+ return;
101
79
  }
102
- /**
103
- * Terminate the job with the given ID. This will close the worker and delete
104
- * the job from the internal job map.
105
- *
106
- * @param jobId - The job ID.
107
- */
108
- #terminateJob(jobId) {
109
- const job = this.jobs.get(jobId);
110
- assert(job, `Job "${jobId}" not found.`);
111
- job.stream.destroy();
112
- job.worker.terminate();
113
- this.jobs.delete(jobId);
80
+ // This is a method specific to the `WebWorkerPool`, as the service itself
81
+ // does not have access to the workers directly.
82
+ if (request.method === 'terminateJob') {
83
+ __classPrivateFieldGet(this, _WebWorkerPool_instances, "m", _WebWorkerPool_terminateJob).call(this, jobId);
84
+ return;
114
85
  }
115
- /**
116
- * Get a worker from the pool. A new worker will be created automatically.
117
- *
118
- * @returns The worker.
119
- */
120
- async #getWorker() {
121
- // Lazily create the pool of workers.
122
- if (this.pool.length === 0) {
123
- await this.#updatePool();
124
- }
125
- const worker = this.pool.shift();
126
- assert(worker, 'Worker not found.');
127
- await this.#updatePool();
128
- return worker;
129
- }
130
- /**
131
- * Update the pool of workers. This will create new workers if the pool is
132
- * below the minimum size.
133
- */
134
- async #updatePool() {
135
- while (this.pool.length < this.#poolSize) {
136
- const worker = await this.#createWorker();
137
- this.pool.push(worker);
138
- }
86
+ job.stream.write(request);
87
+ }, _WebWorkerPool_initializeJob =
88
+ /**
89
+ * Create a new worker and set up a stream to communicate with it.
90
+ *
91
+ * @param jobId - The job ID.
92
+ * @returns The job.
93
+ */
94
+ async function _WebWorkerPool_initializeJob(jobId) {
95
+ const worker = await __classPrivateFieldGet(this, _WebWorkerPool_instances, "m", _WebWorkerPool_getWorker).call(this);
96
+ const jobStream = new WebWorkerParentPostMessageStream({
97
+ worker,
98
+ });
99
+ // Write messages from the worker to the parent, wrapped with the job ID.
100
+ jobStream.on('data', (data) => {
101
+ __classPrivateFieldGet(this, _WebWorkerPool_stream, "f").write({ data, jobId });
102
+ });
103
+ const job = { id: jobId, worker, stream: jobStream };
104
+ this.jobs.set(jobId, job);
105
+ return job;
106
+ }, _WebWorkerPool_terminateJob = function _WebWorkerPool_terminateJob(jobId) {
107
+ const job = this.jobs.get(jobId);
108
+ assert(job, `Job "${jobId}" not found.`);
109
+ job.stream.destroy();
110
+ job.worker.terminate();
111
+ this.jobs.delete(jobId);
112
+ }, _WebWorkerPool_getWorker =
113
+ /**
114
+ * Get a worker from the pool. A new worker will be created automatically.
115
+ *
116
+ * @returns The worker.
117
+ */
118
+ async function _WebWorkerPool_getWorker() {
119
+ // Lazily create the pool of workers.
120
+ if (this.pool.length === 0) {
121
+ await __classPrivateFieldGet(this, _WebWorkerPool_instances, "m", _WebWorkerPool_updatePool).call(this);
139
122
  }
140
- /**
141
- * Create a new worker. This will fetch the worker source if it has not
142
- * already been fetched.
143
- *
144
- * @returns The worker.
145
- */
146
- async #createWorker() {
147
- return new Worker(await this.#getWorkerURL(), {
148
- name: `worker-${nanoid()}`,
149
- });
123
+ const worker = this.pool.shift();
124
+ assert(worker, 'Worker not found.');
125
+ await __classPrivateFieldGet(this, _WebWorkerPool_instances, "m", _WebWorkerPool_updatePool).call(this);
126
+ return worker;
127
+ }, _WebWorkerPool_updatePool =
128
+ /**
129
+ * Update the pool of workers. This will create new workers if the pool is
130
+ * below the minimum size.
131
+ */
132
+ async function _WebWorkerPool_updatePool() {
133
+ while (this.pool.length < __classPrivateFieldGet(this, _WebWorkerPool_poolSize, "f")) {
134
+ const worker = await __classPrivateFieldGet(this, _WebWorkerPool_instances, "m", _WebWorkerPool_createWorker).call(this);
135
+ this.pool.push(worker);
150
136
  }
151
- /**
152
- * Get the URL of the worker source. This will fetch the worker source if it
153
- * has not already been fetched.
154
- *
155
- * @returns The worker source URL, as a `blob:` URL.
156
- */
157
- async #getWorkerURL() {
158
- if (this.#workerSourceURL) {
159
- return this.#workerSourceURL;
160
- }
161
- const blob = await fetch(this.#url)
162
- .then(async (response) => response.blob())
163
- .then(URL.createObjectURL.bind(URL));
164
- this.#workerSourceURL = blob;
165
- return blob;
137
+ }, _WebWorkerPool_createWorker =
138
+ /**
139
+ * Create a new worker. This will fetch the worker source if it has not
140
+ * already been fetched.
141
+ *
142
+ * @returns The worker.
143
+ */
144
+ async function _WebWorkerPool_createWorker() {
145
+ return new Worker(await __classPrivateFieldGet(this, _WebWorkerPool_instances, "m", _WebWorkerPool_getWorkerURL).call(this), {
146
+ name: `worker-${nanoid()}`,
147
+ });
148
+ }, _WebWorkerPool_getWorkerURL =
149
+ /**
150
+ * Get the URL of the worker source. This will fetch the worker source if it
151
+ * has not already been fetched.
152
+ *
153
+ * @returns The worker source URL, as a `blob:` URL.
154
+ */
155
+ async function _WebWorkerPool_getWorkerURL() {
156
+ if (__classPrivateFieldGet(this, _WebWorkerPool_workerSourceURL, "f")) {
157
+ return __classPrivateFieldGet(this, _WebWorkerPool_workerSourceURL, "f");
166
158
  }
167
- }
159
+ const blob = await fetch(__classPrivateFieldGet(this, _WebWorkerPool_url, "f"))
160
+ .then(async (response) => response.blob())
161
+ .then(URL.createObjectURL.bind(URL));
162
+ __classPrivateFieldSet(this, _WebWorkerPool_workerSourceURL, blob, "f");
163
+ return blob;
164
+ };
168
165
  //# sourceMappingURL=WebWorkerPool.mjs.map