UNPKG

threaded.std.min.js

Version:
1 lines 53.4 kB
class ThreadedTools{static workerSourceCode(e){return(ThreadedTools.isnodejs?"import { parentPort } from 'node:worker_threads';\n":"")+"class ThreadExecutor {\n static __threadExceptionOccurred__(ex) {\n "+(ThreadedTools.isnodejs?"parentPort":"self")+".postMessage({ error: ex });\n throw ex;\n }\n}\nThreadExecutor.currentThread = {};\n"+ThreadedTools.toString()+"\nThreadedTools.postMessageToWorker = (worker, data) => "+(ThreadedTools.isnodejs?"global":"worker")+".onmessage(data);\n"+IsolatedThread.toString()+"\n"+ThreadError.toString()+"\nIsolatedThread.this = new IsolatedThread();\nIsolatedThread.this.__createInternalWebWorker__ = () => {}\nIsolatedThread.this.terminate = () => {\n "+(ThreadedTools.isnodejs?"parentPort":"self")+".postMessage({ terminate: true });\n}\nIsolatedThread.this.__worker__ = "+(ThreadedTools.isnodejs?"parentPort":"self")+";\nlet generatorFunc = "+e.toString()+"\nlet generator = null;\nlet args = [];\n"+(ThreadedTools.isnodejs?"global.":"let ")+"onmessage = function(e) {\n try {\n let data = e.data === undefined ? e : e.data;\n "+(ThreadedTools.isnodejs?"global":"self")+".id = data.id;\n let started = data.started;\n let running = data.running;\n let stopped = data.stopped;\n let sleeping = data.sleeping;\n let paused = data.paused;\n let restarted = data.restarted;\n let argschanged = data.argschanged;\n IsolatedThread.this.id = data.id;\n IsolatedThread.this.__started__ = started;\n IsolatedThread.this.__running__ = running;\n IsolatedThread.this.__stopped__ = stopped;\n IsolatedThread.this.__sleeping__ = sleeping;\n IsolatedThread.this.__paused__ = paused;\n IsolatedThread.this.__argschanged__ = argschanged;\n if (argschanged || restarted) {\n args = data.args !== null ? data.args : args;\n generator = generatorFunc(...args);\n }\n let stepscount = 1;\n function loop() {\n if ("+(ThreadedTools.isnodejs?"global":"self")+".__looptimer__ !== undefined) try { clearTimeout("+(ThreadedTools.isnodejs?"global":"self")+".__looptimer__); } catch (ex) {}\n if (!started || !running || stopped) return;\n let done = false;\n if (!sleeping && !paused) {\n let result = generator.next();\n done = result.done === true;\n if (result instanceof Error) return result;\n stepscount = !done ? result : stepscount;\n "+(ThreadedTools.isnodejs?"parentPort":"self")+".postMessage({\n id: "+(ThreadedTools.isnodejs?"global":"self")+".id,\n result: result.value,\n done: done,\n });\n }\n if (!done) "+(ThreadedTools.isnodejs?"global":"self")+".__looptimer__ = setTimeout(loop, 10);\n }\n loop();\n } catch (ex) {\n ThreadExecutor.__threadExceptionOccurred__(ex);\n return ex;\n }\n}\n"+(ThreadedTools.isnodejs?"parentPort.on('message', global.onmessage);":"self.onmessage = onmessage;")}}ThreadedTools.createWorker=(e,t,r)=>{let i=ThreadedTools.workerSourceCode(t);!0===ThreadedTools.isnodejs?(e.__worker__=ThreadedTools.createNodeWorker(i),e.__worker__.on("message",r)):(e.__blob__=new Blob([i],{type:"application/javascript"}),e.__workerURL__=URL.createObjectURL(e.__blob__),e.__worker__=new Worker(e.__workerURL__,!0===ThreadedTools.isesm?{type:"module"}:void 0),e.__worker__.onmessage=r)},ThreadedTools.postMessageToWorker=(e,t)=>{e.postMessage(t)},ThreadedTools.ast_generator={parse:void 0},ThreadedTools.ast_walker={fullAncestor:void 0,simple:void 0,base:void 0},ThreadedTools.escodegenerator={generate:void 0};class Thread{constructor(e,t,r,i){if(void 0===Thread.this&&(Thread.this=this),!0===Thread.__stopcontrols__)return this;if((void 0===Thread.__count__||null===Thread.__count__||Number.isNaN(Thread.__count__))&&(Thread.__count__=0),Thread.__count__++,this.__func__=e,this.innerfunctionsisolation=void 0!=i&&null!==i&&i,this.__generatorFunc__=ThreadExecutor.__generatorFunc__(e,this.innerfunctionsisolation),this.id=void 0===r?"anonymous thread n-"+Thread.__count__:r+" (thread n-"+Thread.__count__+")",void 0===ThreadExecutor.queue&&(ThreadExecutor.queue=[]),this.__sleepingpriority__=!1,this.__resumingpriority__=!1,this.__stepscount__=0,void 0!==t){if("number"!=typeof t)throw new ThreadError("thread priority level must be a valid number",this);if(!Number.isInteger(t))throw new ThreadError("thread priority level must be an integer number",this);if(t<0)throw new ThreadError("thread priority level must be a positive number",this);this.prioritylevel=t}else this.prioritylevel=(t??1)|1;this.__args__=[],this.__result__=null,this.__sleepingtimeout__=null,this.__delaytimeout__=null,this.__isolateErrors__=!1,this.__done__=!1,this.__sleeping__=!1,this.__started__=!1,this.__running__=!1,this.__stopped__=!1,this.__paused__=!1}static count(){return Thread.__count__}static innerThreadFor(e,t,r,i,n){void 0===Thread.__sharedinnerthreads__&&(Thread.__sharedinnerthreads__=new Map),Thread.__sharedinnerthreads__.has(e)||Thread.__sharedinnerthreads__.set(e,new Map),Thread.__sharedinnerthreads__.get(e).has(t)||Thread.__sharedinnerthreads__.get(e).set(t,[new Thread(t,r,i,n)]);let o=null;for(let s in Thread.__sharedinnerthreads__.get(e).get(t)){let a=Thread.__sharedinnerthreads__.get(e).get(t)[s];if(!a.__running__){o=a;break}}return null===o&&(o=new Thread(t,r,i,n),Thread.__sharedinnerthreads__.get(e).get(t).push(o)),void 0!==r&&o.setPriorityLevel(void 0!==r?r:e.prioritylevel),void 0!==i&&o.setId(i),void 0!==n&&o.isolateInnerFunctions(n),o}setId(e){return!0===Thread.__stopcontrols__||(this.id=null==e?"anonymous thread n-"+Thread.__count__:e+" (thread n-"+Thread.__count__+")"),this}setArgs(...e){return!0===Thread.__stopcontrols__||(this.__args__=e),this}isolateErrors(e){return!0===Thread.__stopcontrols__||(null==e&&(this.__isolateErrors__=!1),this.__isolateErrors__=e),this}setFunction(e){return!0===Thread.__stopcontrols__||(this.__paused__||this.pause(),this.__func__=e,this.__generatorFunc__=ThreadExecutor.__generatorFunc__(this.__func__,this.innerfunctionsisolation),this.__started__&&this.start()),this}isolateInnerFunctions(e){if(!0===Thread.__stopcontrols__)return this;let t=e;return null==t&&(t=!0),this.innerfunctionsisolation=t,this.__paused__||this.pause(),this.__generatorFunc__=ThreadExecutor.__generatorFunc__(this.__func__,t),this.__started__&&this.start(),this}toString(){return this.id}stepsCount(){return this.__stepscount__}setPriorityLevel(e){if(!0===Thread.__stopcontrols__)return this;if("number"!=typeof e)throw new ThreadError("thread priority level must be a valid number",this);if(!Number.isInteger(e))throw new ThreadError("thread priority level must be an integer number",this);if(e<0)throw new ThreadError("thread priority level must be a positive number",this);return this.prioritylevel=e,ThreadExecutor.notifyForPriority(),this}start(){if(!0===Thread.__stopcontrols__)return this;if(null!==this.__sleepingtimeout__)try{clearTimeout(this.__sleepingtimeout__)}catch(e){}return this.__generator__=void 0,this.__stepscount__=0,this.__sleepingpriority__=!1,this.__resumingpriority__=!1,this.__result__=null,this.__done__=!1,this.__sleeping__=!1,this.__started__=!0,this.__paused__=!1,this.__stopped__=!1,this.__running__=!0,ThreadExecutor.__timeSpentOutsideThreads__=void 0,ThreadExecutor.queue.push(this),this.prioritylevel>1&&ThreadExecutor.notifyForPriority(!1),ThreadExecutor.isHandling()||ThreadExecutor.handleThreadQueue(),this}startAfter(e){if(!0===Thread.__stopcontrols__)return this;if(null!==this.__delaytimeout__)try{clearTimeout(this.__delaytimeout__)}catch(t){}return this.__paused__||this.pause(),this.__delaytimeout__=setTimeout(()=>this.start(),e),this}interrupt(){return!0===Thread.__stopcontrols__?this:this.stop()}static interrupt(){if(!0===Thread.__stopcontrols__)return this;let e=ThreadExecutor.currentThread;if(null==e)throw new ThreadError("Thread.interrupt called outside thread environment");e.interrupt()}interruptAfter(e){if(!0===Thread.__stopcontrols__)return this;if(null!==this.__delaytimeout__)try{clearTimeout(this.__delaytimeout__)}catch(t){}return this.__paused__||this.pause(),this.__delaytimeout__=setTimeout(()=>this.interrupt(),e),this}static interruptAfter(e){if(!0===Thread.__stopcontrols__)return this;let t=ThreadExecutor.currentThread;if(null==t)throw new ThreadError("Thread.interruptAfter called outside thread environment");t.interruptAfter(e)}stop(){if(!0===Thread.__stopcontrols__)return this;if(!this.__started__)return console.error("Thread not started yet"),this;if(this.__stopped__)return console.error("Thread already stopped"),this;this.__stopped__=!0,this.__running__=!1;let e=ThreadExecutor.queue.indexOf(this);if(-1===e)throw new ThreadError('Cannot stop thread "'+this.id+", the thread is not in the execution queue");return ThreadExecutor.queue.splice(e,1),this}static stop(){if(!0===Thread.__stopcontrols__)return this;let e=ThreadExecutor.currentThread;if(null==e)throw new ThreadError("Thread.stop called outside thread environment");e.stop()}stopAfter(e){if(!0===Thread.__stopcontrols__)return this;if(null!==this.__delaytimeout__)try{clearTimeout(this.__delaytimeout__)}catch(t){}return this.__delaytimeout__=setTimeout(()=>this.stop(),e),this}static stopAfter(e){if(!0===Thread.__stopcontrols__)return this;let t=ThreadExecutor.currentThread;if(null==t)throw new ThreadError("Thread.stopAfter called outside thread environment");t.stopAfter(e)}pause(){return!0===Thread.__stopcontrols__?this:this.__paused__?(console.error("Thread already paused"),this):(this.__paused__=!0,this)}static pause(){if(!0===Thread.__stopcontrols__)return this;let e=ThreadExecutor.currentThread;if(null==e)throw new ThreadError("Thread.pause called outside thread environment");e.pause()}pauseAfter(e){if(!0===Thread.__stopcontrols__)return this;if(null!==this.__delaytimeout__)try{clearTimeout(this.__delaytimeout__)}catch(t){}return this.__delaytimeout__=setTimeout(()=>this.pause(),e),this}static pauseAfter(e){if(!0===Thread.__stopcontrols__)return this;let t=ThreadExecutor.currentThread;if(null==t)throw new ThreadError("Thread.pauseAfter called outside thread environment");t.pauseAfter(e)}resume(){if(!0===Thread.__stopcontrols__)return this;if(!this.__paused__&&!this.__sleeping__)return console.error("Thread is neither paused nor sleeping"),this;let e=ThreadExecutor.queue.indexOf(this);if(-1===e)throw new ThreadError('Cannot resume thread "'+this.id+", the thread is not in the execution queue");if(null!==this.__sleepingtimeout__)try{clearTimeout(this.__sleepingtimeout__)}catch(t){}return this.__paused__?(this.__sleeping__=!1,this.__sleepingpriority__=!1,this.__paused__=!1,this.__resumingpriority__=!0,ThreadExecutor.notifyForResuming(this,e)):this.__sleeping__&&(this.__paused__=!1,this.__resumingpriority__=!1,this.__sleeping__=!1,this.__sleepingpriority__=!0,ThreadExecutor.notifyForSleeping(this,e)),this}static resume(){if(!0===Thread.__stopcontrols__)return this;let e=ThreadExecutor.currentThread;if(null==e)throw new ThreadError("Thread.resume called outside thread environment");e.resume()}resumeAfter(e){if(!0===Thread.__stopcontrols__)return this;if(null!==this.__delaytimeout__)try{clearTimeout(this.__delaytimeout__)}catch(t){}return this.__delaytimeout__=setTimeout(()=>this.resume(),e),this}static resumeAfter(e){if(!0===Thread.__stopcontrols__)return this;let t=ThreadExecutor.currentThread;if(null==t)throw new ThreadError("Thread.resumeAfter called outside thread environment");t.resumeAfter(e)}sleep(e){if(!0===Thread.__stopcontrols__)return this;if(null!==this.__sleepingtimeout__)try{clearTimeout(this.__sleepingtimeout__)}catch(t){}if(!this.__started__)throw new ThreadError('Cannot sleep thread "'+this.id+", the thread is not started yet");if(this.__stopped__)throw new ThreadError('Cannot sleep thread "'+this.id+", the thread is stopped");if(!this.__running__)throw new ThreadError('Cannot sleep thread "'+this.id+", the thread is not running");if(this.__paused__)throw new ThreadError('Cannot sleep thread "'+this.id+", the thread is paused");let r=ThreadExecutor.queue.indexOf(this);if(-1===r)throw new ThreadError('Cannot sleep thread "'+this.id+", the thread is not in the execution queue");return this.__sleeping__=!0,this.__sleepingpriority__=!0,this.__sleepingtimeout__=setTimeout(()=>ThreadExecutor.notifyForSleeping(this,r),e),this}static sleep(e){if(!0===Thread.__stopcontrols__)return this;let t=ThreadExecutor.currentThread;if(null==t)throw new ThreadError("Thread.sleep called outside thread environment");t.sleep(e)}sleepAfter(e,t){if(!0===Thread.__stopcontrols__)return this;if(null!==this.__delaytimeout__)try{clearTimeout(this.__delaytimeout__)}catch(r){}return this.__delaytimeout__=setTimeout(()=>this.sleep(t),e),this}static sleepAfter(e,t){if(!0===Thread.__stopcontrols__)return this;let r=ThreadExecutor.currentThread;if(null==r)throw new ThreadError("Thread.sleepAfter called outside thread environment");r.sleepAfter(e,t)}join(e){if(!0!==Thread.__stopcontrols__)throw new ThreadError("Thread.join method can't be called outside thread environment")}catch(e){return!0===Thread.__stopcontrols__||(this.__exceptionFunc__=e),this}onfinish(e){return!0===Thread.__stopcontrols__||(this.__finishFunc__=e),this}onyield(e){return!0===Thread.__stopcontrols__||(this.__yieldFunc__=e),this}isdone(){return this.__done__}issleeping(){return this.__sleeping__}isstarted(){return this.__started__}isrunning(){return this.__running__}isstopped(){return this.__stopped__}ispaused(){return this.__paused__}result(){return this.__result__}}Thread.LOW_PRIORITY_LEVEL=1,Thread.MID_PRIORITY_LEVEL=2,Thread.HIGH_PRIORITY_LEVEL=3,Thread.innerfunctionsisolation=!1,Thread.__stopcontrols__=!1;class ThreadExecutor{static handleThreadQueue(){void 0!==ThreadExecutor.queue&&0!==ThreadExecutor.queue.length&&(ThreadExecutor.__isLooping__=!0,ThreadExecutor.__isHandling__=!1,ThreadExecutor.__timeSpentOutsideThreads__=void 0,ThreadExecutor.queueIndex=0,ThreadExecutor.currentThread=null,ThreadExecutor.handlerLoop(!1))}static handlerLoop(e){if(void 0!==ThreadExecutor.__timeSpentOutsideThreads__?ThreadExecutor.__timeSpentOutsideThreads__=Date.now()-ThreadExecutor.__timeSpentOutsideThreads__:ThreadExecutor.__timeSpentOutsideThreads__=10,ThreadExecutor.__timeSpentOutsideThreads__=Math.min(ThreadExecutor.__timeSpentOutsideThreads__,20),!e&&ThreadExecutor.__isHandling__)return;if(void 0!==ThreadExecutor.handlerlooptimeout&&null!==ThreadExecutor.handlerlooptimeout)try{clearTimeout(ThreadExecutor.handlerlooptimeout)}catch(t){}let r=ThreadExecutor.queue[ThreadExecutor.queueIndex];if(null!=r){if(r.__sleeping__||!r.__started__||r.__stopped__||!r.__running__||r.__paused__)ThreadExecutor.queueIndex++,ThreadExecutor.queueIndex=ThreadExecutor.queueIndex%ThreadExecutor.queue.length;else{ThreadExecutor.__isHandling__=!0,ThreadExecutor.currentThread=r,Thread.this=r,r.__sleepingpriority__=!1,r.__resumingpriority__=!1,void 0===r.__generator__&&(r.__generator__=r.__generatorFunc__(...r.__args__));let i=r.__generator__.next();r.__stepscount__=!0!==i.done?i.value:r.__stepscount__,i instanceof Error||!0!==i.done?(void 0!==r.__yieldFunc__&&r.__yieldFunc__(i.value),void 0!==ThreadExecutor.__globalYieldFunc__&&null!==ThreadExecutor.__globalYieldFunc__&&ThreadExecutor.__globalYieldFunc__(i.value,r),void 0!==r.__threadgroup__&&null!==r.__threadgroup__&&void 0!==r.__threadgroup__.__yieldFunc__&&null!==r.__threadgroup__.__yieldFunc__&&r.__threadgroup__.__yieldFunc__(i.value,r),ThreadExecutor.queueIndex++,ThreadExecutor.queueIndex=ThreadExecutor.queueIndex%ThreadExecutor.queue.length):(ThreadExecutor.queue.splice(ThreadExecutor.queueIndex,1),r.__result__=i.value,r.__done__=!0,r.__running__=!1,r.__sleepingpriority__=!1,r.__resumingpriority__=!1,void 0!==r.__finishFunc__&&r.__finishFunc__(i.value),void 0!==ThreadExecutor.__globalFinishFunc__&&null!==ThreadExecutor.__globalFinishFunc__&&ThreadExecutor.__globalFinishFunc__(i.value,r),void 0!==r.__threadgroup__&&null!==r.__threadgroup__&&void 0!==r.__threadgroup__.__finishFunc__&&null!==r.__threadgroup__.__finishFunc__&&r.__threadgroup__.__finishFunc__(i.value,r),ThreadExecutor.queueIndex>=ThreadExecutor.queue.length&&(ThreadExecutor.queueIndex=0)),ThreadExecutor.__isHandling__=!1}}0!==ThreadExecutor.queue.length?(ThreadExecutor.handlerlooptimeout=setTimeout(()=>ThreadExecutor.handlerLoop(!1),void 0===ThreadExecutor.__loopingbeattime__||ThreadExecutor.__loopingbeattime__===ThreadExecutor.ADAPTIVE?ThreadExecutor.__timeSpentOutsideThreads__:ThreadExecutor.__loopingbeattime__),ThreadExecutor.__timeSpentOutsideThreads__=Date.now()):ThreadExecutor.__isLooping__=!1}static isHandling(){return void 0!==ThreadExecutor.__isHandling__&&ThreadExecutor.__isHandling__}static isLooping(){return void 0!==ThreadExecutor.__isLooping__&&ThreadExecutor.__isLooping__}static setBeatTime(e){ThreadExecutor.__loopingbeattime__=e}static notifyForSleeping(e,t){for(let r=0;r<ThreadExecutor.queue.length;r++){let i=ThreadExecutor.queue[r];if(!i.__sleepingpriority__){ThreadExecutor.queue.splice(t,1),ThreadExecutor.queue.splice(r,0,e);break}}e.__sleeping__=!1,ThreadExecutor.__timeSpentOutsideThreads__=void 0,ThreadExecutor.isLooping()?ThreadExecutor.handlerLoop(!0):ThreadExecutor.handleThreadQueue()}static notifyForResuming(e,t){for(let r=0;r<ThreadExecutor.queue.length;r++){let i=ThreadExecutor.queue[r];if(!i.__sleepingpriority__&&!i.__resumingpriority__){ThreadExecutor.queue.splice(t,1),ThreadExecutor.queue.splice(r,0,e);break}}ThreadExecutor.__timeSpentOutsideThreads__=void 0,ThreadExecutor.isLooping()?ThreadExecutor.handlerLoop(!0):ThreadExecutor.handleThreadQueue()}static notifyForPriority(e){let t=ThreadExecutor.queue.length;for(let r=0;r<ThreadExecutor.queue.length;r++){let i=ThreadExecutor.queue[r];if(!i.__sleepingpriority__&&!i.__resumingpriority__){t=r;break}}ThreadExecutor.queue.length-t!=0&&(ThreadExecutor.queue=ThreadExecutor.queue.slice(0,t).concat(ThreadExecutor.queue.slice(t,ThreadExecutor.queue.length).sort((e,t)=>((e.prioritylevel??1)|1)-((t.prioritylevel??1)|1))),ThreadExecutor.__timeSpentOutsideThreads__=void 0,(void 0===e||!0==e)&&(ThreadExecutor.isLooping()?ThreadExecutor.handlerLoop(!0):ThreadExecutor.handleThreadQueue()))}static catch(e){ThreadExecutor.__globalExceptionFunc__=e}static __threadExceptionOccurred__(e){if(e instanceof TypeError&&"Generator is already running"===e.message)return;e=new ThreadError(e,ThreadExecutor.currentThread);let t=!0;void 0!==ThreadExecutor.currentThread&&null!==ThreadExecutor.currentThread?(void 0!==ThreadExecutor.currentThread.__exceptionFunc__&&null!==ThreadExecutor.currentThread.__exceptionFunc__&&(t=!1,ThreadExecutor.currentThread.__exceptionFunc__(e)),void 0===ThreadExecutor.currentThread.__threadgroup__||null===ThreadExecutor.currentThread.__threadgroup__||void 0===ThreadExecutor.currentThread.__threadgroup__.__exceptionFunc__||null===ThreadExecutor.currentThread.__threadgroup__.__exceptionFunc__||(t=!1,ThreadExecutor.currentThread.__isolateErrors__||ThreadExecutor.currentThread.__threadgroup__.__exceptionFunc__(e,ThreadExecutor.currentThread)),void 0===ThreadExecutor.__globalExceptionFunc__||null===ThreadExecutor.__globalExceptionFunc__||(t=!1,ThreadExecutor.currentThread.__isolateErrors__||ThreadExecutor.__globalExceptionFunc__(e,ThreadExecutor.currentThread)),t&&!ThreadExecutor.currentThread.__isolateErrors__&&console.error(e)):console.error("Error thrown outside thread environment : ",e)}static __generatorFunc__(func,innerfunctionsisolation){let functionSource=`(${func.toString()})`;if(null===functionSource)throw new ThreadError("Failed to retrieve the function source code");if(ThreadExecutor.__isNativeFunction__(func))throw new ThreadError("Can't execute native function \""+functionSource+'", the thread function has to be a normal function, try to wrap the function into a normal function instead...');let ast=ThreadedTools.ast_generator.parse(functionSource,{ecmaVersion:"latest"}),alreadyAGeneratorFunction="function"==typeof func&&func.constructor&&"GeneratorFunction"===func.constructor.name;ThreadedTools.ast_walker.simple(ast,{FunctionDeclaration(e){e.body.istheouterfunction=!0},FunctionExpression(e){e.body.istheouterfunction=!0},ArrowFunctionExpression(e){e.body.istheouterfunction=!0}},{...ThreadedTools.ast_walker.base,FunctionDeclaration(){},FunctionExpression(){},ArrowFunctionExpression(){}}),ThreadedTools.ast_walker.fullAncestor(ast,(node,ancestors)=>{Thread.__stopcontrols__=!0,IsolatedThread.__stopcontrols__=!0,ThreadGroup.__stopcontrols__=!0;let functionId=0,jointThreadId=0;if("BlockStatement"===node.type){for(let i=ancestors.length-1;i>=0;i--){let ancestor=ancestors[i];if("FunctionDeclaration"===ancestor.type||"FunctionExpression"===ancestor.type||"ArrowFunctionExpression"===ancestor.type){let functioncode=ThreadedTools.escodegenerator.generate(ancestor),innerfunc=null;try{innerfunc=eval(`(${functioncode})`),ancestor.body.isFunctionGenerator="function"==typeof innerfunc&&innerfunc.constructor&&"GeneratorFunction"===innerfunc.constructor.name}catch(ex){}!0!==ancestor.body.istheouterfunction&&(ancestor.body.isinnerfunction=!0),ancestor.body.isFunctionGenerator||"ArrowFunctionExpression"===ancestor.type&&(ancestor.type="FunctionExpression",ancestor.id=null,ancestor.expression=void 0,"BlockStatement"!==node.body.type&&ThreadExecutor.__wrapArrowFunctionInBlockStatement__(ancestor))}}let isFunctionGenerator=void 0!==node.isFunctionGenerator?node.isFunctionGenerator:alreadyAGeneratorFunction;function handleStatement(stmt,newBody){if("IfStatement"===stmt.type){let current=stmt;for(;current;){if(current.consequent&&"BlockStatement"!==current.consequent.type){let newBody=[];handleStatement(current.consequent,newBody),current.consequent={type:"BlockStatement",body:newBody}}let alt=current.alternate;if(!alt)break;if("IfStatement"===alt.type)current=alt;else{if("BlockStatement"!==alt.type){let newBody=[];handleStatement(alt,newBody),current.alternate={type:"BlockStatement",body:newBody}}break}}}else if(("WhileStatement"===stmt.type||"DoWhileStatement"===stmt.type||"ForStatement"===stmt.type||"ForInStatement"===stmt.type||"ForOfStatement"===stmt.type)&&stmt.body&&"BlockStatement"!==stmt.body.type){let newBody=[];handleStatement(stmt.body,newBody),stmt.body={type:"BlockStatement",body:newBody}}let callee=null,calleeisthread=!1,calleeisthreadgroup=!1,calleeisisolatedthread=!1;try{calleeisthread=(callee=eval(ThreadedTools.escodegenerator.generate(stmt.expression.callee.object)))instanceof Thread,calleeisthreadgroup=callee instanceof ThreadGroup,calleeisisolatedthread=callee instanceof IsolatedThread}catch(ex){}let stmtisjoin="ExpressionStatement"===stmt.type&&"CallExpression"===stmt.expression.type&&"MemberExpression"===stmt.expression.callee.type&&"Identifier"===stmt.expression.callee.property.type&&"join"===stmt.expression.callee.property.name&&(calleeisthread||calleeisthreadgroup||calleeisisolatedthread);if(stmtisjoin){let threadVar=stmt.expression.callee.object,callArgs=stmt.expression.arguments;jointThreadId++,callArgs.length>=1&&(newBody.push({type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:`__isjointimeout${jointThreadId}__`},init:{type:"Literal",value:!1}}],kind:"let",leadingComments:[{type:"Line",value:` AUTO GENERATED : ${ThreadedTools.escodegenerator.generate(stmt).replaceAll(";","")} call implementation...`}]}),newBody.push({type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:`__jointimeout${jointThreadId}__`},init:{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"Identifier",name:"setTimeout"},arguments:[{type:"FunctionExpression",id:null,params:[],body:{type:"BlockStatement",body:[{type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:{type:"Identifier",name:`__isjointimeout${jointThreadId}__`},right:{type:"Literal",value:!0}}}],processforbidden:!0}},callArgs[0]]}}}],kind:"let"})),newBody.push({type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:`__jointthread${calleeisthread?"":"group"}${jointThreadId}__`},init:threadVar}],kind:"let",leadingComments:callArgs.length>=1?null:[{type:"Line",value:` AUTO GENERATED : ${ThreadedTools.escodegenerator.generate(stmt).replaceAll(";","")} call implementation...`}]}),newBody.push({type:"WhileStatement",test:callArgs.length>=1?{type:"LogicalExpression",operator:"&&",left:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:`__jointthread${calleeisthread?"":"group"}${jointThreadId}__`},property:{type:"Identifier",name:"isrunning"},computed:!1},arguments:[]},right:{type:"UnaryExpression",operator:"!",prefix:!0,argument:{type:"Identifier",name:`__isjointimeout${jointThreadId}__`}}}:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:`__jointthread${calleeisthread?"":"group"}${jointThreadId}__`},property:{type:"Identifier",name:"isrunning"},computed:!1},arguments:[]},body:{type:"BlockStatement",body:[{type:"ExpressionStatement",expression:{type:"YieldExpression",argument:isFunctionGenerator?null:{type:"Identifier",name:"__thefunctionstepscount__"}}}]}}),callArgs.length>=1&&newBody.push({type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"Identifier",name:"clearTimeout"},arguments:[{type:"Identifier",name:`__jointimeout${jointThreadId}__`}]}}),newBody.push({type:"EmptyStatement",leadingComments:[{type:"Line",value:` ${ThreadedTools.escodegenerator.generate(stmt).replaceAll(";","")} call implementation end`}]})}if((!0===Thread.innerfunctionsisolation||!0==innerfunctionsisolation)&&("VariableDeclaration"===stmt.type||"ExpressionStatement"===stmt.type||"FunctionDeclaration"===stmt.type||"FunctionExpression"===stmt.type||"ArrowFunctionExpression"===stmt.type)){let originalVarName="VariableDeclaration"===stmt.type?stmt.declarations[0].id.name:null,callExpr="VariableDeclaration"===stmt.type?stmt.declarations[0].init:stmt.expression,functionCallee=null,isNativeOrLibraryFunction=!1,dontIsolateToThread=!1;if("ArrowFunctionExpression"===callExpr.type){for(let declarator of stmt.declarations)if("VariableDeclarator"===declarator.type&&"Identifier"===declarator.id.type){let varName=declarator.id.name;functionCallee={type:"Identifier",name:varName}}let generatedcode=null;try{generatedcode="("+ThreadedTools.escodegenerator.generate(callExpr)+")",isNativeOrLibraryFunction=ThreadExecutor.__isNativeOrLibraryFunction__(eval(generatedcode))}catch(ex){try{isNativeOrLibraryFunction=ThreadExecutor.__isNativeOrLibraryFunction__(eval(generatedcode.replace("this","ThreadExecutor.currentThread")))}catch(ex2){isNativeOrLibraryFunction=!1}}dontIsolateToThread=!0}else{functionCallee=callExpr.callee;let generatedcode=null;if(null!=functionCallee)try{generatedcode=`(${ThreadedTools.escodegenerator.generate(functionCallee)})`,isNativeOrLibraryFunction=ThreadExecutor.__isNativeOrLibraryFunction__(eval(generatedcode))}catch(ex){try{isNativeOrLibraryFunction=ThreadExecutor.__isNativeOrLibraryFunction__(eval(generatedcode.replaceAll("this","Thread.this")))}catch(ex2){isNativeOrLibraryFunction=!1}}dontIsolateToThread="CallExpression"!==callExpr.type}if(isNativeOrLibraryFunction||dontIsolateToThread){stmtisjoin||newBody.push(stmt),isFunctionGenerator||newBody.push({type:"ExpressionStatement",expression:{type:"YieldExpression",argument:{type:"UpdateExpression",operator:"++",argument:{type:"Identifier",name:"__thefunctionstepscount__"},prefix:!1}}});return}if(!dontIsolateToThread){let threadVar=`__innerfunctionexecutor${++functionId}__`,tempVarName=`__innerfunctionexecutionresult${functionId}__`;newBody.push({type:"VariableDeclaration",kind:"const",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:threadVar},init:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Thread"},property:{type:"Identifier",name:"innerThreadFor"},computed:!1,optional:!1},arguments:[{type:"MemberExpression",object:{type:"Identifier",name:"ThreadExecutor"},property:{type:"Identifier",name:"currentThread"},computed:!1,optional:!1},functionCallee]},property:{type:"Identifier",name:"setId"},computed:!1,optional:!1},arguments:[{type:"BinaryExpression",operator:"+",left:{type:"MemberExpression",object:{type:"MemberExpression",object:{type:"Identifier",name:"ThreadExecutor"},property:{type:"Identifier",name:"currentThread"},computed:!1,optional:!1},property:{type:"Identifier",name:"id"},computed:!1,optional:!1},right:{type:"Literal",value:"'s inner thread",raw:"'s inner thread"}}]},property:{type:"Identifier",name:"setArgs"},computed:!1,optional:!1},arguments:callExpr.arguments},property:{type:"Identifier",name:"isolateErrors"},computed:!1,optional:!1},arguments:[{type:"Literal",value:!0,raw:"true"}]},property:{type:"Identifier",name:"start"},computed:!1,optional:!1},arguments:[]}}]},{type:"WhileStatement",test:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:threadVar},property:{type:"Identifier",name:"isrunning"},computed:!1},arguments:[]},body:{type:"BlockStatement",body:[{type:"ExpressionStatement",expression:{type:"YieldExpression",argument:isFunctionGenerator?null:{type:"Identifier",name:"__thefunctionstepscount__"}}}]}},{type:"VariableDeclaration",kind:"let",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:null!==originalVarName?originalVarName:tempVarName},init:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:threadVar},property:{type:"Identifier",name:"result"}},arguments:[]}}]},isFunctionGenerator?{type:"EmptyStatement"}:{type:"ExpressionStatement",expression:{type:"YieldExpression",argument:{type:"UpdateExpression",operator:"++",argument:{type:"Identifier",name:"__thefunctionstepscount__"},prefix:!1}}},{type:"IfStatement",test:{type:"BinaryExpression",operator:"instanceof",left:{type:"Identifier",name:null!==originalVarName?originalVarName:tempVarName},right:{type:"Identifier",name:"Error"}},consequent:{type:"BlockStatement",body:[{type:"ThrowStatement",argument:{type:"NewExpression",callee:{type:"Identifier",name:"ThreadError"},arguments:[{type:"Identifier",name:null!==originalVarName?originalVarName:tempVarName},{type:"VariableDeclarator",id:{type:"Identifier",name:threadVar}}]}}]},alternate:null})}}else stmtisjoin||newBody.push(stmt),isFunctionGenerator||!0===node.isinnerfunction||"ReturnStatement"===stmt.type||"ContinueStatement"===stmt.type||"BreakStatement"===stmt.type||"ThrowStatement"===stmt.type||newBody.push({type:"ExpressionStatement",expression:{type:"YieldExpression",argument:{type:"UpdateExpression",operator:"++",argument:{type:"Identifier",name:"__thefunctionstepscount__"},prefix:!1}}})}let newBody=[];for(let i=0;i<node.body.length;i++)handleStatement(node.body[i],newBody);node.body=newBody}return Thread.__stopcontrols__=!1,IsolatedThread.__stopcontrols__=!1,ThreadGroup.__stopcontrols__=!1,node}),ThreadedTools.ast_walker.simple(ast,{FunctionDeclaration(e){(!0===Thread.innerfunctionsisolation||!0===innerfunctionsisolation)&&!0!==e.body.processforbidden&&(ThreadExecutor.__wrapFunctionBodyInTryCatch__(e,!e.generator,!0),e.generator=!0)},FunctionExpression(e){(!0===Thread.innerfunctionsisolation||!0===innerfunctionsisolation)&&!0!==e.body.processforbidden&&(ThreadExecutor.__wrapFunctionBodyInTryCatch__(e,!e.generator,!0),e.generator=!0)},ArrowFunctionExpression(e){"BlockStatement"!==e.body.type&&ThreadExecutor.__wrapArrowFunctionInBlockStatement__(e),(!0===Thread.innerfunctionsisolation||!0===innerfunctionsisolation)&&!0!==e.body.processforbidden&&(ThreadExecutor.__wrapFunctionBodyInTryCatch__(e,!e.generator,!0),e.type="FunctionExpression",e.generator=!0,e.expression=!1)}}),ThreadedTools.ast_walker.simple(ast,{FunctionDeclaration(e){!0!==e.body.processforbidden&&(ThreadExecutor.__wrapFunctionBodyInTryCatch__(e,!e.generator,!0),e.generator=!0,e.body.body.unshift({type:"EmptyStatement",leadingComments:[{type:"Line",value:" AUTO GENERATED THREAD GENERATOR FUNCTION BY threaded.js..."}]}))},FunctionExpression(e){!0!==e.body.processforbidden&&(ThreadExecutor.__wrapFunctionBodyInTryCatch__(e,!e.generator,!0),e.generator=!0,e.body.body.unshift({type:"EmptyStatement",leadingComments:[{type:"Line",value:" AUTO GENERATED THREAD GENERATOR FUNCTION BY threaded.js..."}]}))},ArrowFunctionExpression(e){"BlockStatement"!==e.body.type&&ThreadExecutor.__wrapArrowFunctionInBlockStatement__(e),!0!==e.body.processforbidden&&(ThreadExecutor.__wrapFunctionBodyInTryCatch__(e,!e.generator,!0),e.type="FunctionExpression",e.generator=!0,e.expression=!1,e.body.body.unshift({type:"EmptyStatement",leadingComments:[{type:"Line",value:" AUTO GENERATED THREAD GENERATOR FUNCTION BY threaded.js..."}]}))}},{...ThreadedTools.ast_walker.base,FunctionDeclaration(){},FunctionExpression(){},ArrowFunctionExpression(){}});let newCode,generatorFunc;return eval(ThreadedTools.escodegenerator.generate(ast,{comment:!0}))}static __isNativeFunction__(e){if(void 0===e||"function"!=typeof e)return!1;let t="function"==typeof e&&e.toString().includes("[native code]")||e.toString().includes("[wasm code]");return t||(t="function"==typeof e&&/#\w+/.test(e.toString())),t}static __isNativeOrLibraryFunction__(e){if(e.name,void 0===e||"function"!=typeof e)return!1;let t=e.name;return!!t&&(ThreadExecutor.__isNativeFunction__(e)||Thread.prototype.hasOwnProperty(t)||IsolatedThread.prototype.hasOwnProperty(t)||ThreadExecutor.prototype.hasOwnProperty(t)||ThreadGroup.prototype.hasOwnProperty(t)||ThreadTask.prototype.hasOwnProperty(t)||ThreadError.prototype.hasOwnProperty(t))}static __wrapArrowFunctionInBlockStatement__(e){e.body,e.expression&&(e.body={type:"BlockStatement",body:[{type:"ReturnStatement",argument:e.body}]},e.expression=!1)}static __wrapFunctionBodyInTryCatch__(e,t,r){if(!0===e.wrappedintrycatch)return;e.wrappedintrycatch=!0;let i=e.body.body;e.body.body=[{type:"TryStatement",block:{type:"BlockStatement",body:[!0===r?{type:"IfStatement",test:{type:"BinaryExpression",operator:"==",left:{type:"MemberExpression",object:{type:"Identifier",name:"ThreadExecutor"},property:{type:"Identifier",name:"currentThread"},computed:!1},right:{type:"Literal",value:null,raw:"null"}},consequent:{type:"BlockStatement",body:[{type:"ThrowStatement",argument:{type:"NewExpression",callee:{type:"Identifier",name:"ThreadError"},arguments:[{type:"Literal",value:"a thread function called outside thread environment",raw:'"a thread function called outside thread environment"'}]}}]}}:{type:"EmptyStatement"},!0===t?{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"__thefunctionstepscount__"},init:{type:"Literal",value:0}}],kind:"let"}:{type:"EmptyStatement"},...i]},handler:{type:"CatchClause",param:{type:"Identifier",name:"ex"},body:{type:"BlockStatement",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"ThreadExecutor"},property:{type:"Identifier",name:"__threadExceptionOccurred__"}},arguments:[{type:"Identifier",name:"ex"}]}},{type:"ReturnStatement",argument:{type:"Identifier",name:"ex"}}]}},finalizer:null}]}static onfinish(e){ThreadExecutor.__globalFinishFunc__=e}static onyield(e){ThreadExecutor.__globalYieldFunc__=e}}ThreadExecutor.ADAPTIVE=-1;class ThreadGroup{constructor(...e){if(!0===ThreadGroup.__stopcontrols__)return this;for(let t of((void 0===ThreadGroup.__count__||null===ThreadGroup.__count__||Number.isNaN(ThreadGroup.__count__))&&(ThreadGroup.__count__=0),ThreadGroup.__count__++,this.id="anonymous threadgroup n-"+ThreadGroup.__count__,null==e?this.threads=[]:this.threads=e,this.threads))null!=t&&(t.__threadgroup__=this);this.__delaytimeout__=null,this.__sleeping__=!1,this.__started__=!1,this.__running__=!1,this.__stopped__=!1,this.__paused__=!1}setId(e){return!0===ThreadGroup.__stopcontrols__||(this.id=null==e?"anonymous threadgroup n-"+ThreadGroup.__count__:e+" (threadgroup n-"+ThreadGroup.__count__+")"),this}add(e){if(!0===ThreadGroup.__stopcontrols__)return this;if(null==e)throw new ThreadError("Given thread in threadgroup add function is undefined or null",this);return this.threads.push(e),e.__threadgroup__=this,this}remove(e){if(!0===ThreadGroup.__stopcontrols__||null==e)return this;let t=this.threads.indexOf(e);if(-1===t)throw new ThreadError('Cannot remove thread "'+e.id+" from threadgroup, the thread is not added to that threadgroup");return this.threads.splice(t,1),e.__threadgroup__=void 0,this}setPriorityLevel(e){if(!0===ThreadGroup.__stopcontrols__)return this;if(0==this.threads.length)throw new ThreadError("threadgroup has no threads",this);if("number"!=typeof e)throw new ThreadError("thread priority level must be a valid number",this);if(!Number.isInteger(e))throw new ThreadError("thread priority level must be an integer number",this);if(e<0)throw new ThreadError("thread priority level must be a positive number",this);for(let t of this.threads)null!=t&&t.setPriorityLevel(e);return this}length(){return this.threads.length}static count(){return ThreadGroup.__count__}stepsCount(){if(0==this.threads.length)throw new ThreadError("threadgroup has no threads",this);let e=0;for(let t of this.threads)null!=t&&(e+=t.stepsCount());return e}start(){if(!0===ThreadGroup.__stopcontrols__)return this;if(0==this.threads.length)throw new ThreadError("threadgroup has no threads",this);for(let e of(this.__started__=!0,this.threads))null!=e&&e.start();return this}startAfter(e){if(!0===ThreadGroup.__stopcontrols__)return this;if(0==this.threads.length)throw new ThreadError("threadgroup has no threads",this);if(null!==this.__delaytimeout__)try{clearTimeout(this.__delaytimeout__)}catch(t){}return this.__paused__||this.pause(),this.__delaytimeout__=setTimeout(()=>this.start(),e),this}startChained(e=!1,t=0){if(!0===ThreadGroup.__stopcontrols__)return this;if(0==this.threads.length)throw new ThreadError("threadgroup has no threads",this);this.__started__=!0;for(let r=0;r<this.threads.length;r++){let i=r;e&&(i=this.threads.length-1-r);let n=this.threads[i],o=i+(e?-1:1),s=o>=0&&o<this.threads.length?this.threads[o]:void 0;if(null!=n&&null!=s){let a=n.__finishFunc__;n.onfinish(e=>{if(n.onfinish(a),0==t)s.start();else{if(null!==n.__delaytimeout__)try{clearTimeout(n.__delaytimeout__)}catch(r){}n.__delaytimeout__=setTimeout(()=>s.start(),t)}"function"==typeof a&&a(e)})}0===r&&null!=n&&n.start()}return this}startChainedAfter(e,t,r){if(!0===ThreadGroup.__stopcontrols__)return this;if(0==this.threads.length)throw new ThreadError("threadgroup has no threads",this);if(null!==this.__delaytimeout__)try{clearTimeout(this.__delaytimeout__)}catch(i){}return this.__delaytimeout__=setTimeout(()=>this.startChained(t,r),e),this}interrupt(){if(!0===ThreadGroup.__stopcontrols__)return this;if(0==this.threads.length)throw new ThreadError("threadgroup has no threads",this);return this.stop()}interruptAfter(e){if(!0===ThreadGroup.__stopcontrols__)return this;if(0==this.threads.length)throw new ThreadError("threadgroup has no threads",this);if(null!==this.__delaytimeout__)try{clearTimeout(this.__delaytimeout__)}catch(t){}return this.__delaytimeout__=setTimeout(()=>this.interrupt(),e),this}stop(){if(!0===ThreadGroup.__stopcontrols__)return this;if(0==this.threads.length)throw new ThreadError("threadgroup has no threads",this);if(!this.__started__)return console.error("ThreadGroup not started yet"),this;if(this.__stopped__)return console.error("ThreadGroup already stopped"),this;for(let e of(this.__stopped__=!0,this.threads))null!=e&&e.stop();return this}stopAfter(e){if(!0===ThreadGroup.__stopcontrols__)return this;if(0==this.threads.length)throw new ThreadError("threadgroup has no threads",this);if(null!==this.__delaytimeout__)try{clearTimeout(this.__delaytimeout__)}catch(t){}return this.__delaytimeout__=setTimeout(()=>this.stop(),e),this}pause(){if(!0===ThreadGroup.__stopcontrols__)return this;if(0==this.threads.length)throw new ThreadError("threadgroup has no threads",this);if(this.__paused__)return console.error("ThreadGroup already paused"),this;for(let e of(this.__paused__=!0,this.threads))null==e||e.__paused__||e.pause();return this}pauseAfter(e){if(!0===ThreadGroup.__stopcontrols__)return this;if(0==this.threads.length)throw new ThreadError("threadgroup has no threads",this);if(null!==this.__delaytimeout__)try{clearTimeout(this.__delaytimeout__)}catch(t){}return this.__delaytimeout__=setTimeout(()=>this.pause(),e),this}resume(){if(!0===ThreadGroup.__stopcontrols__)return this;if(0==this.threads.length)throw new ThreadError("threadgroup has no threads",this);if(!this.__paused__&&!this.__sleeping__)return console.error("ThreadGroup is neither paused nor sleeping"),this;for(let e of(this.__sleeping__=!1,this.__paused__=!1,this.threads))null!=e&&e.resume();return this}resumeAfter(e){if(!0===ThreadGroup.__stopcontrols__)return this;if(0==this.threads.length)throw new ThreadError("threadgroup has no threads",this);if(null!==this.__delaytimeout__)try{clearTimeout(this.__delaytimeout__)}catch(t){}return this.__delaytimeout__=setTimeout(()=>this.resume(),e),this}sleep(e){if(!0===ThreadGroup.__stopcontrols__)return this;if(0==this.threads.length)throw new ThreadError("threadgroup has no threads",this);for(let t of(this.__sleeping__=!0,this.threads))null!=t&&t.sleep(e);return this}sleepAfter(e,t){if(!0===ThreadGroup.__stopcontrols__)return this;if(0==this.threads.length)throw new ThreadError("threadgroup has no threads",this);if(null!==this.__delaytimeout__)try{clearTimeout(this.__delaytimeout__)}catch(r){}return this.__delaytimeout__=setTimeout(()=>this.sleep(t),e),this}join(e){if(!0===ThreadGroup.__stopcontrols__)return this;throw new ThreadError("ThreadGroup.join method can't be called outside thread environment")}catch(e){return!0===ThreadGroup.__stopcontrols__||(this.__exceptionFunc__=e),this}onfinish(e){return!0===ThreadGroup.__stopcontrols__||(this.__finishFunc__=e),this}onyield(e){return!0===ThreadGroup.__stopcontrols__||(this.__yieldFunc__=e),this}isdone(){let e=!0;for(let t of this.threads)if(!t.isdone()){e=!1;break}return e}issleeping(){return this.__sleeping__}isstarted(){return this.__started__}isrunning(){let e=!1;for(let t of this.threads)if(t.isrunning()){e=!0;break}return e}isstopped(){return this.__stopped__}ispaused(){return this.__paused__}}ThreadGroup.__stopcontrols__=!1;class ThreadTask{constructor(){(void 0===ThreadTask.__count__||null===ThreadTask.__count__||Number.isNaN(ThreadTask.__count__))&&(ThreadTask.__count__=0),ThreadTask.__count__++,this.id="anonymous threadtask n-"+ThreadTask.__count__,this.queue=[]}static run(e){let t=new ThreadTask;return t.queue.push(e),t}then(e){return this.queue.push(e),this}setId(e){return this.id=null==e?"anonymous threadtask n-"+ThreadTask.__count__:e+" (threadtask n-"+ThreadTask.__count__+")",this}chained(e){let t={__isolated__:!1,start:(r,i)=>(this.group(e,t.__branchtaskid__,t.__isolated__).startChained(r,i),t),startAfter:(r,i,n)=>(this.group(e,t.__branchtaskid__,t.__isolated__).startChainedAfter(r,i,n),t),chained:this.chained,atonce:this.atonce,isolated:(e=!0)=>(t.__isolated__=e,t),setId:e=>(t.__branchtaskid__=e,t),group:this.group,queue:this.queue,__branchtaskid__:this.id,run:ThreadTask.run};return t}atonce(e){let t={__isolated__:!1,start:()=>(this.group(e,t.__branchtaskid__,t.__isolated__).start(),t),startAfter:r=>(this.group(e,t.__branchtaskid__,t.__isolated__).startAfter(r),t),chained:this.chained,atonce:this.atonce,isolated:(e=!0)=>(t.__isolated__=e,t),setId:e=>(t.__branchtaskid__=e,t),group:this.group,queue:this.queue,__branchtaskid__:this.id,run:ThreadTask.run};return t}group(e=Thread.LOW_PRIORITY_LEVEL,t=this.id,r=!1){let i=new ThreadGroup;for(let n of this.queue)i.add(r?new IsolatedThread(n,(n.name?.trim()?n.name+"'s ThreadTask isolated thread":"anonymous ThreadTask isolated thread")+` [${t}]`):new Thread(n,e,(n.name?.trim()?n.name+"'s ThreadTask thread":"anonymous ThreadTask thread")+` [${t}]`));return i}}class ThreadError extends Error{constructor(e,t){super(void 0===t?"":(t instanceof Thread?"error in thread ":"error in threadgroup ")+'"'+t.id+'"'),this.cause=e instanceof Error?e:void 0}}class IsolatedThread{constructor(e,t){if(!0===IsolatedThread.__stopcontrols__)return this;(void 0===IsolatedThread.__count__||null===IsolatedThread.__count__||Number.isNaN(IsolatedThread.__count__))&&(IsolatedThread.__count__=0),IsolatedThread.__count__++,void 0!==e&&(this.__func__=e,this.__generatorFunc__=ThreadExecutor.__generatorFunc__(e,!1),this.__createInternalWebWorker__()),this.id=void 0===t?"anonymous isolated thread n-"+IsolatedThread.__count__:t+" (isolated thread n-"+IsolatedThread.__count__+")",(void 0===IsolatedThread.threads||null===IsolatedThread.threads)&&(IsolatedThread.threads=new Map),IsolatedThread.threads.set(this.id,this),this.__stepscount__=0,this.__args__=[],this.__result__=null,this.__sleepingtimeout__=null,this.__delaytimeout__=null,this.__done__=!1,this.__sleeping__=!1,this.__started__=!1,this.__running__=!1,this.__stopped__=!1,this.__paused__=!1,this.__terminated__=!1}static count(){return IsolatedThread.__count__}setId(e){return!0===IsolatedThread.__stopcontrols__?this:null==e?(console.error("Null or undefined isolated thread id in setId method"),this):(IsolatedThread.threads.delete(this.id),this.id=e+" (isolated thread n-"+IsolatedThread.__count__+")",IsolatedThread.threads.set(this.id,this),this)}setArgs(...e){return!0===IsolatedThread.__stopcontrols__||(this.__args__=e,this.__argschanged__=!0),this}setFunction(e){return!0===IsolatedThread.__stopcontrols__||(this.__paused__||this.pause(),this.__func__=e,this.__generatorFunc__=ThreadExecutor.__generatorFunc__(this.__func__,!1),this.__started__&&this.start()),this}toString(){return this.id}stepsCount(){return this.__stepscount__}__createInternalWebWorker__(){let e=e=>{let t=void 0===e.data?e:e.data;t.id,this.__result__=t.result,this.__done__=t.done;let r=t.error;null!=r?void 0!==this.__exceptionFunc__&&null!==this.__exceptionFunc__&&this.__exceptionFunc__(r):this.isdone()?(void 0!==this.__finishFunc__&&null!==this.__finishFunc__&&this.__finishFunc__(this.result()),this.terminate()):(this.__stepscount__=this.__result__,void 0!==this.__yieldFunc__&&null!==this.__yieldFunc__&&this.__yieldFunc__(this.result())),!0===t.terminate&&this.terminate()};ThreadedTools.createWorker(this,this.__generatorFunc__,e)}__notifyWorker__(e){let t=this.__argschanged__?this.__args__:null;ThreadedTools.postMessageToWorker(this.__worker__,{id:this.id,sleeping:this.__sleeping__,started:this.__started__,paused:this.__paused__,stopped:this.__stopped__,running:this.__running__,args:t,restarted:!0===e,argschanged:this.__argschanged__}),this.__argschanged__=!1}start(){if(!0===IsolatedThread.__stopcontrols__)return this;if(this.__terminated__)throw new ThreadError(`Isolated thread "${this.__terminated__.id}" terminated`);if(null!==this.__sleepingtimeout__)try{clearTimeout(this.__sleepingtimeout__)}catch(e){}return this.__stepscount__=0,this.__result__=null,this.__done__=!1,this.__sleeping__=!1,this.__started__=!0,this.__paused__=!1,this.__stopped__=!1,this.__running__=!0,this.__notifyWorker__(!0),this}startAfter(e){if(!0===IsolatedThread.__stopcontrols__)return this;if(this.__terminated__)throw new ThreadError(`Isolated thread "${this.__terminated__.id}" terminated`);if(null!==this.__delaytimeout__)try{clearTimeout(this.__delaytimeout__)}catch(t){}return this.__paused__||this.pause(),this.__delaytimeout__=setTimeout(()=>this.start(),e),this}interrupt(){if(!0===IsolatedThread.__stopcontrols__)return this;if(this.__terminated__)throw new ThreadError(`Isolated thread "${this.__terminated__.id}" terminated`);return this.stop()}interruptAfter(e){if(!0===IsolatedThread.__stopcontrols__)return this;if(this.__terminated__)throw new ThreadError(`Isolated thread "${this.__terminated__.id}" terminated`);if(null!==this.__delaytimeout__)try{clearTimeout(this.__delaytimeout__)}catch(t){}return this.__paused__||this.pause(),this.__delaytimeout__=setTimeout(()=>this.interrupt(),e),this}stop(){if(!0===IsolatedThread.__stopcontrols__)return this;if(this.__terminated__)throw new ThreadError(`Isolated thread "${this.__terminated__.id}" terminated`);return this.__started__?this.__stopped__?(console.error("IsolatedThread already stopped"),this):(this.__stopped__=!0,this.__running__=!1,this.__notifyWorker__(),this):(console.error("IsolatedThread not started yet"),this)}stopAfter(e){if(!0===IsolatedThread.__stopcontrols__)return this;if(this.__terminated__)throw new ThreadError(`Isolated thread "${this.__terminated__.id}" terminated`);if(null!==this.__delaytimeout__)try{clearTimeout(this.__delaytimeout__)}catch(t){}return this.__delaytimeout__=setTimeout(()=>this.stop(),e),this}pause(){if(!0===IsolatedThread.__stopcontrols__)return this;if(this.__terminated__)throw new ThreadError(`Isolated thread "${this.__terminated__.id}" terminated`);return this.__paused__?(console.error("IsolatedThread already paused"),this):(this.__paused__=!0,this.__notifyWorker__(),this)}pauseAfter(e){if(!0===IsolatedThread.__stopcontrols__)return this;if(this.__terminated__)throw new ThreadError(`Isolated thread "${this.__terminated__.id}" terminated`);if(null!==this.__delaytimeout__)try{clearTimeout(this.__delaytimeout__)}catch(t){}return this.__delaytimeout__=setTimeout(()=>this.pause(),e),this}resume(){if(!0===IsolatedThread.__stopcontrols__)return this;if(this.__terminated__)throw new ThreadError(`Isolated thread "${this.__termi