File size: 6,021 Bytes
bc20498 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 |
/**
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import URL from 'url';
import VM from 'vm';
import threads from 'worker_threads';
const WORKER = Symbol.for('worker');
const EVENTS = Symbol.for('events');
class EventTarget {
constructor() {
Object.defineProperty(this, EVENTS, {
value: new Map()
});
}
dispatchEvent(event) {
event.target = event.currentTarget = this;
if (this['on'+event.type]) {
try {
this['on'+event.type](event);
}
catch (err) {
console.error(err);
}
}
const list = this[EVENTS].get(event.type);
if (list == null) return;
list.forEach(handler => {
try {
handler.call(this, event);
}
catch (err) {
console.error(err);
}
});
}
addEventListener(type, fn) {
let events = this[EVENTS].get(type);
if (!events) this[EVENTS].set(type, events = []);
events.push(fn);
}
removeEventListener(type, fn) {
let events = this[EVENTS].get(type);
if (events) {
const index = events.indexOf(fn);
if (index !== -1) events.splice(index, 1);
}
}
}
function Event(type, target) {
this.type = type;
this.timeStamp = Date.now();
this.target = this.currentTarget = this.data = null;
}
// this module is used self-referentially on both sides of the
// thread boundary, but behaves differently in each context.
export default threads.isMainThread ? mainThread() : workerThread();
const baseUrl = URL.pathToFileURL(process.cwd() + '/');
function mainThread() {
/**
* A web-compatible Worker implementation atop Node's worker_threads.
* - uses DOM-style events (Event.data, Event.type, etc)
* - supports event handler properties (worker.onmessage)
* - Worker() constructor accepts a module URL
* - accepts the {type:'module'} option
* - emulates WorkerGlobalScope within the worker
* @param {string} url The URL or module specifier to load
* @param {object} [options] Worker construction options
* @param {string} [options.name] Available as `self.name` within the Worker
* @param {string} [options.type="classic"] Pass "module" to create a Module Worker.
*/
class Worker extends EventTarget {
constructor(url, options) {
super();
const { name, type } = options || {};
url += '';
let mod;
if (/^data:/.test(url)) {
mod = url;
}
else {
mod = URL.fileURLToPath(new URL.URL(url, baseUrl));
}
const worker = new threads.Worker(
__filename,
{ workerData: { mod, name, type } }
);
Object.defineProperty(this, WORKER, {
value: worker
});
worker.on('message', data => {
const event = new Event('message');
event.data = data;
this.dispatchEvent(event);
});
worker.on('error', error => {
error.type = 'error';
this.dispatchEvent(error);
});
worker.on('exit', () => {
this.dispatchEvent(new Event('close'));
});
}
postMessage(data, transferList) {
this[WORKER].postMessage(data, transferList);
}
terminate() {
this[WORKER].terminate();
}
}
Worker.prototype.onmessage = Worker.prototype.onerror = Worker.prototype.onclose = null;
return Worker;
}
function workerThread() {
let { mod, name, type } = threads.workerData;
if (!mod) return mainThread();
// turn global into a mock WorkerGlobalScope
const self = global.self = global;
// enqueue messages to dispatch after modules are loaded
let q = [];
function flush() {
const buffered = q;
q = null;
buffered.forEach(event => { self.dispatchEvent(event); });
}
threads.parentPort.on('message', data => {
const event = new Event('message');
event.data = data;
if (q == null) self.dispatchEvent(event);
else q.push(event);
});
threads.parentPort.on('error', err => {
err.type = 'Error';
self.dispatchEvent(err);
});
class WorkerGlobalScope extends EventTarget {
postMessage(data, transferList) {
threads.parentPort.postMessage(data, transferList);
}
// Emulates https://developer.mozilla.org/en-US/docs/Web/API/DedicatedWorkerGlobalScope/close
close() {
process.exit();
}
}
let proto = Object.getPrototypeOf(global);
delete proto.constructor;
Object.defineProperties(WorkerGlobalScope.prototype, proto);
proto = Object.setPrototypeOf(global, new WorkerGlobalScope());
['postMessage', 'addEventListener', 'removeEventListener', 'dispatchEvent'].forEach(fn => {
proto[fn] = proto[fn].bind(global);
});
global.name = name;
const isDataUrl = /^data:/.test(mod);
if (type === 'module') {
import(mod)
.catch(err => {
if (isDataUrl && err.message === 'Not supported') {
console.warn('Worker(): Importing data: URLs requires Node 12.10+. Falling back to classic worker.');
return evaluateDataUrl(mod, name);
}
console.error(err);
})
.then(flush);
}
else {
try {
if (/^data:/.test(mod)) {
evaluateDataUrl(mod, name);
}
else {
require(mod);
}
}
catch (err) {
console.error(err);
}
Promise.resolve().then(flush);
}
}
function evaluateDataUrl(url, name) {
const { data } = parseDataUrl(url);
return VM.runInThisContext(data, {
filename: 'worker.<'+(name || 'data:')+'>'
});
}
function parseDataUrl(url) {
let [m, type, encoding, data] = url.match(/^data: *([^;,]*)(?: *; *([^,]*))? *,(.*)$/) || [];
if (!m) throw Error('Invalid Data URL.');
if (encoding) switch (encoding.toLowerCase()) {
case 'base64':
data = Buffer.from(data, 'base64').toString();
break;
default:
throw Error('Unknown Data URL encoding "' + encoding + '"');
}
return { type, data };
}
|