Socket
Socket
Sign inDemoInstall

@loaders.gl/worker-utils

Package Overview
Dependencies
Maintainers
7
Versions
198
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@loaders.gl/worker-utils - npm Package Compare versions

Comparing version 3.0.0-beta.1 to 3.0.0-beta.2

2

dist/es5/index.js

@@ -132,3 +132,3 @@ "use strict";

var VERSION = typeof "3.0.0-beta.1" !== 'undefined' ? "3.0.0-beta.1" : 'latest';
var VERSION = typeof "3.0.0-beta.2" !== 'undefined' ? "3.0.0-beta.2" : 'latest';
var NullWorker = {

@@ -135,0 +135,0 @@ id: 'null',

@@ -28,3 +28,3 @@ "use strict";

var LATEST = 'beta';
var VERSION = typeof "3.0.0-beta.1" !== 'undefined' ? "3.0.0-beta.1" : LATEST;
var VERSION = typeof "3.0.0-beta.2" !== 'undefined' ? "3.0.0-beta.2" : LATEST;
var loadLibraryPromises = {};

@@ -31,0 +31,0 @@

@@ -18,3 +18,3 @@ "use strict";

var NPM_TAG = 'beta';
var VERSION = typeof "3.0.0-beta.1" !== 'undefined' ? "3.0.0-beta.1" : NPM_TAG;
var VERSION = typeof "3.0.0-beta.2" !== 'undefined' ? "3.0.0-beta.2" : NPM_TAG;

@@ -21,0 +21,0 @@ function getWorkerObjectURL(worker, options) {

"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
//# sourceMappingURL=protocol.js.map
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
//# sourceMappingURL=types.js.map

@@ -14,4 +14,4 @@ export { assert } from './lib/env-utils/assert';

export { default as ChildProcessProxy } from './lib/process-utils/child-process-proxy';
var VERSION = typeof "3.0.0-beta.1" !== 'undefined' ? "3.0.0-beta.1" : 'latest';
export var NullWorker = {
const VERSION = typeof "3.0.0-beta.2" !== 'undefined' ? "3.0.0-beta.2" : 'latest';
export const NullWorker = {
id: 'null',

@@ -18,0 +18,0 @@ name: 'null',

@@ -1,13 +0,8 @@

import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
import _createClass from "@babel/runtime/helpers/esm/createClass";
import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
var _Symbol$asyncIterator;
let _Symbol$asyncIterator;
_Symbol$asyncIterator = Symbol.asyncIterator;
var AsyncQueue = function () {
function AsyncQueue() {
_classCallCheck(this, AsyncQueue);
export default class AsyncQueue {
constructor() {
_defineProperty(this, "_values", void 0);

@@ -24,92 +19,80 @@

_createClass(AsyncQueue, [{
key: _Symbol$asyncIterator,
value: function value() {
return this;
[_Symbol$asyncIterator]() {
return this;
}
push(value) {
return this.enqueue(value);
}
enqueue(value) {
if (this._closed) {
throw new Error('Closed');
}
}, {
key: "push",
value: function push(value) {
return this.enqueue(value);
}
}, {
key: "enqueue",
value: function enqueue(value) {
if (this._closed) {
throw new Error('Closed');
if (this._settlers.length > 0) {
if (this._values.length > 0) {
throw new Error('Illegal internal state');
}
if (this._settlers.length > 0) {
if (this._values.length > 0) {
throw new Error('Illegal internal state');
}
const settler = this._settlers.shift();
var settler = this._settlers.shift();
if (value instanceof Error) {
settler.reject(value);
} else {
settler.resolve({
value: value
});
}
if (value instanceof Error) {
settler.reject(value);
} else {
this._values.push(value);
}
}
}, {
key: "close",
value: function close() {
while (this._settlers.length > 0) {
var settler = this._settlers.shift();
settler.resolve({
done: true
value
});
}
} else {
this._values.push(value);
}
}
this._closed = true;
close() {
while (this._settlers.length > 0) {
const settler = this._settlers.shift();
settler.resolve({
done: true
});
}
}, {
key: "next",
value: function next() {
var _this = this;
if (this._values.length > 0) {
var value = this._values.shift();
this._closed = true;
}
if (value instanceof Error) {
return Promise.reject(value);
}
next() {
if (this._values.length > 0) {
const value = this._values.shift();
return Promise.resolve({
done: false,
value: value
});
if (value instanceof Error) {
return Promise.reject(value);
}
if (this._closed) {
if (this._settlers.length > 0) {
throw new Error('Illegal internal state');
}
return Promise.resolve({
done: false,
value
});
}
return Promise.resolve({
done: true,
value: undefined
});
if (this._closed) {
if (this._settlers.length > 0) {
throw new Error('Illegal internal state');
}
return new Promise(function (resolve, reject) {
_this._settlers.push({
resolve: resolve,
reject: reject
});
return Promise.resolve({
done: true,
value: undefined
});
}
}]);
return AsyncQueue;
}();
return new Promise((resolve, reject) => {
this._settlers.push({
resolve,
reject
});
});
}
export { AsyncQueue as default };
}
//# sourceMappingURL=async-queue.js.map

@@ -1,3 +0,2 @@

import _typeof from "@babel/runtime/helpers/esm/typeof";
var globals = {
const globals = {
self: typeof self !== 'undefined' && self,

@@ -8,12 +7,12 @@ window: typeof window !== 'undefined' && window,

};
var self_ = globals.self || globals.window || globals.global || {};
var window_ = globals.window || globals.self || globals.global || {};
var global_ = globals.global || globals.self || globals.window || {};
var document_ = globals.document || {};
const self_ = globals.self || globals.window || globals.global || {};
const window_ = globals.window || globals.self || globals.global || {};
const global_ = globals.global || globals.self || globals.window || {};
const document_ = globals.document || {};
export { self_ as self, window_ as window, global_ as global, document_ as document };
export var isBrowser = (typeof process === "undefined" ? "undefined" : _typeof(process)) !== 'object' || String(process) !== '[object process]' || process.browser;
export var isWorker = typeof importScripts === 'function';
export var isMobile = typeof window !== 'undefined' && typeof window.orientation !== 'undefined';
var matches = typeof process !== 'undefined' && process.version && /v([0-9]*)/.exec(process.version);
export var nodeVersion = matches && parseFloat(matches[1]) || 0;
export const isBrowser = typeof process !== 'object' || String(process) !== '[object process]' || process.browser;
export const isWorker = typeof importScripts === 'function';
export const isMobile = typeof window !== 'undefined' && typeof window.orientation !== 'undefined';
const matches = typeof process !== 'undefined' && process.version && /v([0-9]*)/.exec(process.version);
export const nodeVersion = matches && parseFloat(matches[1]) || 0;
//# sourceMappingURL=globals.js.map

@@ -1,46 +0,15 @@

import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator";
import _regeneratorRuntime from "@babel/runtime/regenerator";
import { global, isBrowser, isWorker } from '../env-utils/globals';
import * as node from '../node/require-utils.node';
import { assert } from '../env-utils/assert';
var LATEST = 'beta';
var VERSION = typeof "3.0.0-beta.1" !== 'undefined' ? "3.0.0-beta.1" : LATEST;
var loadLibraryPromises = {};
export function loadLibrary(_x) {
return _loadLibrary.apply(this, arguments);
}
const LATEST = 'beta';
const VERSION = typeof "3.0.0-beta.2" !== 'undefined' ? "3.0.0-beta.2" : LATEST;
const loadLibraryPromises = {};
export async function loadLibrary(libraryUrl, moduleName = null, options = {}) {
if (moduleName) {
libraryUrl = getLibraryUrl(libraryUrl, moduleName, options);
}
function _loadLibrary() {
_loadLibrary = _asyncToGenerator(_regeneratorRuntime.mark(function _callee(libraryUrl) {
var moduleName,
options,
_args = arguments;
return _regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
moduleName = _args.length > 1 && _args[1] !== undefined ? _args[1] : null;
options = _args.length > 2 && _args[2] !== undefined ? _args[2] : {};
if (moduleName) {
libraryUrl = getLibraryUrl(libraryUrl, moduleName, options);
}
loadLibraryPromises[libraryUrl] = loadLibraryPromises[libraryUrl] || loadLibraryFromFile(libraryUrl);
_context.next = 6;
return loadLibraryPromises[libraryUrl];
case 6:
return _context.abrupt("return", _context.sent);
case 7:
case "end":
return _context.stop();
}
}
}, _callee);
}));
return _loadLibrary.apply(this, arguments);
loadLibraryPromises[libraryUrl] = loadLibraryPromises[libraryUrl] || loadLibraryFromFile(libraryUrl);
return await loadLibraryPromises[libraryUrl];
}
export function getLibraryUrl(library, moduleName, options) {

@@ -51,3 +20,3 @@ if (library.startsWith('http')) {

var modules = options.modules || {};
const modules = options.modules || {};

@@ -74,81 +43,19 @@ if (modules[library]) {

function loadLibraryFromFile(_x2) {
return _loadLibraryFromFile.apply(this, arguments);
}
async function loadLibraryFromFile(libraryUrl) {
if (libraryUrl.endsWith('wasm')) {
const response = await fetch(libraryUrl);
return await response.arrayBuffer();
}
function _loadLibraryFromFile() {
_loadLibraryFromFile = _asyncToGenerator(_regeneratorRuntime.mark(function _callee2(libraryUrl) {
var _response, response, scriptSource;
if (!isBrowser) {
return node.requireFromFile && (await node.requireFromFile(libraryUrl));
}
return _regeneratorRuntime.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
if (!libraryUrl.endsWith('wasm')) {
_context2.next = 7;
break;
}
if (isWorker) {
return importScripts(libraryUrl);
}
_context2.next = 3;
return fetch(libraryUrl);
case 3:
_response = _context2.sent;
_context2.next = 6;
return _response.arrayBuffer();
case 6:
return _context2.abrupt("return", _context2.sent);
case 7:
if (isBrowser) {
_context2.next = 14;
break;
}
_context2.t0 = node.requireFromFile;
if (!_context2.t0) {
_context2.next = 13;
break;
}
_context2.next = 12;
return node.requireFromFile(libraryUrl);
case 12:
_context2.t0 = _context2.sent;
case 13:
return _context2.abrupt("return", _context2.t0);
case 14:
if (!isWorker) {
_context2.next = 16;
break;
}
return _context2.abrupt("return", importScripts(libraryUrl));
case 16:
_context2.next = 18;
return fetch(libraryUrl);
case 18:
response = _context2.sent;
_context2.next = 21;
return response.text();
case 21:
scriptSource = _context2.sent;
return _context2.abrupt("return", loadLibraryFromString(scriptSource, libraryUrl));
case 23:
case "end":
return _context2.stop();
}
}
}, _callee2);
}));
return _loadLibraryFromFile.apply(this, arguments);
const response = await fetch(libraryUrl);
const scriptSource = await response.text();
return loadLibraryFromString(scriptSource, libraryUrl);
}

@@ -166,3 +73,3 @@

var script = document.createElement('script');
const script = document.createElement('script');
script.id = id;

@@ -169,0 +76,0 @@

@@ -1,62 +0,18 @@

import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
import _typeof from "@babel/runtime/helpers/esm/typeof";
import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator";
import _regeneratorRuntime from "@babel/runtime/regenerator";
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
import Module from 'module';
import path from 'path';
export function requireFromFile(_x) {
return _requireFromFile.apply(this, arguments);
}
export async function requireFromFile(filename) {
if (filename.startsWith('http')) {
const response = await fetch(filename);
const code = await response.text();
return requireFromString(code);
}
function _requireFromFile() {
_requireFromFile = _asyncToGenerator(_regeneratorRuntime.mark(function _callee(filename) {
var response, code;
return _regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
if (!filename.startsWith('http')) {
_context.next = 8;
break;
}
if (!filename.startsWith('/')) {
filename = "".concat(process.cwd(), "/").concat(filename);
}
_context.next = 3;
return fetch(filename);
case 3:
response = _context.sent;
_context.next = 6;
return response.text();
case 6:
code = _context.sent;
return _context.abrupt("return", requireFromString(code));
case 8:
if (!filename.startsWith('/')) {
filename = "".concat(process.cwd(), "/").concat(filename);
}
return _context.abrupt("return", require(filename));
case 10:
case "end":
return _context.stop();
}
}
}, _callee);
}));
return _requireFromFile.apply(this, arguments);
return require(filename);
}
export function requireFromString(code) {
var filename = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
if (_typeof(filename) === 'object') {
export function requireFromString(code, filename = '', options = {}) {
if (typeof filename === 'object') {
options = filename;

@@ -66,15 +22,16 @@ filename = '';

options = _objectSpread({
options = {
appendPaths: [],
prependPaths: []
}, options);
prependPaths: [],
...options
};
if (typeof code !== 'string') {
throw new Error("code must be a string, not ".concat(_typeof(code)));
throw new Error("code must be a string, not ".concat(typeof code));
}
var paths = Module._nodeModulePaths(path.dirname(filename));
const paths = Module._nodeModulePaths(path.dirname(filename));
var parent = module.parent;
var newModule = new Module(filename, parent);
const parent = module.parent;
const newModule = new Module(filename, parent);
newModule.filename = filename;

@@ -81,0 +38,0 @@ newModule.paths = [].concat(options.prependPaths).concat(paths).concat(options.appendPaths);

@@ -1,15 +0,5 @@

import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray";
import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator";
import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
import _createClass from "@babel/runtime/helpers/esm/createClass";
import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
import _regeneratorRuntime from "@babel/runtime/regenerator";
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
import { spawn } from 'child_process';
import { getAvailablePort } from './process-utils';
var DEFAULT_PROPS = {
const DEFAULT_PROPS = {
command: '',

@@ -20,18 +10,14 @@ arguments: [],

wait: 2000,
onSuccess: function onSuccess(processProxy) {
onSuccess: processProxy => {
console.log("Started ".concat(processProxy.props.command));
}
};
var ChildProcessProxy = function () {
function ChildProcessProxy() {
var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
_ref$id = _ref.id,
id = _ref$id === void 0 ? 'browser-driver' : _ref$id;
_classCallCheck(this, ChildProcessProxy);
export default class ChildProcessProxy {
constructor({
id = 'browser-driver'
} = {}) {
_defineProperty(this, "id", void 0);
_defineProperty(this, "props", _objectSpread({}, DEFAULT_PROPS));
_defineProperty(this, "props", { ...DEFAULT_PROPS
});

@@ -47,186 +33,92 @@ _defineProperty(this, "childProcess", null);

_createClass(ChildProcessProxy, [{
key: "start",
value: function () {
var _start = _asyncToGenerator(_regeneratorRuntime.mark(function _callee(props) {
var _this = this;
async start(props) {
props = { ...DEFAULT_PROPS,
...props
};
this.props = props;
const args = [...props.arguments];
this.port = Number(props.port);
var args;
return _regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
props = _objectSpread(_objectSpread({}, DEFAULT_PROPS), props);
this.props = props;
args = _toConsumableArray(props.arguments);
this.port = Number(props.port);
if (props.portArg) {
if (props.autoPort) {
this.port = await getAvailablePort(props.port);
}
if (!props.portArg) {
_context.next = 10;
break;
}
args.push(props.portArg, String(this.port));
}
if (!props.autoPort) {
_context.next = 9;
break;
}
return await new Promise((resolve, reject) => {
try {
this._setTimeout(() => {
if (props.onSuccess) {
props.onSuccess(this);
}
_context.next = 8;
return getAvailablePort(props.port);
resolve({});
});
case 8:
this.port = _context.sent;
console.log("Spawning ".concat(props.command, " ").concat(props.arguments.join(' ')));
const childProcess = spawn(props.command, args, props.spawn);
this.childProcess = childProcess;
childProcess.stdout.on('data', data => {
console.log(data.toString());
});
childProcess.stderr.on('data', data => {
console.log("Child process wrote to stderr: \"".concat(data, "\"."));
case 9:
args.push(props.portArg, String(this.port));
this._clearTimeout();
case 10:
_context.next = 12;
return new Promise(function (resolve, reject) {
try {
_this._setTimeout(function () {
if (props.onSuccess) {
props.onSuccess(_this);
}
reject(new Error(data));
});
childProcess.on('error', error => {
console.log("Child process errored with ".concat(error));
resolve({});
});
this._clearTimeout();
console.log("Spawning ".concat(props.command, " ").concat(props.arguments.join(' ')));
var childProcess = spawn(props.command, args, props.spawn);
_this.childProcess = childProcess;
childProcess.stdout.on('data', function (data) {
console.log(data.toString());
});
childProcess.stderr.on('data', function (data) {
console.log("Child process wrote to stderr: \"".concat(data, "\"."));
reject(error);
});
childProcess.on('close', code => {
console.log("Child process exited with ".concat(code));
this.childProcess = null;
_this._clearTimeout();
this._clearTimeout();
reject(new Error(data));
});
childProcess.on('error', function (error) {
console.log("Child process errored with ".concat(error));
_this._clearTimeout();
reject(error);
});
childProcess.on('close', function (code) {
console.log("Child process exited with ".concat(code));
_this.childProcess = null;
_this._clearTimeout();
resolve({});
});
} catch (error) {
reject(error);
}
});
case 12:
return _context.abrupt("return", _context.sent);
case 13:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function start(_x) {
return _start.apply(this, arguments);
resolve({});
});
} catch (error) {
reject(error);
}
});
}
return start;
}()
}, {
key: "stop",
value: function () {
var _stop = _asyncToGenerator(_regeneratorRuntime.mark(function _callee2() {
return _regeneratorRuntime.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
if (this.childProcess) {
this.childProcess.kill();
this.childProcess = null;
}
async stop() {
if (this.childProcess) {
this.childProcess.kill();
this.childProcess = null;
}
}
case 1:
case "end":
return _context2.stop();
}
}
}, _callee2, this);
}));
async exit(statusCode = 0) {
try {
await this.stop();
process.exit(statusCode);
} catch (error) {
console.error(error.message || error);
process.exit(1);
}
}
function stop() {
return _stop.apply(this, arguments);
}
_setTimeout(callback) {
if (Number(this.props.wait) > 0) {
this.successTimer = setTimeout(callback, this.props.wait);
}
}
return stop;
}()
}, {
key: "exit",
value: function () {
var _exit = _asyncToGenerator(_regeneratorRuntime.mark(function _callee3() {
var statusCode,
_args3 = arguments;
return _regeneratorRuntime.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
statusCode = _args3.length > 0 && _args3[0] !== undefined ? _args3[0] : 0;
_context3.prev = 1;
_context3.next = 4;
return this.stop();
case 4:
process.exit(statusCode);
_context3.next = 11;
break;
case 7:
_context3.prev = 7;
_context3.t0 = _context3["catch"](1);
console.error(_context3.t0.message || _context3.t0);
process.exit(1);
case 11:
case "end":
return _context3.stop();
}
}
}, _callee3, this, [[1, 7]]);
}));
function exit() {
return _exit.apply(this, arguments);
}
return exit;
}()
}, {
key: "_setTimeout",
value: function _setTimeout(callback) {
if (Number(this.props.wait) > 0) {
this.successTimer = setTimeout(callback, this.props.wait);
}
_clearTimeout() {
if (this.successTimer) {
clearTimeout(this.successTimer);
}
}, {
key: "_clearTimeout",
value: function _clearTimeout() {
if (this.successTimer) {
clearTimeout(this.successTimer);
}
}
}]);
}
return ChildProcessProxy;
}();
export { ChildProcessProxy as default };
}
//# sourceMappingURL=child-process-proxy.js.map
import ChildProcess from 'child_process';
export function getAvailablePort() {
var defaultPort = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 3000;
return new Promise(function (resolve) {
ChildProcess.exec('lsof -i -P -n | grep LISTEN', function (error, stdout) {
export function getAvailablePort(defaultPort = 3000) {
return new Promise(resolve => {
ChildProcess.exec('lsof -i -P -n | grep LISTEN', (error, stdout) => {
if (error) {

@@ -11,6 +10,6 @@ resolve(defaultPort);

var portsInUse = [];
var regex = /:(\d+) \(LISTEN\)/;
stdout.split('\n').forEach(function (line) {
var match = regex.exec(line);
const portsInUse = [];
const regex = /:(\d+) \(LISTEN\)/;
stdout.split('\n').forEach(line => {
const match = regex.exec(line);

@@ -21,3 +20,3 @@ if (match) {

});
var port = defaultPort;
let port = defaultPort;

@@ -24,0 +23,0 @@ while (portsInUse.includes(port)) {

@@ -1,8 +0,5 @@

import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator";
import _asyncIterator from "@babel/runtime/helpers/esm/asyncIterator";
import _regeneratorRuntime from "@babel/runtime/regenerator";
import AsyncQueue from '../async-queue/async-queue';
import WorkerBody from '../worker-farm/worker-body';
var inputBatches;
var options;
let inputBatches;
let options;
export function createWorker(process, processInBatches) {

@@ -13,153 +10,51 @@ if (typeof self === 'undefined') {

WorkerBody.onmessage = function () {
var _ref = _asyncToGenerator(_regeneratorRuntime.mark(function _callee(type, payload) {
var result, resultIterator, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, _value, batch;
WorkerBody.onmessage = async (type, payload) => {
try {
switch (type) {
case 'process':
if (!process) {
throw new Error('Worker does not support atomic processing');
}
return _regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.prev = 0;
_context.t0 = type;
_context.next = _context.t0 === 'process' ? 4 : _context.t0 === 'process-in-batches' ? 11 : _context.t0 === 'input-batch' ? 51 : _context.t0 === 'input-done' ? 53 : 55;
break;
const result = await process(payload.input, payload.options || {});
WorkerBody.postMessage('done', {
result
});
break;
case 4:
if (process) {
_context.next = 6;
break;
}
case 'process-in-batches':
if (!processInBatches) {
throw new Error('Worker does not support batched processing');
}
throw new Error('Worker does not support atomic processing');
inputBatches = new AsyncQueue();
options = payload.options || {};
const resultIterator = processInBatches(inputBatches, options);
case 6:
_context.next = 8;
return process(payload.input, payload.options || {});
for await (const batch of resultIterator) {
WorkerBody.postMessage('output-batch', {
result: batch
});
}
case 8:
result = _context.sent;
WorkerBody.postMessage('done', {
result: result
});
return _context.abrupt("break", 55);
WorkerBody.postMessage('done', {});
break;
case 11:
if (processInBatches) {
_context.next = 13;
break;
}
case 'input-batch':
inputBatches.push(payload.input);
break;
throw new Error('Worker does not support batched processing');
case 'input-done':
inputBatches.close();
break;
case 13:
inputBatches = new AsyncQueue();
options = payload.options || {};
resultIterator = processInBatches(inputBatches, options);
_iteratorNormalCompletion = true;
_didIteratorError = false;
_context.prev = 18;
_iterator = _asyncIterator(resultIterator);
case 20:
_context.next = 22;
return _iterator.next();
case 22:
_step = _context.sent;
_iteratorNormalCompletion = _step.done;
_context.next = 26;
return _step.value;
case 26:
_value = _context.sent;
if (_iteratorNormalCompletion) {
_context.next = 33;
break;
}
batch = _value;
WorkerBody.postMessage('output-batch', {
result: batch
});
case 30:
_iteratorNormalCompletion = true;
_context.next = 20;
break;
case 33:
_context.next = 39;
break;
case 35:
_context.prev = 35;
_context.t1 = _context["catch"](18);
_didIteratorError = true;
_iteratorError = _context.t1;
case 39:
_context.prev = 39;
_context.prev = 40;
if (!(!_iteratorNormalCompletion && _iterator.return != null)) {
_context.next = 44;
break;
}
_context.next = 44;
return _iterator.return();
case 44:
_context.prev = 44;
if (!_didIteratorError) {
_context.next = 47;
break;
}
throw _iteratorError;
case 47:
return _context.finish(44);
case 48:
return _context.finish(39);
case 49:
WorkerBody.postMessage('done', {});
return _context.abrupt("break", 55);
case 51:
inputBatches.push(payload.input);
return _context.abrupt("break", 55);
case 53:
inputBatches.close();
return _context.abrupt("break", 55);
case 55:
_context.next = 60;
break;
case 57:
_context.prev = 57;
_context.t2 = _context["catch"](0);
WorkerBody.postMessage('error', {
error: _context.t2.message
});
case 60:
case "end":
return _context.stop();
}
}
}, _callee, null, [[0, 57], [18, 35, 39, 49], [40,, 44, 48]]);
}));
return function (_x, _x2) {
return _ref.apply(this, arguments);
};
}();
default:
}
} catch (error) {
WorkerBody.postMessage('error', {
error: error.message
});
}
};
}
//# sourceMappingURL=create-worker.js.map

@@ -1,72 +0,34 @@

import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator";
import _regeneratorRuntime from "@babel/runtime/regenerator";
import WorkerFarm from '../worker-farm/worker-farm';
import { getWorkerObjectURL, getWorkerObjectName, removeNontransferableOptions } from './worker-object-utils';
export function processOnWorker(_x, _x2) {
return _processOnWorker.apply(this, arguments);
}
export async function processOnWorker(worker, data, options = {}) {
const name = getWorkerObjectName(worker);
const url = getWorkerObjectURL(worker, options);
const workerFarm = WorkerFarm.getWorkerFarm(options);
const workerPool = workerFarm.getWorkerPool({
name,
url
});
const job = await workerPool.startJob(worker.name, (job_, type, payload) => {
switch (type) {
case 'done':
job.done(payload);
break;
function _processOnWorker() {
_processOnWorker = _asyncToGenerator(_regeneratorRuntime.mark(function _callee(worker, data) {
var options,
name,
url,
workerFarm,
workerPool,
job,
transferableOptions,
result,
_args = arguments;
return _regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
options = _args.length > 2 && _args[2] !== undefined ? _args[2] : {};
name = getWorkerObjectName(worker);
url = getWorkerObjectURL(worker, options);
workerFarm = WorkerFarm.getWorkerFarm(options);
workerPool = workerFarm.getWorkerPool({
name: name,
url: url
});
_context.next = 7;
return workerPool.startJob(worker.name, function (job_, type, payload) {
switch (type) {
case 'done':
job.done(payload);
break;
case 'error':
job.error(payload.error);
break;
case 'error':
job.error(payload.error);
break;
default:
job.error(type);
break;
}
});
case 7:
job = _context.sent;
transferableOptions = removeNontransferableOptions(options);
job.postMessage('process', {
input: data,
options: transferableOptions
});
_context.next = 12;
return job.result;
case 12:
result = _context.sent;
return _context.abrupt("return", result.result);
case 14:
case "end":
return _context.stop();
}
}
}, _callee);
}));
return _processOnWorker.apply(this, arguments);
default:
job.error(type);
break;
}
});
const transferableOptions = removeNontransferableOptions(options);
job.postMessage('process', {
input: data,
options: transferableOptions
});
const result = await job.result;
return result.result;
}
//# sourceMappingURL=process-on-worker.js.map

@@ -1,10 +0,9 @@

import _typeof from "@babel/runtime/helpers/esm/typeof";
import { assert } from '../env-utils/assert';
var NPM_TAG = 'beta';
var VERSION = typeof "3.0.0-beta.1" !== 'undefined' ? "3.0.0-beta.1" : NPM_TAG;
const NPM_TAG = 'beta';
const VERSION = typeof "3.0.0-beta.2" !== 'undefined' ? "3.0.0-beta.2" : NPM_TAG;
export function getWorkerObjectURL(worker, options) {
var topOptions = options || {};
var workerOptions = topOptions[worker.id] || {};
var workerFile = "".concat(worker.id, "-worker.js");
var url = workerOptions.workerUrl;
const topOptions = options || {};
const workerOptions = topOptions[worker.id] || {};
const workerFile = "".concat(worker.id, "-worker.js");
let url = workerOptions.workerUrl;

@@ -16,3 +15,3 @@ if (topOptions._workerType === 'test') {

if (!url) {
var version = worker.version;
let version = worker.version;

@@ -23,3 +22,3 @@ if (version === 'latest') {

var versionTag = version ? "@".concat(version) : '';
const versionTag = version ? "@".concat(version) : '';
url = "https://unpkg.com/@loaders.gl/".concat(worker.module).concat(versionTag, "/dist/").concat(workerFile);

@@ -32,9 +31,8 @@ }

export function getWorkerObjectName(worker) {
var warning = worker.version !== VERSION ? " (lib@".concat(VERSION, ")") : '';
const warning = worker.version !== VERSION ? " (lib@".concat(VERSION, ")") : '';
return "".concat(worker.name, "-worker@").concat(worker.version).concat(warning);
}
export function validateWorkerVersion(worker) {
var coreVersion = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : VERSION;
export function validateWorkerVersion(worker, coreVersion = VERSION) {
assert(worker, 'no worker provided');
var workerVersion = worker.version;
const workerVersion = worker.version;

@@ -49,3 +47,3 @@ if (!coreVersion || !workerVersion) {

function parseVersion(version) {
var parts = version.split('.').map(Number);
const parts = version.split('.').map(Number);
return {

@@ -62,5 +60,5 @@ major: parts[0],

function stringifyJSON(v) {
var cache = new Set();
return JSON.stringify(v, function (key, value) {
if (_typeof(value) === 'object' && value !== null) {
const cache = new Set();
return JSON.stringify(v, (key, value) => {
if (typeof value === 'object' && value !== null) {
if (cache.has(value)) {

@@ -67,0 +65,0 @@ try {

import { assert } from '../env-utils/assert';
var workerURLCache = new Map();
const workerURLCache = new Map();
export function buildWorkerURL(props) {
assert(props.source && !props.url || !props.source && props.url);
var workerURL = workerURLCache.get(props.source || props.url);
let workerURL = workerURLCache.get(props.source || props.url);

@@ -28,3 +28,3 @@ if (!workerURL) {

var workerSource = buildScriptSource(url);
const workerSource = buildScriptSource(url);
return getWorkerURLFromSource(workerSource);

@@ -34,3 +34,3 @@ }

function getWorkerURLFromSource(workerSource) {
var blob = new Blob([workerSource], {
const blob = new Blob([workerSource], {
type: 'application/javascript'

@@ -37,0 +37,0 @@ });

@@ -1,6 +0,3 @@

import _typeof from "@babel/runtime/helpers/esm/typeof";
export function getTransferList(object) {
var recursive = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
var transfers = arguments.length > 2 ? arguments[2] : undefined;
var transfersSet = transfers || new Set();
export function getTransferList(object, recursive = true, transfers) {
const transfersSet = transfers || new Set();

@@ -11,4 +8,4 @@ if (!object) {} else if (isTransferable(object)) {

transfersSet.add(object.buffer);
} else if (ArrayBuffer.isView(object)) {} else if (recursive && _typeof(object) === 'object') {
for (var key in object) {
} else if (ArrayBuffer.isView(object)) {} else if (recursive && typeof object === 'object') {
for (const key in object) {
getTransferList(object[key], recursive, transfersSet);

@@ -15,0 +12,0 @@ }

@@ -1,15 +0,23 @@

import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
import _createClass from "@babel/runtime/helpers/esm/createClass";
import { getTransferList } from '../worker-farm/get-transfer-list';
var onMessageWrapperMap = new Map();
const onMessageWrapperMap = new Map();
export default class WorkerBody {
static set onmessage(onMessage) {
self.onmessage = message => {
if (!isKnownMessage(message)) {
return;
}
var WorkerBody = function () {
function WorkerBody() {
_classCallCheck(this, WorkerBody);
const {
type,
payload
} = message.data;
onMessage(type, payload);
};
}
_createClass(WorkerBody, null, [{
key: "onmessage",
set: function set(onMessage) {
self.onmessage = function (message) {
static addEventListener(onMessage) {
let onMessageWrapper = onMessageWrapperMap.get(onMessage);
if (!onMessageWrapper) {
onMessageWrapper = message => {
if (!isKnownMessage(message)) {

@@ -19,60 +27,40 @@ return;

var _message$data = message.data,
type = _message$data.type,
payload = _message$data.payload;
const {
type,
payload
} = message.data;
onMessage(type, payload);
};
}
}, {
key: "addEventListener",
value: function addEventListener(onMessage) {
var onMessageWrapper = onMessageWrapperMap.get(onMessage);
if (!onMessageWrapper) {
onMessageWrapper = function onMessageWrapper(message) {
if (!isKnownMessage(message)) {
return;
}
self.addEventListener('message', onMessageWrapper);
}
var _message$data2 = message.data,
type = _message$data2.type,
payload = _message$data2.payload;
onMessage(type, payload);
};
}
static removeEventListener(onMessage) {
const onMessageWrapper = onMessageWrapperMap.get(onMessage);
onMessageWrapperMap.delete(onMessage);
self.removeEventListener('message', onMessageWrapper);
}
self.addEventListener('message', onMessageWrapper);
static postMessage(type, payload) {
if (self) {
const data = {
source: 'loaders.gl',
type,
payload
};
const transferList = getTransferList(payload);
self.postMessage(data, transferList);
}
}, {
key: "removeEventListener",
value: function removeEventListener(onMessage) {
var onMessageWrapper = onMessageWrapperMap.get(onMessage);
onMessageWrapperMap.delete(onMessage);
self.removeEventListener('message', onMessageWrapper);
}
}, {
key: "postMessage",
value: function postMessage(type, payload) {
if (self) {
var data = {
source: 'loaders.gl',
type: type,
payload: payload
};
var transferList = getTransferList(payload);
self.postMessage(data, transferList);
}
}
}]);
}
return WorkerBody;
}();
}
export { WorkerBody as default };
function isKnownMessage(message) {
var type = message.type,
data = message.data;
const {
type,
data
} = message;
return type === 'message' && data && typeof data.source === 'string' && data.source.startsWith('loaders.gl');
}
//# sourceMappingURL=worker-body.js.map

@@ -1,28 +0,24 @@

import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
import _createClass from "@babel/runtime/helpers/esm/createClass";
import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
import WorkerPool from './worker-pool';
import WorkerThread from './worker-thread';
var DEFAULT_PROPS = {
const DEFAULT_PROPS = {
maxConcurrency: 3,
maxMobileConcurrency: 1,
onDebug: function onDebug() {},
onDebug: () => {},
reuseWorkers: true
};
export default class WorkerFarm {
static isSupported() {
return WorkerThread.isSupported();
}
var WorkerFarm = function () {
function WorkerFarm(props) {
_classCallCheck(this, WorkerFarm);
static getWorkerFarm(props = {}) {
WorkerFarm._workerFarm = WorkerFarm._workerFarm || new WorkerFarm({});
WorkerFarm._workerFarm.setProps(props);
return WorkerFarm._workerFarm;
}
constructor(props) {
_defineProperty(this, "props", void 0);

@@ -32,3 +28,4 @@

this.props = _objectSpread({}, DEFAULT_PROPS);
this.props = { ...DEFAULT_PROPS
};
this.setProps(props);

@@ -38,91 +35,51 @@ this.workerPools = new Map();

_createClass(WorkerFarm, [{
key: "destroy",
value: function destroy() {
var _iterator = _createForOfIteratorHelper(this.workerPools.values()),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var workerPool = _step.value;
workerPool.destroy();
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
destroy() {
for (const workerPool of this.workerPools.values()) {
workerPool.destroy();
}
}, {
key: "setProps",
value: function setProps(props) {
this.props = _objectSpread(_objectSpread({}, this.props), props);
}
var _iterator2 = _createForOfIteratorHelper(this.workerPools.values()),
_step2;
setProps(props) {
this.props = { ...this.props,
...props
};
try {
for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
var workerPool = _step2.value;
workerPool.setProps(this._getWorkerPoolProps());
}
} catch (err) {
_iterator2.e(err);
} finally {
_iterator2.f();
}
for (const workerPool of this.workerPools.values()) {
workerPool.setProps(this._getWorkerPoolProps());
}
}, {
key: "getWorkerPool",
value: function getWorkerPool(options) {
var name = options.name,
source = options.source,
url = options.url;
var workerPool = this.workerPools.get(name);
}
if (!workerPool) {
workerPool = new WorkerPool({
name: name,
source: source,
url: url
});
workerPool.setProps(this._getWorkerPoolProps());
this.workerPools.set(name, workerPool);
}
getWorkerPool(options) {
const {
name,
source,
url
} = options;
let workerPool = this.workerPools.get(name);
return workerPool;
if (!workerPool) {
workerPool = new WorkerPool({
name,
source,
url
});
workerPool.setProps(this._getWorkerPoolProps());
this.workerPools.set(name, workerPool);
}
}, {
key: "_getWorkerPoolProps",
value: function _getWorkerPoolProps() {
return {
maxConcurrency: this.props.maxConcurrency,
maxMobileConcurrency: this.props.maxMobileConcurrency,
reuseWorkers: this.props.reuseWorkers,
onDebug: this.props.onDebug
};
}
}], [{
key: "isSupported",
value: function isSupported() {
return WorkerThread.isSupported();
}
}, {
key: "getWorkerFarm",
value: function getWorkerFarm() {
var props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
WorkerFarm._workerFarm = WorkerFarm._workerFarm || new WorkerFarm({});
WorkerFarm._workerFarm.setProps(props);
return workerPool;
}
return WorkerFarm._workerFarm;
}
}]);
_getWorkerPoolProps() {
return {
maxConcurrency: this.props.maxConcurrency,
maxMobileConcurrency: this.props.maxMobileConcurrency,
reuseWorkers: this.props.reuseWorkers,
onDebug: this.props.onDebug
};
}
return WorkerFarm;
}();
}
_defineProperty(WorkerFarm, "_workerFarm", void 0);
export { WorkerFarm as default };
//# sourceMappingURL=worker-farm.js.map

@@ -1,12 +0,5 @@

import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
import _createClass from "@babel/runtime/helpers/esm/createClass";
import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
import { assert } from '../env-utils/assert';
var WorkerJob = function () {
function WorkerJob(jobName, workerThread) {
var _this = this;
_classCallCheck(this, WorkerJob);
export default class WorkerJob {
constructor(jobName, workerThread) {
_defineProperty(this, "name", void 0);

@@ -28,43 +21,35 @@

this._resolve = function () {};
this._resolve = () => {};
this._reject = function () {};
this._reject = () => {};
this.result = new Promise(function (resolve, reject) {
_this._resolve = resolve;
_this._reject = reject;
this.result = new Promise((resolve, reject) => {
this._resolve = resolve;
this._reject = reject;
});
}
_createClass(WorkerJob, [{
key: "postMessage",
value: function postMessage(type, payload) {
this.workerThread.postMessage({
source: 'loaders.gl',
type: type,
payload: payload
});
}
}, {
key: "done",
value: function done(value) {
assert(this.isRunning);
this.isRunning = false;
postMessage(type, payload) {
this.workerThread.postMessage({
source: 'loaders.gl',
type,
payload
});
}
this._resolve(value);
}
}, {
key: "error",
value: function error(_error) {
assert(this.isRunning);
this.isRunning = false;
done(value) {
assert(this.isRunning);
this.isRunning = false;
this._reject(_error);
}
}]);
this._resolve(value);
}
return WorkerJob;
}();
error(error) {
assert(this.isRunning);
this.isRunning = false;
export { WorkerJob as default };
this._reject(error);
}
}
//# sourceMappingURL=worker-job.js.map

@@ -1,19 +0,7 @@

import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator";
import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
import _createClass from "@babel/runtime/helpers/esm/createClass";
import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
import _regeneratorRuntime from "@babel/runtime/regenerator";
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
import { isMobile } from '../env-utils/globals';
import WorkerThread from './worker-thread';
import WorkerJob from './worker-job';
var WorkerPool = function () {
function WorkerPool(props) {
_classCallCheck(this, WorkerPool);
export default class WorkerPool {
constructor(props) {
_defineProperty(this, "name", 'unnamed');

@@ -29,3 +17,3 @@

_defineProperty(this, "onDebug", function () {});
_defineProperty(this, "onDebug", () => {});

@@ -49,209 +37,123 @@ _defineProperty(this, "reuseWorkers", true);

_createClass(WorkerPool, [{
key: "destroy",
value: function destroy() {
this.idleQueue.forEach(function (worker) {
return worker.destroy();
});
this.isDestroyed = true;
}
}, {
key: "setProps",
value: function setProps(props) {
this.props = _objectSpread(_objectSpread({}, this.props), props);
destroy() {
this.idleQueue.forEach(worker => worker.destroy());
this.isDestroyed = true;
}
if (props.name !== undefined) {
this.name = props.name;
}
setProps(props) {
this.props = { ...this.props,
...props
};
if (props.maxConcurrency !== undefined) {
this.maxConcurrency = props.maxConcurrency;
}
if (props.name !== undefined) {
this.name = props.name;
}
if (props.maxMobileConcurrency !== undefined) {
this.maxMobileConcurrency = props.maxMobileConcurrency;
}
if (props.maxConcurrency !== undefined) {
this.maxConcurrency = props.maxConcurrency;
}
if (props.reuseWorkers !== undefined) {
this.reuseWorkers = props.reuseWorkers;
}
if (props.maxMobileConcurrency !== undefined) {
this.maxMobileConcurrency = props.maxMobileConcurrency;
}
if (props.onDebug !== undefined) {
this.onDebug = props.onDebug;
}
if (props.reuseWorkers !== undefined) {
this.reuseWorkers = props.reuseWorkers;
}
}, {
key: "startJob",
value: function () {
var _startJob = _asyncToGenerator(_regeneratorRuntime.mark(function _callee(name) {
var _this = this;
var onMessage,
onError,
startPromise,
_args = arguments;
return _regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
onMessage = _args.length > 1 && _args[1] !== undefined ? _args[1] : function (job, type, data) {
return job.done(data);
};
onError = _args.length > 2 && _args[2] !== undefined ? _args[2] : function (job, error) {
return job.error(error);
};
startPromise = new Promise(function (onStart) {
_this.jobQueue.push({
name: name,
onMessage: onMessage,
onError: onError,
onStart: onStart
});
if (props.onDebug !== undefined) {
this.onDebug = props.onDebug;
}
}
return _this;
});
async startJob(name, onMessage = (job, type, data) => job.done(data), onError = (job, error) => job.error(error)) {
const startPromise = new Promise(onStart => {
this.jobQueue.push({
name,
onMessage,
onError,
onStart
});
return this;
});
this._startQueuedJob();
this._startQueuedJob();
_context.next = 6;
return startPromise;
return await startPromise;
}
case 6:
return _context.abrupt("return", _context.sent);
async _startQueuedJob() {
if (!this.jobQueue.length) {
return;
}
case 7:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
const workerThread = this._getAvailableWorker();
function startJob(_x) {
return _startJob.apply(this, arguments);
}
if (!workerThread) {
return;
}
return startJob;
}()
}, {
key: "_startQueuedJob",
value: function () {
var _startQueuedJob2 = _asyncToGenerator(_regeneratorRuntime.mark(function _callee2() {
var workerThread, queuedJob, _job;
const queuedJob = this.jobQueue.shift();
return _regeneratorRuntime.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
if (this.jobQueue.length) {
_context2.next = 2;
break;
}
if (queuedJob) {
this.onDebug({
message: 'Starting job',
name: queuedJob.name,
workerThread,
backlog: this.jobQueue.length
});
const job = new WorkerJob(queuedJob.name, workerThread);
return _context2.abrupt("return");
workerThread.onMessage = data => queuedJob.onMessage(job, data.type, data.payload);
case 2:
workerThread = this._getAvailableWorker();
workerThread.onError = error => queuedJob.onError(job, error);
if (workerThread) {
_context2.next = 5;
break;
}
queuedJob.onStart(job);
return _context2.abrupt("return");
case 5:
queuedJob = this.jobQueue.shift();
if (!queuedJob) {
_context2.next = 18;
break;
}
this.onDebug({
message: 'Starting job',
name: queuedJob.name,
workerThread: workerThread,
backlog: this.jobQueue.length
});
_job = new WorkerJob(queuedJob.name, workerThread);
workerThread.onMessage = function (data) {
return queuedJob.onMessage(_job, data.type, data.payload);
};
workerThread.onError = function (error) {
return queuedJob.onError(_job, error);
};
queuedJob.onStart(_job);
_context2.prev = 12;
_context2.next = 15;
return _job.result;
case 15:
_context2.prev = 15;
this.returnWorkerToQueue(workerThread);
return _context2.finish(15);
case 18:
case "end":
return _context2.stop();
}
}
}, _callee2, this, [[12,, 15, 18]]);
}));
function _startQueuedJob() {
return _startQueuedJob2.apply(this, arguments);
try {
await job.result;
} finally {
this.returnWorkerToQueue(workerThread);
}
}
}
return _startQueuedJob;
}()
}, {
key: "returnWorkerToQueue",
value: function returnWorkerToQueue(worker) {
var shouldDestroyWorker = this.isDestroyed || !this.reuseWorkers || this.count > this._getMaxConcurrency();
returnWorkerToQueue(worker) {
const shouldDestroyWorker = this.isDestroyed || !this.reuseWorkers || this.count > this._getMaxConcurrency();
if (shouldDestroyWorker) {
worker.destroy();
this.count--;
} else {
this.idleQueue.push(worker);
}
if (shouldDestroyWorker) {
worker.destroy();
this.count--;
} else {
this.idleQueue.push(worker);
}
if (!this.isDestroyed) {
this._startQueuedJob();
}
if (!this.isDestroyed) {
this._startQueuedJob();
}
}, {
key: "_getAvailableWorker",
value: function _getAvailableWorker() {
if (this.idleQueue.length > 0) {
return this.idleQueue.shift() || null;
}
}
if (this.count < this._getMaxConcurrency()) {
this.count++;
var name = "".concat(this.name.toLowerCase(), " (#").concat(this.count, " of ").concat(this.maxConcurrency, ")");
return new WorkerThread({
name: name,
source: this.source,
url: this.url
});
}
_getAvailableWorker() {
if (this.idleQueue.length > 0) {
return this.idleQueue.shift() || null;
}
return null;
if (this.count < this._getMaxConcurrency()) {
this.count++;
const name = "".concat(this.name.toLowerCase(), " (#").concat(this.count, " of ").concat(this.maxConcurrency, ")");
return new WorkerThread({
name,
source: this.source,
url: this.url
});
}
}, {
key: "_getMaxConcurrency",
value: function _getMaxConcurrency() {
return isMobile ? this.maxMobileConcurrency : this.maxConcurrency;
}
}]);
return WorkerPool;
}();
return null;
}
export { WorkerPool as default };
_getMaxConcurrency() {
return isMobile ? this.maxMobileConcurrency : this.maxConcurrency;
}
}
//# sourceMappingURL=worker-pool.js.map

@@ -1,3 +0,1 @@

import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
import _createClass from "@babel/runtime/helpers/esm/createClass";
import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";

@@ -8,8 +6,10 @@ import { assert } from '../env-utils/assert';

var NOOP = function NOOP() {};
const NOOP = () => {};
var WorkerThread = function () {
function WorkerThread(props) {
_classCallCheck(this, WorkerThread);
export default class WorkerThread {
static isSupported() {
return typeof Worker !== 'undefined';
}
constructor(props) {
_defineProperty(this, "name", void 0);

@@ -31,5 +31,7 @@

var name = props.name,
source = props.source,
url = props.url;
const {
name,
source,
url
} = props;
assert(source || url);

@@ -41,5 +43,3 @@ this.name = name;

this.onError = function (error) {
return console.log(error);
};
this.onError = error => console.log(error);

@@ -49,81 +49,61 @@ this.worker = this._createBrowserWorker();

_createClass(WorkerThread, [{
key: "destroy",
value: function destroy() {
this.onMessage = NOOP;
this.onError = NOOP;
this.worker.terminate();
this.terminated = true;
}
}, {
key: "isRunning",
get: function get() {
return Boolean(this.onMessage);
}
}, {
key: "postMessage",
value: function postMessage(data, transferList) {
transferList = transferList || getTransferList(data);
this.worker.postMessage(data, transferList);
}
}, {
key: "_getErrorFromErrorEvent",
value: function _getErrorFromErrorEvent(event) {
var message = 'Failed to load ';
message += "worker ".concat(this.name, ". ");
destroy() {
this.onMessage = NOOP;
this.onError = NOOP;
this.worker.terminate();
this.terminated = true;
}
if (event.message) {
message += "".concat(event.message, " in ");
}
get isRunning() {
return Boolean(this.onMessage);
}
if (event.lineno) {
message += ":".concat(event.lineno, ":").concat(event.colno);
}
postMessage(data, transferList) {
transferList = transferList || getTransferList(data);
this.worker.postMessage(data, transferList);
}
return new Error(message);
_getErrorFromErrorEvent(event) {
let message = 'Failed to load ';
message += "worker ".concat(this.name, ". ");
if (event.message) {
message += "".concat(event.message, " in ");
}
}, {
key: "_createBrowserWorker",
value: function _createBrowserWorker() {
var _this = this;
this._loadableURL = buildWorkerURL({
source: this.source,
url: this.url
});
var worker = new Worker(this._loadableURL, {
name: this.name
});
if (event.lineno) {
message += ":".concat(event.lineno, ":").concat(event.colno);
}
worker.onmessage = function (event) {
if (!event.data) {
_this.onError(new Error('No data received'));
} else {
_this.onMessage(event.data);
}
};
return new Error(message);
}
worker.onerror = function (error) {
_this.onError(_this._getErrorFromErrorEvent(error));
_createBrowserWorker() {
this._loadableURL = buildWorkerURL({
source: this.source,
url: this.url
});
const worker = new Worker(this._loadableURL, {
name: this.name
});
_this.terminated = true;
};
worker.onmessage = event => {
if (!event.data) {
this.onError(new Error('No data received'));
} else {
this.onMessage(event.data);
}
};
worker.onmessageerror = function (event) {
return console.error(event);
};
worker.onerror = error => {
this.onError(this._getErrorFromErrorEvent(error));
this.terminated = true;
};
return worker;
}
}], [{
key: "isSupported",
value: function isSupported() {
return typeof Worker !== 'undefined';
}
}]);
worker.onmessageerror = event => console.error(event);
return WorkerThread;
}();
return worker;
}
export { WorkerThread as default };
}
//# sourceMappingURL=worker-thread.js.map
import { assert } from '../env-utils/assert';
var workerURLCache = new Map();
const workerURLCache = new Map();
export function getWorkerURL(workerSource) {

@@ -10,6 +10,6 @@ assert(typeof workerSource === 'string', 'worker source');

var workerURL = workerURLCache.get(workerSource);
let workerURL = workerURLCache.get(workerSource);
if (!workerURL) {
var blob = new Blob([workerSource], {
const blob = new Blob([workerSource], {
type: 'application/javascript'

@@ -16,0 +16,0 @@ });

@@ -1,24 +0,5 @@

import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator";
import _regeneratorRuntime from "@babel/runtime/regenerator";
import { createWorker } from '../lib/worker-api/create-worker';
createWorker(function () {
var _ref = _asyncToGenerator(_regeneratorRuntime.mark(function _callee(data) {
return _regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
return _context.abrupt("return", data);
case 1:
case "end":
return _context.stop();
}
}
}, _callee);
}));
return function (_x) {
return _ref.apply(this, arguments);
};
}());
createWorker(async data => {
return data;
});
//# sourceMappingURL=null-worker.js.map

@@ -91,3 +91,3 @@ /******/ (function(modules) { // webpackBootstrap

/*!**************************************************************************************************!*\
!*** /home/user/apps/loaders.gl_duplicate/node_modules/@babel/runtime/helpers/defineProperty.js ***!
!*** /home/daniil/actionengine/loaders.gl/node_modules/@babel/runtime/helpers/defineProperty.js ***!
\**************************************************************************************************/

@@ -94,0 +94,0 @@ /*! no static exports found */

{
"name": "@loaders.gl/worker-utils",
"version": "3.0.0-beta.1",
"version": "3.0.0-beta.2",
"description": "Utilities for running tasks on worker threads",

@@ -44,3 +44,3 @@ "license": "MIT",

},
"gitHead": "2fb06018114d18a86143d10a8a02341a0b9a01a9"
"gitHead": "c9417c6232ad2109a9c269ecf83afbf7ebc46cf8"
}

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc