Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

threads

Package Overview
Dependencies
Maintainers
1
Versions
73
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

threads - npm Package Compare versions

Comparing version 0.5.4 to 0.6.1

test/spec-src/pool-functional.spec.js

2

bower.json
{
"name": "threads",
"version": "0.5.3",
"version": "0.6.1",
"main": "dist/thread.browser.js",

@@ -5,0 +5,0 @@ "homepage": "https://github.com/andywer/threads.js",

@@ -195,2 +195,3 @@ require=(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({"./defaults":[function(require,module,exports){

this.emit.apply(this, ['message'].concat(responseArgs));
this.emit.apply(this, ['done'].concat(responseArgs)); // this one is just for convenience
}

@@ -356,3 +357,3 @@ };

this.runArgs = [];
this.clearSendParameter();
this.sendArgs = [];

@@ -384,11 +385,3 @@ pool.emit('newJob', this);

if (this.hasSendParameter()) {
var _clone$clearSendParameter;
// do not alter this job, clone it and set send param instead
return (_clone$clearSendParameter = this.clone().clearSendParameter()).send.apply(_clone$clearSendParameter, args);
}
this.sendArgs = args;
this.parameterSet = true;

@@ -405,2 +398,4 @@ this.emit('readyToRun');

this.thread = thread;
this.emit('threadChanged');
return this;

@@ -410,31 +405,17 @@ };

Job.prototype.promise = function promise() {
if (!this.thread) {
throw new Error('Cannot return promise, since job is not executed.');
}
return this.thread.promise();
};
var _this = this;
Job.prototype.clone = function clone() {
var clone = new Job(this.pool);
if (this.runArgs.length > 0) {
clone.run.apply(clone, this.runArgs);
}
if (this.parameterSet) {
clone.send.apply(clone, this.sendArgs);
}
return clone;
// Always return a promise
return new Promise(function (resolve) {
// If the thread isn't set, listen for the threadChanged event
if (!_this.thread) {
_this.once('threadChanged', function () {
resolve(_this.thread.promise());
});
} else {
resolve(_this.thread.promise());
}
});
};
Job.prototype.hasSendParameter = function hasSendParameter() {
return this.parameterSet;
};
Job.prototype.clearSendParameter = function clearSendParameter() {
this.parameterSet = false;
this.sendArgs = [];
return this;
};
return Job;

@@ -482,3 +463,3 @@ })(_eventemitter32['default']);

this.jobQueue = [];
this.lastCreatedJob = null;
this.runArgs = [];

@@ -488,17 +469,15 @@ this.on('newJob', this.handleNewJob.bind(this));

Pool.prototype.run = function run() {
var _ref;
return (_ref = new _job2['default'](this)).run.apply(_ref, arguments);
Pool.prototype.run = function run(args) {
this.runArgs = args;
return this;
};
Pool.prototype.send = function send() {
var _lastCreatedJob;
if (!this.lastCreatedJob) {
if (!this.runArgs) {
throw new Error('Pool.send() called without prior Pool.run(). You need to define what to run first.');
}
// this will not alter the last job, but rather clone it and set this params on the new job
return (_lastCreatedJob = this.lastCreatedJob).send.apply(_lastCreatedJob, arguments);
var job = new _job2['default'](this);
job.run(this.runArgs);
return job.send.apply(job, arguments);
};

@@ -519,3 +498,3 @@

if (this.jobQueue.length === 0 || this.idleThreads.length === 0) {
return;
return this.once('threadAvailable', this.dequeue);
}

@@ -526,3 +505,3 @@

job.on('done', this.handleJobSuccess.bind(this, thread, job)).on('error', this.handleJobError.bind(this, thread, job));
job.once('done', this.handleJobSuccess.bind(this, thread, job)).once('error', this.handleJobError.bind(this, thread, job));

@@ -534,3 +513,3 @@ job.executeOn(thread);

this.lastCreatedJob = job;
job.on('readyToRun', this.queueJob.bind(this, job)); // triggered by job.send()
job.once('readyToRun', this.queueJob.bind(this, job)); // triggered by job.send()
};

@@ -556,3 +535,3 @@

this.idleThreads.push(thread);
this.dequeue();
this.emit('threadAvailable');

@@ -559,0 +538,0 @@ if (this.idleThreads.length === this.threads.length) {

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

require=function e(t,n,r){function o(s,a){if(!n[s]){if(!t[s]){var u="function"==typeof require&&require;if(!a&&u)return u(s,!0);if(i)return i(s,!0);var f=new Error("Cannot find module '"+s+"'");throw f.code="MODULE_NOT_FOUND",f}var c=n[s]={exports:{}};t[s][0].call(c.exports,function(e){var n=t[s][1][e];return o(n?n:e)},c,c.exports,e,t,n,r)}return n[s].exports}for(var i="function"==typeof require&&require,s=0;s<r.length;s++)o(r[s]);return o}({"./defaults":[function(e,t,n){"use strict";n.__esModule=!0,n["default"]={pool:{size:navigator.hardwareConcurrency||8}},t.exports=n["default"]},{}],1:[function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}var o=e("./index"),i=r(o);"object"==typeof window&&(window.thread=i["default"]),"function"==typeof define?define([],function(){return i["default"]}):"object"==typeof t&&(t.exports=i["default"])},{"./index":3}],"./worker":[function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function s(e){var t=p.getConfig().basepath.web;return t?t+"/"+e:e}function a(e){for(var t=[],n=0;"undefined"!=typeof e[n];)t.push(e[n]),n++;return t}function u(e){if(e.stack)console.error(e.stack);else if(e.message&&e.filename&&e.lineno){var t=e.filename.match(/^data:text\/javascript/)&&e.filename.length>50?e.filename.substr(0,50)+"...":e.filename;console.error(e.message+" @"+t+":"+e.lineno)}else console.error(e)}n.__esModule=!0;var f=e("eventemitter3"),c=r(f),l=e("./slave-code-uri"),h=r(l),p=e("../config");if("object"!=typeof window.Worker&&"function"!=typeof window.Worker)throw new Error("Browser does not support web workers!");var d=function(e){function t(){var n=arguments.length<=0||void 0===arguments[0]?null:arguments[0],r=arguments.length<=1||void 0===arguments[1]?[]:arguments[1];o(this,t),e.call(this),this.initWorker(),this.worker.addEventListener("message",this.handleMessage.bind(this)),this.worker.addEventListener("error",this.handleError.bind(this)),n&&this.run(n,r)}return i(t,e),t.prototype.initWorker=function(){try{this.worker=new window.Worker(h["default"])}catch(e){var t=p.getConfig().fallback.slaveScriptUrl;if(!t)throw e;this.worker=new window.Worker(h["default"])}},t.prototype.run=function(e){var t=arguments.length<=1||void 0===arguments[1]?[]:arguments[1];return"function"==typeof e?this.runMethod(e,t):this.runScripts(e,t),this},t.prototype.runMethod=function(e,t){var n=e.toString(),r=n.substring(n.indexOf("(")+1,n.indexOf(")")).split(","),o=n.substring(n.indexOf("{")+1,n.lastIndexOf("}"));this.worker.postMessage({initByMethod:!0,method:{args:r,body:o},scripts:t.map(s)})},t.prototype.runScripts=function(e,t){if(!e)throw new Error("Must pass a function or a script URL to run().");this.worker.postMessage({initByScripts:!0,scripts:t.concat([e]).map(s)})},t.prototype.send=function(e){var t=arguments.length<=1||void 0===arguments[1]?[]:arguments[1];return this.worker.postMessage({doRun:!0,param:e},t),this},t.prototype.kill=function(){return this.worker.terminate(),this.emit("exit"),this},t.prototype.promise=function(){var e=this;return new Promise(function(t,n){e.once("message",t).once("error",n)})},t.prototype.handleMessage=function(e){if(e.data.error)this.handleError(e.data.error);else if(e.data.progress)this.handleProgress(e.data.progress);else{var t=a(e.data.response);this.emit.apply(this,["message"].concat(t))}},t.prototype.handleProgress=function(e){this.emit("progress",e)},t.prototype.handleError=function(e){this.listeners("error",!0)||u(e),e.preventDefault&&e.preventDefault(),this.emit("error",e)},t}(c["default"]);n["default"]=d,t.exports=n["default"]},{"../config":2,"./slave-code-uri":6,eventemitter3:8}],2:[function(e,t,n){"use strict";function r(e,t){var n=arguments.length<=2||void 0===arguments[2]?[]:arguments[2];Object.keys(t).forEach(function(o){var i=t[o],s=n.concat([o]);if("object"==typeof i){if("undefined"!=typeof e[o]&&"object"!=typeof e[o])throw new Error("Expected config property not to be an object: "+s.join("."));r(e[o],i,s)}else{if("object"==typeof e[o])throw new Error("Expected config property to be an object: "+s.join("."));e[o]=i}})}function o(){return a.get()}function i(){return a.set.apply(a,arguments)}n.__esModule=!0,n.getConfig=o,n.setConfig=i;var s={basepath:{node:"",web:""},fallback:{slaveScriptUrl:""}},a={get:function(){return s},set:function(e){if("object"!=typeof e)throw new Error("Expected config object.");r(s,e)}};n["default"]=a},{}],3:[function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(){var e=arguments.length<=0||void 0===arguments[0]?null:arguments[0],t=arguments.length<=1||void 0===arguments[1]?[]:arguments[1];return new h["default"](e,t)}n.__esModule=!0,n.spawn=o,e("native-promise-only");var i=e("./config"),s=r(i),a=e("./defaults"),u=r(a),f=e("./pool"),c=r(f),l=e("./worker"),h=r(l);n.config=s["default"],n.defaults=u["default"],n.Pool=c["default"],n["default"]={config:s["default"],defaults:u["default"],Pool:c["default"],spawn:o,Worker:h["default"]}},{"./config":2,"./defaults":"./defaults","./pool":5,"./worker":"./worker","native-promise-only":9}],4:[function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}n.__esModule=!0;var s=e("eventemitter3"),a=r(s),u=function(e){function t(n){o(this,t),e.call(this),this.pool=n,this.thread=null,this.runArgs=[],this.clearSendParameter(),n.emit("newJob",this)}return i(t,e),t.prototype.run=function(){for(var e=arguments.length,t=Array(e),n=0;e>n;n++)t[n]=arguments[n];if(0===t.length)throw new Error("Cannot call .run() without arguments.");return this.runArgs=t,this},t.prototype.send=function(){if(0===this.runArgs.length)throw new Error("Cannot .send() before .run().");for(var e=arguments.length,t=Array(e),n=0;e>n;n++)t[n]=arguments[n];if(this.hasSendParameter()){var r;return(r=this.clone().clearSendParameter()).send.apply(r,t)}return this.sendArgs=t,this.parameterSet=!0,this.emit("readyToRun"),this},t.prototype.executeOn=function(e){var t,n;return(t=(n=e.once("message",this.emit.bind(this,"done")).once("error",this.emit.bind(this,"error"))).run.apply(n,this.runArgs)).send.apply(t,this.sendArgs),this.thread=e,this},t.prototype.promise=function(){if(!this.thread)throw new Error("Cannot return promise, since job is not executed.");return this.thread.promise()},t.prototype.clone=function n(){var n=new t(this.pool);return this.runArgs.length>0&&n.run.apply(n,this.runArgs),this.parameterSet&&n.send.apply(n,this.sendArgs),n},t.prototype.hasSendParameter=function(){return this.parameterSet},t.prototype.clearSendParameter=function(){return this.parameterSet=!1,this.sendArgs=[],this},t}(a["default"]);n["default"]=u,t.exports=n["default"]},{eventemitter3:8}],5:[function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}n.__esModule=!0;var s=e("eventemitter3"),a=r(s),u=e("./job"),f=r(u),c=e("./defaults"),l=r(c),h=e("./"),p=function(e){function t(n){o(this,t),e.call(this),this.threads=t.spawn(n||l["default"].pool.size),this.idleThreads=this.threads.slice(),this.jobQueue=[],this.lastCreatedJob=null,this.on("newJob",this.handleNewJob.bind(this))}return i(t,e),t.prototype.run=function(){var e;return(e=new f["default"](this)).run.apply(e,arguments)},t.prototype.send=function(){var e;if(!this.lastCreatedJob)throw new Error("Pool.send() called without prior Pool.run(). You need to define what to run first.");return(e=this.lastCreatedJob).send.apply(e,arguments)},t.prototype.killAll=function(){this.threads.forEach(function(e){e.kill()})},t.prototype.queueJob=function(e){this.jobQueue.push(e),this.dequeue()},t.prototype.dequeue=function(){if(0!==this.jobQueue.length&&0!==this.idleThreads.length){var e=this.jobQueue.shift(),t=this.idleThreads.shift();e.on("done",this.handleJobSuccess.bind(this,t,e)).on("error",this.handleJobError.bind(this,t,e)),e.executeOn(t)}},t.prototype.handleNewJob=function(e){this.lastCreatedJob=e,e.on("readyToRun",this.queueJob.bind(this,e))},t.prototype.handleJobSuccess=function(e,t){for(var n=arguments.length,r=Array(n>2?n-2:0),o=2;n>o;o++)r[o-2]=arguments[o];this.emit.apply(this,["done",t].concat(r)),this.handleJobDone(e)},t.prototype.handleJobError=function(e,t,n){this.emit("error",t,n),this.handleJobDone(e)},t.prototype.handleJobDone=function(e){var t=this;this.idleThreads.push(e),this.dequeue(),this.idleThreads.length===this.threads.length&&setTimeout(function(){t.emit("finished")},0)},t}(a["default"]);n["default"]=p,p.spawn=function(e){for(var t=[],n=0;e>n;n++)t.push(h.spawn());return t},t.exports=n["default"]},{"./":3,"./defaults":"./defaults","./job":4,eventemitter3:8}],6:[function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}n.__esModule=!0;var o=e("./slave-code"),i=r(o),s="data:text/javascript;charset=utf-8,"+encodeURI(i["default"]),a=window.createBlobURL||window.createObjectURL;if(!a){var u=window.URL||window.webkitURL;if(!u)throw new Error("No Blob creation implementation found.");a=u.createObjectURL}if("function"==typeof window.BlobBuilder&&"function"==typeof a){var f=new window.BlobBuilder;f.append(i["default"]),s=a(f.getBlob())}else if("function"==typeof window.Blob&&"function"==typeof a){var c=new window.Blob([i["default"]],{type:"text/javascript"});s=a(c)}n["default"]=s,t.exports=n["default"]},{"./slave-code":7}],7:[function(e,t,n){t.exports="/*eslint-env worker*/\n/*global importScripts*/\n/*eslint-disable no-console*/\nself.module = {\n exports : function() {\n if (console) { console.error('No thread logic initialized.'); }\n }\n};\n\nfunction handlerDone() {\n var args = Array.prototype.slice.call(arguments, 0);\n this.postMessage({ response : args });\n}\n\nfunction handlerProgress(progress) {\n this.postMessage({ progress : progress });\n}\n\nfunction handlerDoneTransfer() {\n var args = Array.prototype.slice.call(arguments);\n var lastArg = args.pop();\n\n if (!(lastArg instanceof Array) && this.console) {\n console.error('Expected 2nd parameter of <doneCallback>.transfer() to be an array. Got:', lastArg);\n }\n\n this.postMessage({ response : args }, lastArg);\n}\n\nself.onmessage = function (event) {\n var scripts = event.data.scripts;\n if (scripts && scripts.length > 0 && typeof importScripts !== 'function') {\n throw new Error('importScripts() not supported.');\n }\n\n if (event.data.initByScripts) {\n importScripts.apply(null, scripts);\n }\n\n if (event.data.initByMethod) {\n var method = event.data.method;\n this.module.exports = Function.apply(null, method.args.concat(method.body));\n\n if (scripts && scripts.length > 0) {\n importScripts.apply(null, scripts);\n }\n }\n\n if (event.data.doRun) {\n var handler = this.module.exports;\n if (typeof handler !== 'function') {\n throw new Error('Cannot run thread logic. No handler has been exported.');\n }\n\n var preparedHandlerDone = handlerDone.bind(this);\n preparedHandlerDone.transfer = handlerDoneTransfer.bind(this);\n\n handler.call(this, event.data.param, preparedHandlerDone, handlerProgress.bind(this));\n }\n}.bind(self);\n"},{}],8:[function(e,t,n){"use strict";function r(e,t,n){this.fn=e,this.context=t,this.once=n||!1}function o(){}var i="function"!=typeof Object.create?"~":!1;o.prototype._events=void 0,o.prototype.listeners=function(e,t){var n=i?i+e:e,r=this._events&&this._events[n];if(t)return!!r;if(!r)return[];if(r.fn)return[r.fn];for(var o=0,s=r.length,a=new Array(s);s>o;o++)a[o]=r[o].fn;return a},o.prototype.emit=function(e,t,n,r,o,s){var a=i?i+e:e;if(!this._events||!this._events[a])return!1;var u,f,c=this._events[a],l=arguments.length;if("function"==typeof c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),l){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,n),!0;case 4:return c.fn.call(c.context,t,n,r),!0;case 5:return c.fn.call(c.context,t,n,r,o),!0;case 6:return c.fn.call(c.context,t,n,r,o,s),!0}for(f=1,u=new Array(l-1);l>f;f++)u[f-1]=arguments[f];c.fn.apply(c.context,u)}else{var h,p=c.length;for(f=0;p>f;f++)switch(c[f].once&&this.removeListener(e,c[f].fn,void 0,!0),l){case 1:c[f].fn.call(c[f].context);break;case 2:c[f].fn.call(c[f].context,t);break;case 3:c[f].fn.call(c[f].context,t,n);break;default:if(!u)for(h=1,u=new Array(l-1);l>h;h++)u[h-1]=arguments[h];c[f].fn.apply(c[f].context,u)}}return!0},o.prototype.on=function(e,t,n){var o=new r(t,n||this),s=i?i+e:e;return this._events||(this._events=i?{}:Object.create(null)),this._events[s]?this._events[s].fn?this._events[s]=[this._events[s],o]:this._events[s].push(o):this._events[s]=o,this},o.prototype.once=function(e,t,n){var o=new r(t,n||this,!0),s=i?i+e:e;return this._events||(this._events=i?{}:Object.create(null)),this._events[s]?this._events[s].fn?this._events[s]=[this._events[s],o]:this._events[s].push(o):this._events[s]=o,this},o.prototype.removeListener=function(e,t,n,r){var o=i?i+e:e;if(!this._events||!this._events[o])return this;var s=this._events[o],a=[];if(t)if(s.fn)(s.fn!==t||r&&!s.once||n&&s.context!==n)&&a.push(s);else for(var u=0,f=s.length;f>u;u++)(s[u].fn!==t||r&&!s[u].once||n&&s[u].context!==n)&&a.push(s[u]);return a.length?this._events[o]=1===a.length?a[0]:a:delete this._events[o],this},o.prototype.removeAllListeners=function(e){return this._events?(e?delete this._events[i?i+e:e]:this._events=i?{}:Object.create(null),this):this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prototype.setMaxListeners=function(){return this},o.prefixed=i,"undefined"!=typeof t&&(t.exports=o)},{}],9:[function(e,t,n){(function(e){!function(e,n,r){n[e]=n[e]||r(),"undefined"!=typeof t&&t.exports?t.exports=n[e]:"function"==typeof define&&define.amd&&define(function(){return n[e]})}("Promise","undefined"!=typeof e?e:this,function(){"use strict";function e(e,t){h.add(e,t),l||(l=d(h.drain))}function t(e){var t,n=typeof e;return null==e||"object"!=n&&"function"!=n||(t=e.then),"function"==typeof t?t:!1}function n(){for(var e=0;e<this.chain.length;e++)r(this,1===this.state?this.chain[e].success:this.chain[e].failure,this.chain[e]);this.chain.length=0}function r(e,n,r){var o,i;try{n===!1?r.reject(e.msg):(o=n===!0?e.msg:n.call(void 0,e.msg),o===r.promise?r.reject(TypeError("Promise-chain cycle")):(i=t(o))?i.call(o,r.resolve,r.reject):r.resolve(o))}catch(s){r.reject(s)}}function o(r){var s,u=this;if(!u.triggered){u.triggered=!0,u.def&&(u=u.def);try{(s=t(r))?e(function(){var e=new a(u);try{s.call(r,function(){o.apply(e,arguments)},function(){i.apply(e,arguments)})}catch(t){i.call(e,t)}}):(u.msg=r,u.state=1,u.chain.length>0&&e(n,u))}catch(f){i.call(new a(u),f)}}}function i(t){var r=this;r.triggered||(r.triggered=!0,r.def&&(r=r.def),r.msg=t,r.state=2,r.chain.length>0&&e(n,r))}function s(e,t,n,r){for(var o=0;o<t.length;o++)!function(o){e.resolve(t[o]).then(function(e){n(o,e)},r)}(o)}function a(e){this.def=e,this.triggered=!1}function u(e){this.promise=e,this.state=0,this.triggered=!1,this.chain=[],this.msg=void 0}function f(t){if("function"!=typeof t)throw TypeError("Not a function");if(0!==this.__NPO__)throw TypeError("Not a promise");this.__NPO__=1;var r=new u(this);this.then=function(t,o){var i={success:"function"==typeof t?t:!0,failure:"function"==typeof o?o:!1};return i.promise=new this.constructor(function(e,t){if("function"!=typeof e||"function"!=typeof t)throw TypeError("Not a function");i.resolve=e,i.reject=t}),r.chain.push(i),0!==r.state&&e(n,r),i.promise},this["catch"]=function(e){return this.then(void 0,e)};try{t.call(void 0,function(e){o.call(r,e)},function(e){i.call(r,e)})}catch(s){i.call(r,s)}}var c,l,h,p=Object.prototype.toString,d="undefined"!=typeof setImmediate?function(e){return setImmediate(e)}:setTimeout;try{Object.defineProperty({},"x",{}),c=function(e,t,n,r){return Object.defineProperty(e,t,{value:n,writable:!0,configurable:r!==!1})}}catch(y){c=function(e,t,n){return e[t]=n,e}}h=function(){function e(e,t){this.fn=e,this.self=t,this.next=void 0}var t,n,r;return{add:function(o,i){r=new e(o,i),n?n.next=r:t=r,n=r,r=void 0},drain:function(){var e=t;for(t=n=l=void 0;e;)e.fn.call(e.self),e=e.next}}}();var g=c({},"constructor",f,!1);return f.prototype=g,c(g,"__NPO__",0,!1),c(f,"resolve",function(e){var t=this;return e&&"object"==typeof e&&1===e.__NPO__?e:new t(function(t,n){if("function"!=typeof t||"function"!=typeof n)throw TypeError("Not a function");t(e)})}),c(f,"reject",function(e){return new this(function(t,n){if("function"!=typeof t||"function"!=typeof n)throw TypeError("Not a function");n(e)})}),c(f,"all",function(e){var t=this;return"[object Array]"!=p.call(e)?t.reject(TypeError("Not an array")):0===e.length?t.resolve([]):new t(function(n,r){if("function"!=typeof n||"function"!=typeof r)throw TypeError("Not a function");var o=e.length,i=Array(o),a=0;s(t,e,function(e,t){i[e]=t,++a===o&&n(i)},r)})}),c(f,"race",function(e){var t=this;return"[object Array]"!=p.call(e)?t.reject(TypeError("Not an array")):new t(function(n,r){if("function"!=typeof n||"function"!=typeof r)throw TypeError("Not a function");s(t,e,function(e,t){n(t)},r)})}),f})}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}]},{},[1]);
require=function e(t,n,r){function o(s,a){if(!n[s]){if(!t[s]){var u="function"==typeof require&&require;if(!a&&u)return u(s,!0);if(i)return i(s,!0);var f=new Error("Cannot find module '"+s+"'");throw f.code="MODULE_NOT_FOUND",f}var c=n[s]={exports:{}};t[s][0].call(c.exports,function(e){var n=t[s][1][e];return o(n?n:e)},c,c.exports,e,t,n,r)}return n[s].exports}for(var i="function"==typeof require&&require,s=0;s<r.length;s++)o(r[s]);return o}({"./defaults":[function(e,t,n){"use strict";n.__esModule=!0,n["default"]={pool:{size:navigator.hardwareConcurrency||8}},t.exports=n["default"]},{}],1:[function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}var o=e("./index"),i=r(o);"object"==typeof window&&(window.thread=i["default"]),"function"==typeof define?define([],function(){return i["default"]}):"object"==typeof t&&(t.exports=i["default"])},{"./index":3}],"./worker":[function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function s(e){var t=p.getConfig().basepath.web;return t?t+"/"+e:e}function a(e){for(var t=[],n=0;"undefined"!=typeof e[n];)t.push(e[n]),n++;return t}function u(e){if(e.stack)console.error(e.stack);else if(e.message&&e.filename&&e.lineno){var t=e.filename.match(/^data:text\/javascript/)&&e.filename.length>50?e.filename.substr(0,50)+"...":e.filename;console.error(e.message+" @"+t+":"+e.lineno)}else console.error(e)}n.__esModule=!0;var f=e("eventemitter3"),c=r(f),l=e("./slave-code-uri"),h=r(l),p=e("../config");if("object"!=typeof window.Worker&&"function"!=typeof window.Worker)throw new Error("Browser does not support web workers!");var d=function(e){function t(){var n=arguments.length<=0||void 0===arguments[0]?null:arguments[0],r=arguments.length<=1||void 0===arguments[1]?[]:arguments[1];o(this,t),e.call(this),this.initWorker(),this.worker.addEventListener("message",this.handleMessage.bind(this)),this.worker.addEventListener("error",this.handleError.bind(this)),n&&this.run(n,r)}return i(t,e),t.prototype.initWorker=function(){try{this.worker=new window.Worker(h["default"])}catch(e){var t=p.getConfig().fallback.slaveScriptUrl;if(!t)throw e;this.worker=new window.Worker(h["default"])}},t.prototype.run=function(e){var t=arguments.length<=1||void 0===arguments[1]?[]:arguments[1];return"function"==typeof e?this.runMethod(e,t):this.runScripts(e,t),this},t.prototype.runMethod=function(e,t){var n=e.toString(),r=n.substring(n.indexOf("(")+1,n.indexOf(")")).split(","),o=n.substring(n.indexOf("{")+1,n.lastIndexOf("}"));this.worker.postMessage({initByMethod:!0,method:{args:r,body:o},scripts:t.map(s)})},t.prototype.runScripts=function(e,t){if(!e)throw new Error("Must pass a function or a script URL to run().");this.worker.postMessage({initByScripts:!0,scripts:t.concat([e]).map(s)})},t.prototype.send=function(e){var t=arguments.length<=1||void 0===arguments[1]?[]:arguments[1];return this.worker.postMessage({doRun:!0,param:e},t),this},t.prototype.kill=function(){return this.worker.terminate(),this.emit("exit"),this},t.prototype.promise=function(){var e=this;return new Promise(function(t,n){e.once("message",t).once("error",n)})},t.prototype.handleMessage=function(e){if(e.data.error)this.handleError(e.data.error);else if(e.data.progress)this.handleProgress(e.data.progress);else{var t=a(e.data.response);this.emit.apply(this,["message"].concat(t)),this.emit.apply(this,["done"].concat(t))}},t.prototype.handleProgress=function(e){this.emit("progress",e)},t.prototype.handleError=function(e){this.listeners("error",!0)||u(e),e.preventDefault&&e.preventDefault(),this.emit("error",e)},t}(c["default"]);n["default"]=d,t.exports=n["default"]},{"../config":2,"./slave-code-uri":6,eventemitter3:8}],2:[function(e,t,n){"use strict";function r(e,t){var n=arguments.length<=2||void 0===arguments[2]?[]:arguments[2];Object.keys(t).forEach(function(o){var i=t[o],s=n.concat([o]);if("object"==typeof i){if("undefined"!=typeof e[o]&&"object"!=typeof e[o])throw new Error("Expected config property not to be an object: "+s.join("."));r(e[o],i,s)}else{if("object"==typeof e[o])throw new Error("Expected config property to be an object: "+s.join("."));e[o]=i}})}function o(){return a.get()}function i(){return a.set.apply(a,arguments)}n.__esModule=!0,n.getConfig=o,n.setConfig=i;var s={basepath:{node:"",web:""},fallback:{slaveScriptUrl:""}},a={get:function(){return s},set:function(e){if("object"!=typeof e)throw new Error("Expected config object.");r(s,e)}};n["default"]=a},{}],3:[function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(){var e=arguments.length<=0||void 0===arguments[0]?null:arguments[0],t=arguments.length<=1||void 0===arguments[1]?[]:arguments[1];return new h["default"](e,t)}n.__esModule=!0,n.spawn=o,e("native-promise-only");var i=e("./config"),s=r(i),a=e("./defaults"),u=r(a),f=e("./pool"),c=r(f),l=e("./worker"),h=r(l);n.config=s["default"],n.defaults=u["default"],n.Pool=c["default"],n["default"]={config:s["default"],defaults:u["default"],Pool:c["default"],spawn:o,Worker:h["default"]}},{"./config":2,"./defaults":"./defaults","./pool":5,"./worker":"./worker","native-promise-only":9}],4:[function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}n.__esModule=!0;var s=e("eventemitter3"),a=r(s),u=function(e){function t(n){o(this,t),e.call(this),this.pool=n,this.thread=null,this.runArgs=[],this.sendArgs=[],n.emit("newJob",this)}return i(t,e),t.prototype.run=function(){for(var e=arguments.length,t=Array(e),n=0;e>n;n++)t[n]=arguments[n];if(0===t.length)throw new Error("Cannot call .run() without arguments.");return this.runArgs=t,this},t.prototype.send=function(){if(0===this.runArgs.length)throw new Error("Cannot .send() before .run().");for(var e=arguments.length,t=Array(e),n=0;e>n;n++)t[n]=arguments[n];return this.sendArgs=t,this.emit("readyToRun"),this},t.prototype.executeOn=function(e){var t,n;return(t=(n=e.once("message",this.emit.bind(this,"done")).once("error",this.emit.bind(this,"error"))).run.apply(n,this.runArgs)).send.apply(t,this.sendArgs),this.thread=e,this.emit("threadChanged"),this},t.prototype.promise=function(){var e=this;return new Promise(function(t){e.thread?t(e.thread.promise()):e.once("threadChanged",function(){t(e.thread.promise())})})},t}(a["default"]);n["default"]=u,t.exports=n["default"]},{eventemitter3:8}],5:[function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}n.__esModule=!0;var s=e("eventemitter3"),a=r(s),u=e("./job"),f=r(u),c=e("./defaults"),l=r(c),h=e("./"),p=function(e){function t(n){o(this,t),e.call(this),this.threads=t.spawn(n||l["default"].pool.size),this.idleThreads=this.threads.slice(),this.jobQueue=[],this.runArgs=[],this.on("newJob",this.handleNewJob.bind(this))}return i(t,e),t.prototype.run=function(e){return this.runArgs=e,this},t.prototype.send=function(){if(!this.runArgs)throw new Error("Pool.send() called without prior Pool.run(). You need to define what to run first.");var e=new f["default"](this);return e.run(this.runArgs),e.send.apply(e,arguments)},t.prototype.killAll=function(){this.threads.forEach(function(e){e.kill()})},t.prototype.queueJob=function(e){this.jobQueue.push(e),this.dequeue()},t.prototype.dequeue=function(){if(0===this.jobQueue.length||0===this.idleThreads.length)return this.once("threadAvailable",this.dequeue);var e=this.jobQueue.shift(),t=this.idleThreads.shift();e.once("done",this.handleJobSuccess.bind(this,t,e)).once("error",this.handleJobError.bind(this,t,e)),e.executeOn(t)},t.prototype.handleNewJob=function(e){this.lastCreatedJob=e,e.once("readyToRun",this.queueJob.bind(this,e))},t.prototype.handleJobSuccess=function(e,t){for(var n=arguments.length,r=Array(n>2?n-2:0),o=2;n>o;o++)r[o-2]=arguments[o];this.emit.apply(this,["done",t].concat(r)),this.handleJobDone(e)},t.prototype.handleJobError=function(e,t,n){this.emit("error",t,n),this.handleJobDone(e)},t.prototype.handleJobDone=function(e){var t=this;this.idleThreads.push(e),this.emit("threadAvailable"),this.idleThreads.length===this.threads.length&&setTimeout(function(){t.emit("finished")},0)},t}(a["default"]);n["default"]=p,p.spawn=function(e){for(var t=[],n=0;e>n;n++)t.push(h.spawn());return t},t.exports=n["default"]},{"./":3,"./defaults":"./defaults","./job":4,eventemitter3:8}],6:[function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}n.__esModule=!0;var o=e("./slave-code"),i=r(o),s="data:text/javascript;charset=utf-8,"+encodeURI(i["default"]),a=window.createBlobURL||window.createObjectURL;if(!a){var u=window.URL||window.webkitURL;if(!u)throw new Error("No Blob creation implementation found.");a=u.createObjectURL}if("function"==typeof window.BlobBuilder&&"function"==typeof a){var f=new window.BlobBuilder;f.append(i["default"]),s=a(f.getBlob())}else if("function"==typeof window.Blob&&"function"==typeof a){var c=new window.Blob([i["default"]],{type:"text/javascript"});s=a(c)}n["default"]=s,t.exports=n["default"]},{"./slave-code":7}],7:[function(e,t,n){t.exports="/*eslint-env worker*/\n/*global importScripts*/\n/*eslint-disable no-console*/\nself.module = {\n exports : function() {\n if (console) { console.error('No thread logic initialized.'); }\n }\n};\n\nfunction handlerDone() {\n var args = Array.prototype.slice.call(arguments, 0);\n this.postMessage({ response : args });\n}\n\nfunction handlerProgress(progress) {\n this.postMessage({ progress : progress });\n}\n\nfunction handlerDoneTransfer() {\n var args = Array.prototype.slice.call(arguments);\n var lastArg = args.pop();\n\n if (!(lastArg instanceof Array) && this.console) {\n console.error('Expected 2nd parameter of <doneCallback>.transfer() to be an array. Got:', lastArg);\n }\n\n this.postMessage({ response : args }, lastArg);\n}\n\nself.onmessage = function (event) {\n var scripts = event.data.scripts;\n if (scripts && scripts.length > 0 && typeof importScripts !== 'function') {\n throw new Error('importScripts() not supported.');\n }\n\n if (event.data.initByScripts) {\n importScripts.apply(null, scripts);\n }\n\n if (event.data.initByMethod) {\n var method = event.data.method;\n this.module.exports = Function.apply(null, method.args.concat(method.body));\n\n if (scripts && scripts.length > 0) {\n importScripts.apply(null, scripts);\n }\n }\n\n if (event.data.doRun) {\n var handler = this.module.exports;\n if (typeof handler !== 'function') {\n throw new Error('Cannot run thread logic. No handler has been exported.');\n }\n\n var preparedHandlerDone = handlerDone.bind(this);\n preparedHandlerDone.transfer = handlerDoneTransfer.bind(this);\n\n handler.call(this, event.data.param, preparedHandlerDone, handlerProgress.bind(this));\n }\n}.bind(self);\n"},{}],8:[function(e,t,n){"use strict";function r(e,t,n){this.fn=e,this.context=t,this.once=n||!1}function o(){}var i="function"!=typeof Object.create?"~":!1;o.prototype._events=void 0,o.prototype.listeners=function(e,t){var n=i?i+e:e,r=this._events&&this._events[n];if(t)return!!r;if(!r)return[];if(r.fn)return[r.fn];for(var o=0,s=r.length,a=new Array(s);s>o;o++)a[o]=r[o].fn;return a},o.prototype.emit=function(e,t,n,r,o,s){var a=i?i+e:e;if(!this._events||!this._events[a])return!1;var u,f,c=this._events[a],l=arguments.length;if("function"==typeof c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),l){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,n),!0;case 4:return c.fn.call(c.context,t,n,r),!0;case 5:return c.fn.call(c.context,t,n,r,o),!0;case 6:return c.fn.call(c.context,t,n,r,o,s),!0}for(f=1,u=new Array(l-1);l>f;f++)u[f-1]=arguments[f];c.fn.apply(c.context,u)}else{var h,p=c.length;for(f=0;p>f;f++)switch(c[f].once&&this.removeListener(e,c[f].fn,void 0,!0),l){case 1:c[f].fn.call(c[f].context);break;case 2:c[f].fn.call(c[f].context,t);break;case 3:c[f].fn.call(c[f].context,t,n);break;default:if(!u)for(h=1,u=new Array(l-1);l>h;h++)u[h-1]=arguments[h];c[f].fn.apply(c[f].context,u)}}return!0},o.prototype.on=function(e,t,n){var o=new r(t,n||this),s=i?i+e:e;return this._events||(this._events=i?{}:Object.create(null)),this._events[s]?this._events[s].fn?this._events[s]=[this._events[s],o]:this._events[s].push(o):this._events[s]=o,this},o.prototype.once=function(e,t,n){var o=new r(t,n||this,!0),s=i?i+e:e;return this._events||(this._events=i?{}:Object.create(null)),this._events[s]?this._events[s].fn?this._events[s]=[this._events[s],o]:this._events[s].push(o):this._events[s]=o,this},o.prototype.removeListener=function(e,t,n,r){var o=i?i+e:e;if(!this._events||!this._events[o])return this;var s=this._events[o],a=[];if(t)if(s.fn)(s.fn!==t||r&&!s.once||n&&s.context!==n)&&a.push(s);else for(var u=0,f=s.length;f>u;u++)(s[u].fn!==t||r&&!s[u].once||n&&s[u].context!==n)&&a.push(s[u]);return a.length?this._events[o]=1===a.length?a[0]:a:delete this._events[o],this},o.prototype.removeAllListeners=function(e){return this._events?(e?delete this._events[i?i+e:e]:this._events=i?{}:Object.create(null),this):this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prototype.setMaxListeners=function(){return this},o.prefixed=i,"undefined"!=typeof t&&(t.exports=o)},{}],9:[function(e,t,n){(function(e){!function(e,n,r){n[e]=n[e]||r(),"undefined"!=typeof t&&t.exports?t.exports=n[e]:"function"==typeof define&&define.amd&&define(function(){return n[e]})}("Promise","undefined"!=typeof e?e:this,function(){"use strict";function e(e,t){h.add(e,t),l||(l=d(h.drain))}function t(e){var t,n=typeof e;return null==e||"object"!=n&&"function"!=n||(t=e.then),"function"==typeof t?t:!1}function n(){for(var e=0;e<this.chain.length;e++)r(this,1===this.state?this.chain[e].success:this.chain[e].failure,this.chain[e]);this.chain.length=0}function r(e,n,r){var o,i;try{n===!1?r.reject(e.msg):(o=n===!0?e.msg:n.call(void 0,e.msg),o===r.promise?r.reject(TypeError("Promise-chain cycle")):(i=t(o))?i.call(o,r.resolve,r.reject):r.resolve(o))}catch(s){r.reject(s)}}function o(r){var s,u=this;if(!u.triggered){u.triggered=!0,u.def&&(u=u.def);try{(s=t(r))?e(function(){var e=new a(u);try{s.call(r,function(){o.apply(e,arguments)},function(){i.apply(e,arguments)})}catch(t){i.call(e,t)}}):(u.msg=r,u.state=1,u.chain.length>0&&e(n,u))}catch(f){i.call(new a(u),f)}}}function i(t){var r=this;r.triggered||(r.triggered=!0,r.def&&(r=r.def),r.msg=t,r.state=2,r.chain.length>0&&e(n,r))}function s(e,t,n,r){for(var o=0;o<t.length;o++)!function(o){e.resolve(t[o]).then(function(e){n(o,e)},r)}(o)}function a(e){this.def=e,this.triggered=!1}function u(e){this.promise=e,this.state=0,this.triggered=!1,this.chain=[],this.msg=void 0}function f(t){if("function"!=typeof t)throw TypeError("Not a function");if(0!==this.__NPO__)throw TypeError("Not a promise");this.__NPO__=1;var r=new u(this);this.then=function(t,o){var i={success:"function"==typeof t?t:!0,failure:"function"==typeof o?o:!1};return i.promise=new this.constructor(function(e,t){if("function"!=typeof e||"function"!=typeof t)throw TypeError("Not a function");i.resolve=e,i.reject=t}),r.chain.push(i),0!==r.state&&e(n,r),i.promise},this["catch"]=function(e){return this.then(void 0,e)};try{t.call(void 0,function(e){o.call(r,e)},function(e){i.call(r,e)})}catch(s){i.call(r,s)}}var c,l,h,p=Object.prototype.toString,d="undefined"!=typeof setImmediate?function(e){return setImmediate(e)}:setTimeout;try{Object.defineProperty({},"x",{}),c=function(e,t,n,r){return Object.defineProperty(e,t,{value:n,writable:!0,configurable:r!==!1})}}catch(y){c=function(e,t,n){return e[t]=n,e}}h=function(){function e(e,t){this.fn=e,this.self=t,this.next=void 0}var t,n,r;return{add:function(o,i){r=new e(o,i),n?n.next=r:t=r,n=r,r=void 0},drain:function(){var e=t;for(t=n=l=void 0;e;)e.fn.call(e.self),e=e.next}}}();var g=c({},"constructor",f,!1);return f.prototype=g,c(g,"__NPO__",0,!1),c(f,"resolve",function(e){var t=this;return e&&"object"==typeof e&&1===e.__NPO__?e:new t(function(t,n){if("function"!=typeof t||"function"!=typeof n)throw TypeError("Not a function");t(e)})}),c(f,"reject",function(e){return new this(function(t,n){if("function"!=typeof t||"function"!=typeof n)throw TypeError("Not a function");n(e)})}),c(f,"all",function(e){var t=this;return"[object Array]"!=p.call(e)?t.reject(TypeError("Not an array")):0===e.length?t.resolve([]):new t(function(n,r){if("function"!=typeof n||"function"!=typeof r)throw TypeError("Not a function");var o=e.length,i=Array(o),a=0;s(t,e,function(e,t){i[e]=t,++a===o&&n(i)},r)})}),c(f,"race",function(e){var t=this;return"[object Array]"!=p.call(e)?t.reject(TypeError("Not an array")):new t(function(n,r){if("function"!=typeof n||"function"!=typeof r)throw TypeError("Not a function");s(t,e,function(e,t){n(t)},r)})}),f})}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}]},{},[1]);

@@ -5,3 +5,2 @@ // Karma configuration

config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)

@@ -46,11 +45,8 @@ basePath: '',

// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging

@@ -60,11 +56,7 @@ // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG

// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
browserNoActivityTimeout: 10000,
// start these browsers

@@ -74,3 +66,2 @@ // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher

customLaunchers: {

@@ -83,3 +74,2 @@ ChromeInsecure: {

// Continuous Integration mode

@@ -86,0 +76,0 @@ // if true, Karma captures browsers, runs the tests and exits

@@ -26,3 +26,3 @@ 'use strict';

this.runArgs = [];
this.clearSendParameter();
this.sendArgs = [];

@@ -54,11 +54,3 @@ pool.emit('newJob', this);

if (this.hasSendParameter()) {
var _clone$clearSendParameter;
// do not alter this job, clone it and set send param instead
return (_clone$clearSendParameter = this.clone().clearSendParameter()).send.apply(_clone$clearSendParameter, args);
}
this.sendArgs = args;
this.parameterSet = true;

@@ -75,2 +67,4 @@ this.emit('readyToRun');

this.thread = thread;
this.emit('threadChanged');
return this;

@@ -80,31 +74,17 @@ };

Job.prototype.promise = function promise() {
if (!this.thread) {
throw new Error('Cannot return promise, since job is not executed.');
}
return this.thread.promise();
};
var _this = this;
Job.prototype.clone = function clone() {
var clone = new Job(this.pool);
if (this.runArgs.length > 0) {
clone.run.apply(clone, this.runArgs);
}
if (this.parameterSet) {
clone.send.apply(clone, this.sendArgs);
}
return clone;
// Always return a promise
return new Promise(function (resolve) {
// If the thread isn't set, listen for the threadChanged event
if (!_this.thread) {
_this.once('threadChanged', function () {
resolve(_this.thread.promise());
});
} else {
resolve(_this.thread.promise());
}
});
};
Job.prototype.hasSendParameter = function hasSendParameter() {
return this.parameterSet;
};
Job.prototype.clearSendParameter = function clearSendParameter() {
this.parameterSet = false;
this.sendArgs = [];
return this;
};
return Job;

@@ -111,0 +91,0 @@ })(_eventemitter32['default']);

@@ -35,3 +35,3 @@ 'use strict';

this.jobQueue = [];
this.lastCreatedJob = null;
this.runArgs = [];

@@ -41,17 +41,15 @@ this.on('newJob', this.handleNewJob.bind(this));

Pool.prototype.run = function run() {
var _ref;
return (_ref = new _job2['default'](this)).run.apply(_ref, arguments);
Pool.prototype.run = function run(args) {
this.runArgs = args;
return this;
};
Pool.prototype.send = function send() {
var _lastCreatedJob;
if (!this.lastCreatedJob) {
if (!this.runArgs) {
throw new Error('Pool.send() called without prior Pool.run(). You need to define what to run first.');
}
// this will not alter the last job, but rather clone it and set this params on the new job
return (_lastCreatedJob = this.lastCreatedJob).send.apply(_lastCreatedJob, arguments);
var job = new _job2['default'](this);
job.run(this.runArgs);
return job.send.apply(job, arguments);
};

@@ -72,3 +70,3 @@

if (this.jobQueue.length === 0 || this.idleThreads.length === 0) {
return;
return this.once('threadAvailable', this.dequeue);
}

@@ -79,3 +77,3 @@

job.on('done', this.handleJobSuccess.bind(this, thread, job)).on('error', this.handleJobError.bind(this, thread, job));
job.once('done', this.handleJobSuccess.bind(this, thread, job)).once('error', this.handleJobError.bind(this, thread, job));

@@ -87,3 +85,3 @@ job.executeOn(thread);

this.lastCreatedJob = job;
job.on('readyToRun', this.queueJob.bind(this, job)); // triggered by job.send()
job.once('readyToRun', this.queueJob.bind(this, job)); // triggered by job.send()
};

@@ -109,3 +107,3 @@

this.idleThreads.push(thread);
this.dequeue();
this.emit('threadAvailable');

@@ -112,0 +110,0 @@ if (this.idleThreads.length === this.threads.length) {

@@ -155,2 +155,3 @@ 'use strict';

this.emit.apply(this, ['message'].concat(responseArgs));
this.emit.apply(this, ['done'].concat(responseArgs)); // this one is just for convenience
}

@@ -157,0 +158,0 @@ };

@@ -106,2 +106,3 @@ 'use strict';

this.emit.apply(this, ['message'].concat(message.response));
this.emit.apply(this, ['done'].concat(message.response)); // this one is just for convenience
}

@@ -108,0 +109,0 @@ };

{
"name": "threads",
"version": "0.5.4",
"version": "0.6.1",
"keywords": [

@@ -26,3 +26,3 @@ "threads",

"scripts": {
"compile": "./node_modules/.bin/gulp dist",
"build": "./node_modules/.bin/gulp dist",
"test": "./node_modules/.bin/gulp test"

@@ -29,0 +29,0 @@ },

@@ -170,2 +170,6 @@ # threads.js

```javascript
const threads = require('threads');
const spawn = threads.spawn;
const thread = spawn(function() {});
thread

@@ -244,2 +248,6 @@ .run(function minmax(int, done) {

```javascript
const threads = require('threads');
const spawn = threads.spawn;
const thread = spawn(function() {});
const largeArrayBuffer = new Uint8Array(1024 * 1024 * 32); // 32MB

@@ -268,2 +276,6 @@ const jobData = { label : 'huge thing', data: largeArrayBuffer.buffer };

```javascript
const threads = require('threads');
const spawn = threads.spawn;
const thread = spawn(function() {});
thread

@@ -282,2 +294,3 @@ .run(function(input, done, progress) {

console.log(`Done.`);
thread.kill();
});

@@ -327,8 +340,20 @@ ```

## Changelog
### 0.6.1
Added alias for threads: Event `done` as alias for `message`. Updated README example code.
Credit goes to https://github.com/andrakis
### 0.6.0
Fixes promise and async issues. `Job.clone()` has been dropped.
Credit goes to https://github.com/maysale01
## License
This library is published under the MIT license. See [LICENSE](https://raw.githubusercontent.com/andywer/thread.js/master/LICENSE) for details.
This library is published under the MIT license. See [LICENSE](./LICENSE) for details.
__Have fun and build something awesome!__

@@ -11,3 +11,3 @@

this.runArgs = [];
this.clearSendParameter();
this.sendArgs = [];

@@ -31,9 +31,3 @@ pool.emit('newJob', this);

if (this.hasSendParameter()) {
// do not alter this job, clone it and set send param instead
return this.clone().clearSendParameter().send(...args);
}
this.sendArgs = args;
this.parameterSet = true;

@@ -52,2 +46,4 @@ this.emit('readyToRun');

this.thread = thread;
this.emit('threadChanged');
return this;

@@ -57,30 +53,14 @@ }

promise() {
if (!this.thread) {
throw new Error('Cannot return promise, since job is not executed.');
}
return this.thread.promise();
// Always return a promise
return new Promise((resolve) => {
// If the thread isn't set, listen for the threadChanged event
if (!this.thread) {
this.once('threadChanged', () => {
resolve(this.thread.promise());
});
} else {
resolve(this.thread.promise());
}
});
}
clone() {
const clone = new Job(this.pool);
if (this.runArgs.length > 0) {
clone.run(...this.runArgs);
}
if (this.parameterSet) {
clone.send(...this.sendArgs);
}
return clone;
}
hasSendParameter() {
return this.parameterSet;
}
clearSendParameter() {
this.parameterSet = false;
this.sendArgs = [];
return this;
}
}

@@ -12,18 +12,21 @@ import EventEmitter from 'eventemitter3';

this.jobQueue = [];
this.lastCreatedJob = null;
this.runArgs = [];
this.on('newJob', this.handleNewJob.bind(this));
}
run(...args) {
return (new Job(this)).run(...args);
run(args) {
this.runArgs = args;
return this;
}
send(...args) {
if (!this.lastCreatedJob) {
if (!this.runArgs) {
throw new Error('Pool.send() called without prior Pool.run(). You need to define what to run first.');
}
// this will not alter the last job, but rather clone it and set this params on the new job
return this.lastCreatedJob.send(...args);
let job = new Job(this);
job.run(this.runArgs);
return job.send(...args);
}

@@ -44,3 +47,3 @@

if (this.jobQueue.length === 0 || this.idleThreads.length === 0) {
return;
return this.once('threadAvailable', this.dequeue);
}

@@ -52,4 +55,4 @@

job
.on('done', this.handleJobSuccess.bind(this, thread, job))
.on('error', this.handleJobError.bind(this, thread, job));
.once('done', this.handleJobSuccess.bind(this, thread, job))
.once('error', this.handleJobError.bind(this, thread, job));

@@ -61,3 +64,3 @@ job.executeOn(thread);

this.lastCreatedJob = job;
job.on('readyToRun', this.queueJob.bind(this, job)); // triggered by job.send()
job.once('readyToRun', this.queueJob.bind(this, job)); // triggered by job.send()
}

@@ -77,3 +80,3 @@

this.idleThreads.push(thread);
this.dequeue();
this.emit('threadAvailable');

@@ -80,0 +83,0 @@ if (this.idleThreads.length === this.threads.length) {

@@ -132,2 +132,3 @@ import EventEmitter from 'eventemitter3';

this.emit('message', ...responseArgs);
this.emit('done', ...responseArgs); // this one is just for convenience
}

@@ -134,0 +135,0 @@ }

@@ -81,2 +81,3 @@ import child from 'child_process';

this.emit('message', ...message.response);
this.emit('done', ...message.response); // this one is just for convenience
}

@@ -83,0 +84,0 @@ }

@@ -7,3 +7,7 @@ import expect from 'expect.js';

const fakeThreadPromise = new Promise(() => {});
const fakeThreadPromise = new Promise((resolve) => {
setTimeout(() => {
resolve(100);
});
});

@@ -49,3 +53,3 @@ function noop() {

expect(job.hasSendParameter()).to.equal(false);
expect(job.sendArgs).to.eql([]);
sinon.assert.calledOnce(pool.emit);

@@ -135,64 +139,4 @@ sinon.assert.calledWith(pool.emit, 'newJob', job);

it('can clone empty job', () => {
it('proxies the promise', (done) => {
const job = new Job(pool);
const clone = job.clone();
expect(clone.runArgs).to.eql(job.runArgs);
expect(clone.sendArgs).to.eql(job.sendArgs);
expect(clone.hasSendParameter()).to.equal(job.hasSendParameter());
});
it('can clone with runnable (w/o parameter)', () => {
const job = new Job(pool);
const runnable = noop;
const importScripts = [];
job.run(runnable, importScripts);
const clone = job.clone();
expect(clone.runArgs).to.eql(job.runArgs);
expect(clone.sendArgs).to.eql(job.sendArgs);
expect(clone.hasSendParameter()).to.equal(job.hasSendParameter());
});
it('can clone with runnable & parameter', () => {
const job = new Job(pool);
const runnable = noop;
const importScripts = [];
const param = 'some data';
const transferables = [];
job
.run(runnable, importScripts)
.send(param, transferables);
const clone = job.clone();
expect(clone.runArgs).to.eql(job.runArgs);
expect(clone.sendArgs).to.eql(job.sendArgs);
expect(clone.hasSendParameter()).to.equal(job.hasSendParameter());
});
it('clones on 2nd .send()', () => {
const job = new Job(pool);
const runnable = noop;
const paramA = { foo : 'bar' };
const paramB = 'foo bar';
job
.run(runnable)
.send(paramA);
const clone = job.send(paramB);
expect(clone).not.to.equal(job);
expect(clone.runArgs).to.eql(job.runArgs);
expect(clone.sendArgs).to.eql([ paramB ]);
expect(clone.hasSendParameter()).to.equal(true);
expect(job.sendArgs).to.eql([ paramA ]);
expect(job.hasSendParameter()).to.equal(true);
});
it('proxies the promise', () => {
const job = new Job(pool);
const thread = createFakeThread({

@@ -208,6 +152,11 @@ response : [ 'foo bar' ]

expect(promise).to.equal(fakeThreadPromise);
Promise
.all([promise, fakeThreadPromise])
.then((results) => {
expect(results[0]).to.equal(results[1]);
done();
});
});
it('prevents promise without .executeOn()', () => {
it('Creates a promise even if there is no thread', () => {
const job = new Job(pool);

@@ -219,5 +168,5 @@

expect(job.promise).to.throwError(/Cannot return promise, since job is not executed/);
expect(job.promise() instanceof Promise).to.equal(true);
});
});

@@ -186,3 +186,18 @@ import async from 'async';

it('does also emit "done" event', done => {
const progressUpdates = [];
const worker = spawn(progressThread);
worker.on('progress', progress => {
progressUpdates.push(progress);
});
worker.send();
worker.on('done', () => {
expect(progressUpdates).to.eql([ 0.3, 0.6 ]);
done();
});
});
if (env === 'node') {

@@ -189,0 +204,0 @@

@@ -23,3 +23,7 @@ 'use strict';

var fakeThreadPromise = new Promise(function () {});
var fakeThreadPromise = new Promise(function (resolve) {
setTimeout(function () {
resolve(100);
});
});

@@ -67,3 +71,3 @@ function noop() {

(0, _expectJs2['default'])(job.hasSendParameter()).to.equal(false);
(0, _expectJs2['default'])(job.sendArgs).to.eql([]);
_sinon2['default'].assert.calledOnce(pool.emit);

@@ -148,60 +152,4 @@ _sinon2['default'].assert.calledWith(pool.emit, 'newJob', job);

it('can clone empty job', function () {
it('proxies the promise', function (done) {
var job = new _libJob2['default'](pool);
var clone = job.clone();
(0, _expectJs2['default'])(clone.runArgs).to.eql(job.runArgs);
(0, _expectJs2['default'])(clone.sendArgs).to.eql(job.sendArgs);
(0, _expectJs2['default'])(clone.hasSendParameter()).to.equal(job.hasSendParameter());
});
it('can clone with runnable (w/o parameter)', function () {
var job = new _libJob2['default'](pool);
var runnable = noop;
var importScripts = [];
job.run(runnable, importScripts);
var clone = job.clone();
(0, _expectJs2['default'])(clone.runArgs).to.eql(job.runArgs);
(0, _expectJs2['default'])(clone.sendArgs).to.eql(job.sendArgs);
(0, _expectJs2['default'])(clone.hasSendParameter()).to.equal(job.hasSendParameter());
});
it('can clone with runnable & parameter', function () {
var job = new _libJob2['default'](pool);
var runnable = noop;
var importScripts = [];
var param = 'some data';
var transferables = [];
job.run(runnable, importScripts).send(param, transferables);
var clone = job.clone();
(0, _expectJs2['default'])(clone.runArgs).to.eql(job.runArgs);
(0, _expectJs2['default'])(clone.sendArgs).to.eql(job.sendArgs);
(0, _expectJs2['default'])(clone.hasSendParameter()).to.equal(job.hasSendParameter());
});
it('clones on 2nd .send()', function () {
var job = new _libJob2['default'](pool);
var runnable = noop;
var paramA = { foo: 'bar' };
var paramB = 'foo bar';
job.run(runnable).send(paramA);
var clone = job.send(paramB);
(0, _expectJs2['default'])(clone).not.to.equal(job);
(0, _expectJs2['default'])(clone.runArgs).to.eql(job.runArgs);
(0, _expectJs2['default'])(clone.sendArgs).to.eql([paramB]);
(0, _expectJs2['default'])(clone.hasSendParameter()).to.equal(true);
(0, _expectJs2['default'])(job.sendArgs).to.eql([paramA]);
(0, _expectJs2['default'])(job.hasSendParameter()).to.equal(true);
});
it('proxies the promise', function () {
var job = new _libJob2['default'](pool);
var thread = createFakeThread({

@@ -213,6 +161,9 @@ response: ['foo bar']

(0, _expectJs2['default'])(promise).to.equal(fakeThreadPromise);
Promise.all([promise, fakeThreadPromise]).then(function (results) {
(0, _expectJs2['default'])(results[0]).to.equal(results[1]);
done();
});
});
it('prevents promise without .executeOn()', function () {
it('Creates a promise even if there is no thread', function () {
var job = new _libJob2['default'](pool);

@@ -222,4 +173,4 @@

(0, _expectJs2['default'])(job.promise).to.throwError(/Cannot return promise, since job is not executed/);
(0, _expectJs2['default'])(job.promise() instanceof Promise).to.equal(true);
});
});

@@ -187,2 +187,17 @@ 'use strict';

it('does also emit "done" event', function (done) {
var progressUpdates = [];
var worker = (0, _.spawn)(progressThread);
worker.on('progress', function (progress) {
progressUpdates.push(progress);
});
worker.send();
worker.on('done', function () {
(0, _expectJs2['default'])(progressUpdates).to.eql([0.3, 0.6]);
done();
});
});
if (env === 'node') {

@@ -189,0 +204,0 @@

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