@cheprasov/worker-thread
Version:
The WorkerThread wraps a Web Worker with a Promise, also the class creates a worker script on the fly (without having to create separate worker files). You can 'inline' your worker function in the same js file as main logic.
1 lines • 13.1 kB
JavaScript
module.exports=function(e){var r={};function t(n){if(r[n])return r[n].exports;var o=r[n]={i:n,l:!1,exports:{}};return e[n].call(o.exports,o,o.exports,t),o.l=!0,o.exports}return t.m=e,t.c=r,t.d=function(e,r,n){t.o(e,r)||Object.defineProperty(e,r,{enumerable:!0,get:n})},t.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},t.t=function(e,r){if(1&r&&(e=t(e)),8&r)return e;if(4&r&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(t.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&r&&"string"!=typeof e)for(var o in e)t.d(n,o,function(r){return e[r]}.bind(null,o));return n},t.n=function(e){var r=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(r,"a",r),r},t.o=function(e,r){return Object.prototype.hasOwnProperty.call(e,r)},t.p="",t(t.s=0)}([function(e,r,t){"use strict";function n(e,r){for(var t=0;t<r.length;t++){var n=r[t];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}t.r(r),t.d(r,"ThreadFactory",(function(){return T})),t.d(r,"WorkerThread",(function(){return k})),t.d(r,"TimeoutThread",(function(){return M})),t.d(r,"NoopThread",(function(){return O})),t.d(r,"WorkerError",(function(){return y}));var o=new Map,a=function(){function e(){!function(e,r){if(!(e instanceof r))throw new TypeError("Cannot call a class as a function")}(this,e)}var r,t,a;return r=e,a=[{key:"createJavaScriptObjectUrl",value:function(e){var r=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(r&&o.has(e))return o.get(e);var t=new Blob([e],{type:"text/javascript"}),n=URL.createObjectURL(t);return r&&o.set(e,n),n}}],(t=null)&&n(r.prototype,t),a&&n(r,a),e}();function i(e){return(i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function c(e,r){if(!(e instanceof r))throw new TypeError("Cannot call a class as a function")}function u(e,r){for(var t=0;t<r.length;t++){var n=r[t];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}function s(e,r){return!r||"object"!==i(r)&&"function"!=typeof r?l(e):r}function l(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function f(e){var r="function"==typeof Map?new Map:void 0;return(f=function(e){if(null===e||(t=e,-1===Function.toString.call(t).indexOf("[native code]")))return e;var t;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==r){if(r.has(e))return r.get(e);r.set(e,n)}function n(){return p(e,arguments,h(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),v(n,e)})(e)}function p(e,r,t){return(p=d()?Reflect.construct:function(e,r,t){var n=[null];n.push.apply(n,r);var o=new(Function.bind.apply(e,n));return t&&v(o,t.prototype),o}).apply(null,arguments)}function d(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch(e){return!1}}function v(e,r){return(v=Object.setPrototypeOf||function(e,r){return e.__proto__=r,e})(e,r)}function h(e){return(h=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function m(e,r,t){return r in e?Object.defineProperty(e,r,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[r]=t,e}var y=function(e){!function(e,r){if("function"!=typeof r&&null!==r)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(r&&r.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),r&&v(e,r)}(i,e);var r,t,n,o,a=(r=i,function(){var e,t=h(r);if(d()){var n=h(this).constructor;e=Reflect.construct(t,arguments,n)}else e=t.apply(this,arguments);return s(this,e)});function i(e){var r,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;return c(this,i),m(l(r=a.call(this,t)),"type",void 0),m(l(r),"data",void 0),r.type=e,r.data=n,r}return t=i,(n=[{key:"getType",value:function(){return this.type}},{key:"getData",value:function(){return this.data}}])&&u(t.prototype,n),o&&u(t,o),i}(f(Error));function b(e,r){if(!(e instanceof r))throw new TypeError("Cannot call a class as a function")}function g(e,r){for(var t=0;t<r.length;t++){var n=r[t];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}function w(e,r,t){return r in e?Object.defineProperty(e,r,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[r]=t,e}var k=function(){function e(r){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};b(this,e),w(this,"worker",void 0),w(this,"promiseCompletionsMap",void 0),w(this,"options",void 0),this.options=t,this.promiseCompletionsMap=new Map,this.worker=new Worker(e.createWorkerBlobFile(r,t),{name:t.name,type:t.type,credentials:t.credentials}),this.worker.onmessage=this._onMessage.bind(this),this.worker.onmessageerror=this._onMessageError.bind(this),this.worker.onerror=this._onError.bind(this)}var r,t,n;return r=e,n=[{key:"isSupported",value:function(){try{return!!(URL&&URL.createObjectURL&&Blob&&Worker)}catch(e){return!1}}},{key:"createWorkerBlobFile",value:function(e,r){var t=r.importScripts?"importScripts('".concat(r.importScripts.join("', '"),"');"):"",n="function"==typeof e?Function.toString.call(e):e;return a.createJavaScriptObjectUrl("'use strict';\n \n ".concat(t,"\n \n var threadFunc = ").concat(n,";\n\n var workerCommandExec = function(data) {\n var result = threadFunc.apply(threadFunc, data.args);\n self.postMessage({\n status: '").concat("ok","',\n promiseId: data.promiseId,\n result: result\n });\n };\n\n var workerCommandClose = function(data) {\n self.postMessage({\n status: '").concat("ok","',\n promiseId: data.promiseId,\n result: true\n });\n self.close();\n };\n\n var workerSendError = function(data, error) {\n self.postMessage({\n status: '").concat("error","',\n promiseId: data.promiseId,\n error: {\n type: error.name || 'Error',\n message: error.message,\n }\n });\n };\n\n self.onmessage = function(event) {\n try {\n switch (event.data.command) {\n case '").concat("exec","':\n workerCommandExec(event.data);\n break;\n case '").concat("close","':\n workerCommandClose(event.data);\n break;\n default:\n workerSendError(event.data, {\n name: '").concat("WorkerCommand","',\n message: 'Wrong command \"' + event.data.command + '\"' \n });\n }\n } catch (error) {\n workerSendError(event.data, error);\n }\n };\n\n // see: https://developer.mozilla.org/en-US/docs/Web/API/DedicatedWorkerGlobalScope/onmessageerror\n self.onmessageerror = function(event) {\n var error = {\n name: '").concat("WorkerOnMessageError","',\n message: 'The onmessageerror event handler of the DedicatedWorkerGlobalScope interface is '\n + 'an EventListener, called whenever an MessageEvent of type messageerror is fired on '\n + 'the worker—that is, when it receives a message that cannot be deserialized.'\n };\n workerSendError(event.data, error);\n };\n "))}}],(t=[{key:"_getNewPromiseId",value:function(){var e,r=Date.now(),t=0;do{e="".concat(r,"-").concat(t),t+=1}while(this.promiseCompletionsMap.has(e));return e}},{key:"_createError",value:function(e){return new y(e.type,e.message)}},{key:"_onMessage",value:function(e){var r=e.data.promiseId,t=this.promiseCompletionsMap.get(r);if(t){switch(e.data.status){case"ok":t.resolve(e.data.result);break;case"error":t.reject(this._createError(e.data.error));break;default:t.reject(new y("WrongMessageStatus","Incorrect message status: ".concat(e.data.status),e.data))}this.promiseCompletionsMap.delete(r)}}},{key:"_onMessageError",value:function(e){var r=e.data.promiseId,t=this.promiseCompletionsMap.get(r);t&&t.reject(new y("OnMessageError","The onmessageerror event handler of the Worker interface is an EventListener, called whenever anMessageEvent of type messageerror is fired on the Worker instance — that is, when it receives a message that cannot be deserialized.",e)),this.promiseCompletionsMap.delete(r)}},{key:"_onError",value:function(e){var r=this;this.promiseCompletionsMap.forEach((function(t,n){t.reject(e),r.promiseCompletionsMap.delete(n)})),this.options.onError&&this.options.onError(e)}},{key:"_postMessage",value:function(e){var r=this;return new Promise((function(t,n){e.promiseId||(e.promiseId=r._getNewPromiseId()),r.promiseCompletionsMap.set(e.promiseId,{resolve:t,reject:n});try{r.worker.postMessage(e)}catch(e){n(e)}}))}},{key:"exec",value:function(){for(var e=arguments.length,r=new Array(e),t=0;t<e;t++)r[t]=arguments[t];var n={command:"exec",args:r};return this._postMessage(n)}},{key:"close",value:function(){var e={command:"close"};return this._postMessage(e)}},{key:"terminate",value:function(){this.worker.terminate()}}])&&g(r.prototype,t),n&&g(r,n),e}();function j(e,r){for(var t=0;t<r.length;t++){var n=r[t];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}var M=function(){function e(r){var t,n,o;!function(e,r){if(!(e instanceof r))throw new TypeError("Cannot call a class as a function")}(this,e),o=void 0,(n="threadFunc")in(t=this)?Object.defineProperty(t,n,{value:o,enumerable:!0,configurable:!0,writable:!0}):t[n]=o,this.threadFunc=r}var r,t,n;return r=e,n=[{key:"isSupported",value:function(){try{return setTimeout&&"function"==typeof setTimeout||!1}catch(e){return!1}}}],(t=[{key:"exec",value:function(){for(var e=this,r=arguments.length,t=new Array(r),n=0;n<r;n++)t[n]=arguments[n];return new Promise((function(r,n){setTimeout((function(){try{r(e.threadFunc.apply(e,t))}catch(e){n(e)}}),0)}))}},{key:"close",value:function(){return this.threadFunc=function(){},Promise.resolve(!0)}},{key:"terminate",value:function(){this.threadFunc=function(){}}}])&&j(r.prototype,t),n&&j(r,n),e}();function E(e,r){for(var t=0;t<r.length;t++){var n=r[t];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}var O=function(){function e(){!function(e,r){if(!(e instanceof r))throw new TypeError("Cannot call a class as a function")}(this,e)}var r,t,n;return r=e,n=[{key:"isSupported",value:function(){return!0}}],(t=[{key:"exec",value:function(){return Promise.resolve()}},{key:"close",value:function(){return Promise.resolve(!0)}},{key:"terminate",value:function(){}}])&&E(r.prototype,t),n&&E(r,n),e}();function S(e,r){for(var t=0;t<r.length;t++){var n=r[t];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}var T=function(){function e(){!function(e,r){if(!(e instanceof r))throw new TypeError("Cannot call a class as a function")}(this,e)}var r,t,n;return r=e,n=[{key:"createThread",value:function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return k.isSupported()?this.createWorkerThread(e,r):M.isSupported()?this.createTimeoutThread(e,r):this.createNoopThread(e,r)}},{key:"createWorkerThread",value:function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return new k(e,r)}},{key:"createTimeoutThread",value:function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return new M(e,r)}},{key:"createNoopThread",value:function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return new O(e,r)}}],(t=null)&&S(r.prototype,t),n&&S(r,n),e}()}]);