"use strict";var e=require("node:cluster"),t=require("node:fs"),r=require("node:process"),s=require("node:worker_threads"),i=require("node:crypto"),o=require("node:os"),n=require("node:async_hooks"),a=require("node:events"),u=require("node:perf_hooks");function h(e){var t=Object.create(null);return e&&Object.keys(e).forEach((function(r){if("default"!==r){var s=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,s.get?s:{enumerable:!0,get:function(){return e[r]}})}})),t.default=e,Object.freeze(t)}var k=h(o);const c=Object.freeze({dynamic:"dynamic",fixed:"fixed"}),d=Object.freeze({backPressure:"backPressure",backPressureEnd:"backPressureEnd",busy:"busy",busyEnd:"busyEnd",destroy:"destroy",empty:"empty",error:"error",full:"full",fullEnd:"fullEnd",ready:"ready",taskError:"taskError"}),l="default",m=Object.freeze((()=>{})),g=e=>Array.isArray(e)&&0===e.length?0:Array.isArray(e)&&1===e.length?e[0]:e.reduce(((e,t)=>e+t),0)/e.length,w=e=>{if(Array.isArray(e)&&0===e.length)return 0;if(Array.isArray(e)&&1===e.length)return e[0];const t=e.slice().sort(((e,t)=>e-t));return(t[t.length-1>>1]+t[t.length>>1])/2},p=(e,t=2)=>{const r=Math.pow(10,t);return Math.round(e*r*(1+Number.EPSILON))/r},y=e=>"object"==typeof e&&null!==e&&e.constructor===Object&&"[object Object]"===Object.prototype.toString.call(e),f=(e,t)=>t===e,T=e=>e?.constructor===(async()=>{}).constructor,N=()=>i.getRandomValues(new Uint32Array(1))[0]/4294967296,W=(...e)=>e.reduce(((e,t)=>ee.reduce(((e,t)=>e>t?e:t),Number.NEGATIVE_INFINITY),S=(e,t)=>({name:e,...null!=t?.priority&&{priority:t.priority},...null!=t?.strategy&&{strategy:t.strategy}}),v=Object.freeze({FAIR_SHARE:"FAIR_SHARE",INTERLEAVED_WEIGHTED_ROUND_ROBIN:"INTERLEAVED_WEIGHTED_ROUND_ROBIN",LEAST_BUSY:"LEAST_BUSY",LEAST_ELU:"LEAST_ELU",LEAST_USED:"LEAST_USED",ROUND_ROBIN:"ROUND_ROBIN",WEIGHTED_ROUND_ROBIN:"WEIGHTED_ROUND_ROBIN"}),x=Object.freeze({elu:"elu",runTime:"runTime",waitTime:"waitTime"}),b=386,I=Object.freeze({cluster:"cluster",thread:"thread"}),C={aggregate:!1,average:!1,median:!1},P=e=>({concurrency:1,size:Math.pow(e,2),tasksFinishedTimeout:2e3,tasksStealingOnBackPressure:!0,tasksStealingRatio:.6,taskStealing:!0}),F=e=>{if(null==e)throw new TypeError("The worker file path must be specified");if("string"!=typeof e)throw new TypeError("The worker file path must be a string");if(!t.existsSync(e))throw new Error(`Cannot find the worker file '${e}'`)},O=(e,t)=>{if(null==t)throw new TypeError("Cannot instantiate a dynamic pool without specifying the maximum pool size");if(!Number.isSafeInteger(t))throw new TypeError("Cannot instantiate a dynamic pool with a non safe integer maximum pool size");if(e>t)throw new RangeError("Cannot instantiate a dynamic pool with a maximum pool size inferior to the minimum pool size");if(0===t)throw new RangeError("Cannot instantiate a dynamic pool with a maximum pool size equal to zero");if(e===t)throw new RangeError("Cannot instantiate a dynamic pool with a minimum pool size equal to the maximum pool size. Use a fixed pool instead")},R=e=>{if(null!=e&&!Number.isSafeInteger(e))throw new TypeError(`Invalid property 'priority': '${e.toString()}'`);if(null!=e&&Number.isSafeInteger(e)&&(e<-20||e>19))throw new RangeError("Property 'priority' must be between -20 and 19")},A=e=>{if(null!=e&&!Object.values(v).includes(e))throw new Error(`Invalid worker choice strategy '${e}'`)},q=e=>{if(null!=e&&!y(e))throw new TypeError("Invalid tasks queue options: must be a plain object");if(null!=e?.concurrency&&!Number.isSafeInteger(e.concurrency))throw new TypeError("Invalid worker node tasks concurrency: must be an integer");if(null!=e?.concurrency&&e.concurrency<=0)throw new RangeError(`Invalid worker node tasks concurrency: ${e.concurrency.toString()} is a negative integer or zero`);if(null!=e?.size&&!Number.isSafeInteger(e.size))throw new TypeError("Invalid worker node tasks queue size: must be an integer");if(null!=e?.size&&e.size<=0)throw new RangeError(`Invalid worker node tasks queue size: ${e.size.toString()} is a negative integer or zero`);if(null!=e?.tasksStealingRatio&&"number"!=typeof e.tasksStealingRatio)throw new TypeError("Invalid worker node tasks stealing ratio: must be a number");if(null!=e?.tasksStealingRatio&&(e.tasksStealingRatio<0||e.tasksStealingRatio>1))throw new RangeError("Invalid worker node tasks stealing ratio: must be between 0 and 1")},z=(e,t,r)=>{null!=t&&null!=r&&t.aggregate&&(e.aggregate=(e.aggregate??0)+r,e.minimum=W(r,e.minimum??Number.POSITIVE_INFINITY),e.maximum=E(r,e.maximum??Number.NEGATIVE_INFINITY),(t.average||t.median)&&(e.history.put(r),t.average?e.average=g(e.history.toArray()):null!=e.average&&delete e.average,t.median?e.median=w(e.history.toArray()):null!=e.median&&delete e.median))};"test"===r.env.NODE_ENV&&(exports.updateMeasurementStatistics=z);const M=(e,t,r)=>{const s=performance.now(),i=s-(r.timestamp??s);z(t.waitTime,e?.getTaskStatisticsRequirements().waitTime,i)},K=(e,t)=>{const r=e.tasks;null!=r.executing&&r.executing>0&&--r.executing,null==t.workerError?++r.executed:++r.failed},Q=(e,t,r)=>{null==r.workerError&&z(t.runTime,e?.getTaskStatisticsRequirements().runTime,r.taskPerformance?.runTime??0)},B=(e,t,r)=>{if(null!=r.workerError)return;const s=e?.getTaskStatisticsRequirements().elu;z(t.elu.active,s,r.taskPerformance?.elu?.active??0),z(t.elu.idle,s,r.taskPerformance?.elu?.idle??0),!0===s?.aggregate&&null!=r.taskPerformance?.elu&&(null!=t.elu.utilization?t.elu.utilization=(t.elu.utilization+r.taskPerformance.elu.utilization)/2:t.elu.utilization=r.taskPerformance.elu.utilization)},U=t=>t instanceof s.Worker?I.thread:t instanceof e.Worker?I.cluster:void 0,D=t=>t instanceof s.Worker?t.threadId:t instanceof e.Worker?t.id:void 0,_=Object.freeze({HARD:"HARD",SOFT:"SOFT"});class L{pool;opts;nextWorkerNodeKey=0;previousWorkerNodeKey=0;strategyPolicy={dynamicWorkerReady:!0,dynamicWorkerUsage:!1};taskStatisticsRequirements={elu:C,runTime:C,waitTime:C};constructor(e,t){this.pool=e,this.opts=t,this.choose=this.choose.bind(this),this.setOptions(this.opts)}checkNextWorkerNodeKey(){null!=this.nextWorkerNodeKey&&(this.nextWorkerNodeKey<0||!this.isWorkerNodeReady(this.nextWorkerNodeKey))&&delete this.nextWorkerNodeKey}getWorkerNodeTaskElu(e){return this.taskStatisticsRequirements.elu.median?this.pool.workerNodes[e].usage.elu.active.median??0:this.pool.workerNodes[e].usage.elu.active.average??0}getWorkerNodeTaskRunTime(e){return this.taskStatisticsRequirements.runTime.median?this.pool.workerNodes[e].usage.runTime.median??0:this.pool.workerNodes[e].usage.runTime.average??0}getWorkerNodeTaskWaitTime(e){return this.taskStatisticsRequirements.waitTime.median?this.pool.workerNodes[e].usage.waitTime.median??0:this.pool.workerNodes[e].usage.waitTime.average??0}isWorkerNodeReady(e){return this.pool.workerNodes[e]?.info?.ready??!1}resetWorkerNodeKeyProperties(){this.nextWorkerNodeKey=0,this.previousWorkerNodeKey=0}setPreviousWorkerNodeKey(e){this.previousWorkerNodeKey=null!=e&&e>=0?e:this.previousWorkerNodeKey}setTaskStatisticsRequirements(e){te(this.taskStatisticsRequirements.runTime,e.runTime.median),te(this.taskStatisticsRequirements.waitTime,e.waitTime.median),te(this.taskStatisticsRequirements.elu,e.elu.median)}setOptions(e){this.opts=ee(this.pool,e),this.setTaskStatisticsRequirements(this.opts)}}class V extends L{taskStatisticsRequirements={elu:{aggregate:!0,average:!0,median:!1},runTime:{aggregate:!0,average:!0,median:!1},waitTime:{aggregate:!0,average:!0,median:!1}};constructor(e,t){super(e,t),this.setTaskStatisticsRequirements(this.opts)}computeWorkerNodeVirtualTaskEndTimestamp(e){return this.getWorkerNodeVirtualTaskEndTimestamp(e,this.getWorkerNodeVirtualTaskStartTimestamp(e))}fairShareNextWorkerNodeKey(){return this.pool.workerNodes.reduce(((e,t,r,s)=>(null==t.strategyData?.virtualTaskEndTimestamp&&(t.strategyData={virtualTaskEndTimestamp:this.computeWorkerNodeVirtualTaskEndTimestamp(r)}),this.isWorkerNodeReady(r)&&t.strategyData.virtualTaskEndTimestampe-t)))]}interleavedWeightedRoundRobinNextWorkerNodeId(){0===this.pool.workerNodes.length?this.workerNodeId=0:this.roundId===this.roundWeights.length-1&&this.workerNodeId===this.pool.workerNodes.length-1?(this.roundId=0,this.workerNodeId=0):this.workerNodeId===this.pool.workerNodes.length-1?(this.roundId=this.roundId+1,this.workerNodeId=0):this.workerNodeId=this.workerNodeId+1}choose(){for(let e=this.roundId;e=this.roundWeights[e]&&this.workerNodeVirtualTaskExecutionTimethis.pool.workerNodes.length-1&&(this.workerNodeId=this.pool.workerNodes.length-1),this.previousWorkerNodeKey===e&&this.previousWorkerNodeKey>this.pool.workerNodes.length-1&&(this.previousWorkerNodeKey=this.pool.workerNodes.length-1),!0)}reset(){return this.resetWorkerNodeKeyProperties(),this.roundId=0,this.workerNodeId=0,this.workerNodeVirtualTaskExecutionTime=0,!0}setOptions(e){super.setOptions(e),this.roundWeights=this.getRoundWeights()}update(){return!0}}class j extends L{taskStatisticsRequirements={elu:C,runTime:{aggregate:!0,average:!1,median:!1},waitTime:{aggregate:!0,average:!1,median:!1}};constructor(e,t){super(e,t),this.setTaskStatisticsRequirements(this.opts)}leastBusyNextWorkerNodeKey(){return this.pool.workerNodes.reduce(((e,t,r,s)=>this.isWorkerNodeReady(r)&&(t.usage.waitTime.aggregate??0)+(t.usage.runTime.aggregate??0)<(s[e].usage.waitTime.aggregate??0)+(s[e].usage.runTime.aggregate??0)?r:e),0)}choose(){return this.setPreviousWorkerNodeKey(this.nextWorkerNodeKey),this.nextWorkerNodeKey=this.leastBusyNextWorkerNodeKey(),this.nextWorkerNodeKey}remove(){return!0}reset(){return!0}update(){return!0}}class $ extends L{taskStatisticsRequirements={elu:{aggregate:!0,average:!1,median:!1},runTime:C,waitTime:C};constructor(e,t){super(e,t),this.setTaskStatisticsRequirements(this.opts)}leastEluNextWorkerNodeKey(){return this.pool.workerNodes.reduce(((e,t,r,s)=>this.isWorkerNodeReady(r)&&(t.usage.elu.active.aggregate??0)<(s[e].usage.elu.active.aggregate??0)?r:e),0)}choose(){return this.setPreviousWorkerNodeKey(this.nextWorkerNodeKey),this.nextWorkerNodeKey=this.leastEluNextWorkerNodeKey(),this.nextWorkerNodeKey}remove(){return!0}reset(){return!0}update(){return!0}}class Y extends L{constructor(e,t){super(e,t)}leastUsedNextWorkerNodeKey(){return this.pool.workerNodes.reduce(((e,t,r,s)=>this.isWorkerNodeReady(r)&&t.usage.tasks.executing+t.usage.tasks.queuedthis.pool.workerNodes.length-1&&(this.nextWorkerNodeKey=this.pool.workerNodes.length-1),this.previousWorkerNodeKey===e&&this.previousWorkerNodeKey>this.pool.workerNodes.length-1&&(this.previousWorkerNodeKey=this.pool.workerNodes.length-1),!0)}reset(){return this.resetWorkerNodeKeyProperties(),!0}update(){return!0}}class J extends L{workerNodeVirtualTaskExecutionTime=0;taskStatisticsRequirements={elu:C,runTime:{aggregate:!0,average:!0,median:!1},waitTime:{aggregate:!0,average:!0,median:!1}};constructor(e,t){super(e,t),this.setTaskStatisticsRequirements(this.opts)}weightedRoundRobinNextWorkerNodeKey(){const e=this.opts.weights[this.nextWorkerNodeKey??this.previousWorkerNodeKey];return this.workerNodeVirtualTaskExecutionTimethis.pool.workerNodes.length-1&&(this.nextWorkerNodeKey=this.pool.workerNodes.length-1)),this.previousWorkerNodeKey===e&&this.previousWorkerNodeKey>this.pool.workerNodes.length-1&&(this.previousWorkerNodeKey=this.pool.workerNodes.length-1),!0)}reset(){return this.resetWorkerNodeKeyProperties(),this.workerNodeVirtualTaskExecutionTime=0,!0}update(){return!0}}const X=()=>{const e=o.cpus();let t;e.every((e=>null==e.speed||0===e.speed))&&(t=(()=>{const e=performance.now(),t=performance.now()-e;return Math.trunc(15e7/t/1e3)})());let r=0;for(const s of e){null!=s.speed&&0!==s.speed||(s.speed=e.find((e=>null!=e.speed&&0!==e.speed))?.speed??t??2e3);const i=s.speed.toString().length-1;r+=1/(s.speed/Math.pow(10,i))*Math.pow(10,i)}return Math.round(r/e.length)},Z=(e,t)=>{t=t??X();const r={};for(let s=0;s((t=structuredClone(t??{})).weights=t.weights??Z(e.info.maxSize),{elu:{median:!1},runTime:{median:!1},waitTime:{median:!1},...t}),te=(e,t)=>{e.average&&t&&(e.average=!1,e.median=t),e.median&&!t&&(e.average=!0,e.median=t)},re=e=>{const t=Array.from(e,(([e,t])=>t.strategyPolicy));return{dynamicWorkerReady:t.some((e=>e.dynamicWorkerReady)),dynamicWorkerUsage:t.some((e=>e.dynamicWorkerUsage))}},se=e=>{const t=Array.from(e,(([e,t])=>t.taskStatisticsRequirements));return{elu:{aggregate:t.some((e=>e.elu.aggregate)),average:t.some((e=>e.elu.average)),median:t.some((e=>e.elu.median))},runTime:{aggregate:t.some((e=>e.runTime.aggregate)),average:t.some((e=>e.runTime.average)),median:t.some((e=>e.runTime.median))},waitTime:{aggregate:t.some((e=>e.waitTime.aggregate)),average:t.some((e=>e.waitTime.average)),median:t.some((e=>e.waitTime.median))}}};class ie{pool;defaultWorkerChoiceStrategy;retries;workerChoiceStrategies;workerChoiceStrategiesPolicy;workerChoiceStrategiesTaskStatisticsRequirements;retriesCount;constructor(e,t=[v.ROUND_ROBIN],r){this.pool=e,this.execute=this.execute.bind(this),this.defaultWorkerChoiceStrategy=t[0],this.workerChoiceStrategies=new Map;for(const e of t)this.addWorkerChoiceStrategy(e,this.pool,r);this.workerChoiceStrategiesPolicy=re(this.workerChoiceStrategies),this.workerChoiceStrategiesTaskStatisticsRequirements=se(this.workerChoiceStrategies),this.retriesCount=0,this.retries=((e,t)=>e.info.maxSize+Object.keys(t?.weights??Z(e.info.maxSize)).length)(this.pool,r)}addWorkerChoiceStrategy(e,t,r){return this.workerChoiceStrategies.has(e)?this.workerChoiceStrategies:this.workerChoiceStrategies.set(e,((e,t,r,s)=>{switch(e){case v.FAIR_SHARE:return new(V.bind(r))(t,s);case v.INTERLEAVED_WEIGHTED_ROUND_ROBIN:return new(H.bind(r))(t,s);case v.LEAST_BUSY:return new(j.bind(r))(t,s);case v.LEAST_ELU:return new($.bind(r))(t,s);case v.LEAST_USED:return new(Y.bind(r))(t,s);case v.ROUND_ROBIN:return new(G.bind(r))(t,s);case v.WEIGHTED_ROUND_ROBIN:return new(J.bind(r))(t,s);default:throw new Error(`Worker choice strategy '${e}' is not valid`)}})(e,t,this,r))}executeStrategy(e){let t,r=0,s=0;do{t=e.choose(),null==t&&r>0&&(++s,++this.retriesCount),++r}while(null==t&&sr.remove(e))).every((e=>e))}setDefaultWorkerChoiceStrategy(e,t){e!==this.defaultWorkerChoiceStrategy&&(this.defaultWorkerChoiceStrategy=e,this.addWorkerChoiceStrategy(e,this.pool,t))}setOptions(e){for(const t of this.workerChoiceStrategies.values())t.setOptions(e)}syncWorkerChoiceStrategies(e,t){for(const t of this.workerChoiceStrategies.keys())e.has(t)||this.removeWorkerChoiceStrategy(t);for(const r of e)this.workerChoiceStrategies.has(r)||this.addWorkerChoiceStrategy(r,this.pool,t);this.workerChoiceStrategiesPolicy=re(this.workerChoiceStrategies),this.workerChoiceStrategiesTaskStatisticsRequirements=se(this.workerChoiceStrategies)}update(e){return Array.from(this.workerChoiceStrategies,(([t,r])=>r.update(e))).every((e=>e))}}class oe{items;maxArrayIdx;readIdx;writeIdx;size;constructor(e=2048){this.checkSize(e),this.readIdx=0,this.writeIdx=0,this.maxArrayIdx=e-1,this.size=0,this.items=new Float32Array(e).fill(-1)}checkSize(e){if(!Number.isSafeInteger(e))throw new TypeError(`Invalid circular buffer size: '${e.toString()}' is not an integer`);if(e<0)throw new RangeError(`Invalid circular buffer size: ${e.toString()} < 0`)}empty(){return 0===this.size}full(){return this.size===this.items.length}get(){const e=this.items[this.readIdx];if(-1!==e)return this.items[this.readIdx]=-1,this.readIdx=this.readIdx===this.maxArrayIdx?0:this.readIdx+1,--this.size,e}put(e){this.items[this.writeIdx]=e,this.writeIdx=this.writeIdx===this.maxArrayIdx?0:this.writeIdx+1,this.size-1!==e)))}}class ne{start;capacity;nodeArray;size;constructor(e=2048){this.checkSize(e),this.capacity=e,this.nodeArray=new Array(this.capacity),this.clear()}checkSize(e){if(!Number.isSafeInteger(e))throw new TypeError(`Invalid fixed queue size: '${e.toString()}' is not an integer`);if(e<0)throw new RangeError(`Invalid fixed queue size: ${e.toString()} < 0`)}clear(){this.start=0,this.size=0}dequeue(){if(this.empty())return;const e=this.start;return--this.size,++this.start,this.start===this.capacity&&(this.start=0),this.nodeArray[e].data}empty(){return 0===this.size}full(){return this.size===this.capacity}get(e){if(!(this.empty()||e>=this.size))return(e+=this.start)>=this.capacity&&(e-=this.capacity),this.nodeArray[e].data}[Symbol.iterator](){let e=this.start,t=0;return{next:()=>{if(t>=this.size)return{done:!0,value:void 0};const r=this.nodeArray[e].data;return++e,++t,e===this.capacity&&(e=0),{done:!1,value:r}}}}}class ae extends ne{enqueue(e,t){if(this.full())throw new Error("Fixed priority queue is full");t=t??0;let r=!1,s=this.start;for(let i=0;it){this.nodeArray.splice(s,0,{data:e,priority:t}),this.nodeArray.length=this.capacity,r=!0;break}++s,s===this.capacity&&(s=0)}if(!r){let r=this.start+this.size;r>=this.capacity&&(r-=this.capacity),this.nodeArray[r]={data:e,priority:t}}return++this.size}}class ue extends ne{enqueue(e,t){if(this.full())throw new Error("Fixed queue is full");let r=this.start+this.size;return r>=this.capacity&&(r-=this.capacity),this.nodeArray[r]={data:e,priority:t??0},++this.size}}class he{bucketSize;head;priorityEnabled;tail;maxSize;constructor(e=2048,t=!1){if(!Number.isSafeInteger(e))throw new TypeError(`Invalid bucket size: '${e.toString()}' is not an integer`);if(e<0)throw new RangeError(`Invalid bucket size: ${e.toString()} < 0`);this.bucketSize=e,this.priorityEnabled=t,this.clear()}getPriorityQueueNode(e){let t;return t=this.priorityEnabled?new ae(this.bucketSize):new ue(this.bucketSize),null!=e&&(t.nodeArray=e),t}clear(){this.head=this.tail=this.getPriorityQueueNode(),this.maxSize=0}dequeue(e){let t=this.tail,r=!1;if(null!=e&&e>0){let s=1;for(;null!=t&&s!==e;)++s,t=t.next;r=t!==this.tail}const s=t.dequeue();if(t.empty())if(r||null==t.next){if(r){let e=this.tail;for(;null!=e;){if(e.next===t&&null!=t.next){e.next=t.next,delete t.next;break}if(e.next===t&&null==t.next){delete e.next,this.head=e;break}e=e.next}}}else this.tail=t.next,delete t.next;return s}enqueue(e,t){this.head.full()&&(this.head=this.head.next=this.getPriorityQueueNode()),this.head.enqueue(e,t);const r=this.size;return r>this.maxSize&&(this.maxSize=r),r}[Symbol.iterator](){let e=0,t=this.tail;return{next:()=>{const r=t.get(e);return null==r?{done:!0,value:void 0}:(++e,e===t.capacity&&null!=t.next&&(t=t.next,e=0),{done:!1,value:r})}}}get buckets(){return Math.trunc(this.size/this.bucketSize)}get enablePriority(){return this.priorityEnabled}set enablePriority(e){if(this.priorityEnabled===e)return;let t,r,s;this.priorityEnabled=e;let i=this.tail,o=0;for(;null!=i;){const e=this.getPriorityQueueNode(i.nodeArray);0===o&&(r=e),null!=s&&(s.next=e),s=e,null==i.next&&(t=e),++o,i=i.next}this.head=t,this.tail=r}get size(){let e=this.tail,t=0;for(;null!=e;)t+=e.size,e=e.next;return t}}class ke extends a.EventEmitter{setBackPressureFlag;taskFunctionsUsage;tasksQueue;info;messageChannel;strategyData;tasksQueueBackPressureSize;usage;worker;constructor(t,r,i){super(),((e,t,r)=>{if(null==e)throw new TypeError("Cannot construct a worker node without a worker type");if(!Object.values(I).includes(e))throw new TypeError(`Cannot construct a worker node with an invalid worker type '${e}'`);if(F(t),null==r)throw new TypeError("Cannot construct a worker node without worker node options");if(!y(r))throw new TypeError("Cannot construct a worker node with invalid worker node options: must be a plain object");if(null==r.tasksQueueBackPressureSize)throw new TypeError("Cannot construct a worker node without a tasks queue back pressure size option");if(!Number.isSafeInteger(r.tasksQueueBackPressureSize))throw new TypeError("Cannot construct a worker node with a tasks queue back pressure size option that is not an integer");if(r.tasksQueueBackPressureSize<=0)throw new RangeError("Cannot construct a worker node with a tasks queue back pressure size option that is not a positive integer");if(null==r.tasksQueueBucketSize)throw new TypeError("Cannot construct a worker node without a tasks queue bucket size option");if(!Number.isSafeInteger(r.tasksQueueBucketSize))throw new TypeError("Cannot construct a worker node with a tasks queue bucket size option that is not an integer");if(r.tasksQueueBucketSize<=0)throw new RangeError("Cannot construct a worker node with a tasks queue bucket size option that is not a positive integer");if(null==r.tasksQueuePriority)throw new TypeError("Cannot construct a worker node without a tasks queue priority option");if("boolean"!=typeof r.tasksQueuePriority)throw new TypeError("Cannot construct a worker node with a tasks queue priority option that is not a boolean")})(t,r,i),this.worker=((t,r,i)=>{switch(t){case I.cluster:return e.fork(i.env);case I.thread:return new s.Worker(r,{env:s.SHARE_ENV,...i.workerOptions});default:throw new Error(`Unknown worker type '${t}'`)}})(t,r,{env:i.env,workerOptions:i.workerOptions}),this.info=this.initWorkerInfo(this.worker),this.usage=this.initWorkerUsage(),this.info.type===I.thread&&(this.messageChannel=new s.MessageChannel),this.tasksQueueBackPressureSize=i.tasksQueueBackPressureSize,this.tasksQueue=new he(i.tasksQueueBucketSize,i.tasksQueuePriority),this.setBackPressureFlag=!1,this.taskFunctionsUsage=new Map}closeMessageChannel(){null!=this.messageChannel&&(this.messageChannel.port1.unref(),this.messageChannel.port2.unref(),this.messageChannel.port1.close(),this.messageChannel.port2.close(),delete this.messageChannel)}hasBackPressure(){return this.tasksQueue.size>=this.tasksQueueBackPressureSize}initTaskFunctionWorkerUsage(e){const t=()=>{let t=0;for(const r of this.tasksQueue)(r.name===l&&e===this.info.taskFunctionsProperties[1].name||r.name!==l&&e===r.name)&&++t;return t};return{elu:{active:{history:new oe(b)},idle:{history:new oe(b)}},runTime:{history:new oe(b)},tasks:{executed:0,executing:0,failed:0,get queued(){return t()},sequentiallyStolen:0,stolen:0},waitTime:{history:new oe(b)}}}initWorkerInfo(e){return{backPressure:!1,backPressureStealing:!1,continuousStealing:!1,dynamic:!1,id:D(e),ready:!1,stealing:!1,stolen:!1,type:U(e)}}initWorkerUsage(){const e=()=>this.tasksQueue.size,t=()=>this.tasksQueue.maxSize;return{elu:{active:{history:new oe(b)},idle:{history:new oe(b)}},runTime:{history:new oe(b)},tasks:{executed:0,executing:0,failed:0,get maxQueued(){return t()},get queued(){return e()},sequentiallyStolen:0,stolen:0},waitTime:{history:new oe(b)}}}clearTasksQueue(){this.tasksQueue.clear()}deleteTaskFunctionWorkerUsage(e){return this.taskFunctionsUsage.delete(e)}dequeueLastPrioritizedTask(){return this.dequeueTask(this.tasksQueue.buckets+1)}dequeueTask(e){const t=this.tasksQueue.dequeue(e);return this.setBackPressureFlag||this.hasBackPressure()||!this.info.backPressure||(this.setBackPressureFlag=!0,this.info.backPressure=!1,this.setBackPressureFlag=!1),t}enqueueTask(e){const t=this.tasksQueue.enqueue(e,e.priority);return this.setBackPressureFlag||!this.hasBackPressure()||this.info.backPressure||(this.setBackPressureFlag=!0,this.info.backPressure=!0,this.emit("backPressure",{workerId:this.info.id}),this.setBackPressureFlag=!1),t}getTaskFunctionWorkerUsage(e){if(!Array.isArray(this.info.taskFunctionsProperties))throw new Error(`Cannot get task function worker usage for task function name '${e}' when task function properties list is not yet defined`);if(Array.isArray(this.info.taskFunctionsProperties)&&this.info.taskFunctionsProperties.length<3)throw new Error(`Cannot get task function worker usage for task function name '${e}' when task function properties list has less than 3 elements`);return e===l&&(e=this.info.taskFunctionsProperties[1].name),this.taskFunctionsUsage.has(e)||this.taskFunctionsUsage.set(e,this.initTaskFunctionWorkerUsage(e)),this.taskFunctionsUsage.get(e)}registerOnceWorkerEventHandler(e,t){this.worker.once(e,t)}registerWorkerEventHandler(e,t){this.worker.on(e,t)}setTasksQueuePriority(e){this.tasksQueue.enablePriority=e}tasksQueueSize(){return this.tasksQueue.size}async terminate(){const e=new Promise((e=>{this.registerOnceWorkerEventHandler("exit",(()=>{e()}))}));switch(this.closeMessageChannel(),this.removeAllListeners(),this.info.type){case I.cluster:this.registerOnceWorkerEventHandler("disconnect",(()=>{this.worker.kill?.()})),this.worker.disconnect?.();break;case I.thread:this.worker.unref?.(),await(this.worker.terminate?.())}await e}}class ce{minimumNumberOfWorkers;filePath;opts;maximumNumberOfWorkers;promiseResponseMap=new Map;workerChoiceStrategiesContext;workerMessageListener=e=>{this.checkMessageWorkerId(e);const{ready:t,taskFunctionsProperties:r,taskId:s,workerId:i}=e;if(null!=t&&null!=r)this.handleWorkerReadyResponse(e);else if(null!=r){const e=this.getWorkerNodeKeyByWorkerId(i),t=this.getWorkerInfo(e);null!=t&&(t.taskFunctionsProperties=r,this.sendStatisticsMessageToWorker(e),this.setTasksQueuePriority(e))}else null!=s&&this.handleTaskExecutionResponse(e)};backPressureEventEmitted;busyEventEmitted;destroying;getTaskFunctionWorkerChoiceStrategy=e=>{e=e??l;const t=this.listTaskFunctionsProperties();return e===l&&(e=t[1]?.name),t.find((t=>t.name===e))?.strategy};getWorkerChoiceStrategies=()=>new Set([this.opts.workerChoiceStrategy,...this.listTaskFunctionsProperties().map((e=>e.strategy)).filter((e=>null!=e))]);getWorkerNodeTaskFunctionPriority=(e,t)=>{const r=this.getWorkerInfo(e);if(null!=r)return(t=t??l)===l&&(t=r.taskFunctionsProperties?.[1]?.name),r.taskFunctionsProperties?.find((e=>e.name===t))?.priority};getWorkerNodeTaskFunctionWorkerChoiceStrategy=(e,t)=>{const r=this.getWorkerInfo(e);if(null!=r)return(t=t??l)===l&&(t=r.taskFunctionsProperties?.[1]?.name),r.taskFunctionsProperties?.find((e=>e.name===t))?.strategy};handleWorkerNodeBackPressureEvent=e=>{if(this.cannotStealTask()||this.backPressure||this.isStealingRatioReached())return;if(this.opts.tasksQueueOptions.size<=1)return;const{workerId:t}=e,r=this.workerNodes[this.getWorkerNodeKeyByWorkerId(t)],s=this.workerNodes.slice().sort(((e,t)=>e.usage.tasks.queued-t.usage.tasks.queued));for(const[e,i]of s.entries()){if(0===r.usage.tasks.queued)break;i.info.id!==t&&!i.info.backPressureStealing&&i.usage.tasks.queued{const{workerNodeKey:r}=e;if(null==r)throw new Error("WorkerNode event detail 'workerNodeKey' property must be defined");const s=this.workerNodes[r];if(null==s)return;if(!s.info.continuousStealing&&(this.cannotStealTask()||this.isStealingRatioReached()))return;const i=s.usage.tasks;if(s.info.continuousStealing&&!this.isWorkerNodeIdle(r))return s.info.continuousStealing=!1,void(i.sequentiallyStolen>0&&this.resetTaskSequentiallyStolenStatisticsWorkerUsage(r,t?.name));s.info.continuousStealing=!0;const o=this.workerNodeStealTask(r);this.updateTaskSequentiallyStolenStatisticsWorkerUsage(r,o?.name,t?.name),(async e=>{await new Promise((t=>{setTimeout(t,e)}))})(((e=0,t=100)=>{const r=Math.pow(2,e)*t;return r+.2*r*N()})(i.sequentiallyStolen)).then((()=>{this.handleWorkerNodeIdleEvent(e,o)})).catch((e=>{this.emitter?.emit(d.error,e)}))};isStealingRatioReached=()=>0===this.opts.tasksQueueOptions?.tasksStealingRatio||(this.info.stealingWorkerNodes??0)>Math.ceil(this.workerNodes.length*this.opts.tasksQueueOptions.tasksStealingRatio);readyEventEmitted;started;starting;startingMinimumNumberOfWorkers;startTimestamp;stealTask=(e,t)=>{const r=this.workerNodes[t];if(null==r)return;if(!e.info.ready||e.info.stolen||e.info.stealing||!r.info.ready||r.info.stolen||r.info.stealing)return;r.info.stealing=!0,e.info.stolen=!0;const s=e.dequeueLastPrioritizedTask();return e.info.stolen=!1,r.info.stealing=!1,this.handleTask(t,s),this.updateTaskStolenStatisticsWorkerUsage(t,s.name),s};taskFunctions;workerNodeStealTask=e=>{const t=this.workerNodes.slice().sort(((e,t)=>t.usage.tasks.queued-e.usage.tasks.queued)).find(((t,r)=>r!==e&&t.usage.tasks.queued>0));if(null!=t)return this.stealTask(t,e)};emitter;workerNodes=[];constructor(e,t,r,s){if(this.minimumNumberOfWorkers=e,this.filePath=t,this.opts=r,this.maximumNumberOfWorkers=s,!this.isMain())throw new Error("Cannot start a pool from a worker with the same type as the pool");this.checkPoolType(),F(this.filePath),this.checkMinimumNumberOfWorkers(this.minimumNumberOfWorkers),this.checkPoolOptions(this.opts),this.chooseWorkerNode=this.chooseWorkerNode.bind(this),this.executeTask=this.executeTask.bind(this),this.enqueueTask=this.enqueueTask.bind(this),!0===this.opts.enableEvents&&this.initEventEmitter(),this.workerChoiceStrategiesContext=new ie(this,[this.opts.workerChoiceStrategy],this.opts.workerChoiceStrategyOptions),this.setupHook(),this.taskFunctions=new Map,this.started=!1,this.starting=!1,this.destroying=!1,this.readyEventEmitted=!1,this.busyEventEmitted=!1,this.backPressureEventEmitted=!1,this.startingMinimumNumberOfWorkers=!1,!0===this.opts.startWorkers&&this.start()}afterTaskExecutionHook(e,t){let r=!1;if(null!=this.workerNodes[e]?.usage){const s=this.workerNodes[e].usage;K(s,t),Q(this.workerChoiceStrategiesContext,s,t),B(this.workerChoiceStrategiesContext,s,t),r=!0}if(this.shallUpdateTaskFunctionWorkerUsage(e)&&null!=t.taskPerformance?.name&&null!=this.workerNodes[e].getTaskFunctionWorkerUsage(t.taskPerformance.name)){const s=this.workerNodes[e].getTaskFunctionWorkerUsage(t.taskPerformance.name);K(s,t),Q(this.workerChoiceStrategiesContext,s,t),B(this.workerChoiceStrategiesContext,s,t),r=!0}r&&this.workerChoiceStrategiesContext?.update(e)}afterWorkerNodeSetup(e){this.registerWorkerMessageListener(e,this.workerMessageListener),this.sendStartupMessageToWorker(e),this.sendStatisticsMessageToWorker(e),!0===this.opts.enableTasksQueue&&(!0===this.opts.tasksQueueOptions?.taskStealing&&this.workerNodes[e].on("idle",this.handleWorkerNodeIdleEvent),!0===this.opts.tasksQueueOptions?.tasksStealingOnBackPressure&&this.workerNodes[e].on("backPressure",this.handleWorkerNodeBackPressureEvent))}beforeTaskExecutionHook(e,t){if(null!=this.workerNodes[e]?.usage){const r=this.workerNodes[e].usage;++r.tasks.executing,M(this.workerChoiceStrategiesContext,r,t)}if(this.shallUpdateTaskFunctionWorkerUsage(e)&&null!=this.workerNodes[e].getTaskFunctionWorkerUsage(t.name)){const r=this.workerNodes[e].getTaskFunctionWorkerUsage(t.name);++r.tasks.executing,M(this.workerChoiceStrategiesContext,r,t)}}createAndSetupDynamicWorkerNode(){const e=this.createAndSetupWorkerNode();if(this.registerWorkerMessageListener(e,(e=>{this.checkMessageWorkerId(e);const t=this.getWorkerNodeKeyByWorkerId(e.workerId);(f(_.HARD,e.kill)||f(_.SOFT,e.kill)&&this.isWorkerNodeIdle(t)&&!this.isWorkerNodeStealing(t))&&(this.flagWorkerNodeAsNotReady(t),this.destroyWorkerNode(t).catch((e=>{this.emitter?.emit(d.error,e)})))})),this.sendToWorker(e,{checkActive:!0}),this.taskFunctions.size>0)for(const[t,r]of this.taskFunctions)this.sendTaskFunctionOperationToWorker(e,{taskFunction:r.taskFunction.toString(),taskFunctionOperation:"add",taskFunctionProperties:S(t,r)}).catch((e=>{this.emitter?.emit(d.error,e)}));const t=this.workerNodes[e];return t.info.dynamic=!0,!0===this.workerChoiceStrategiesContext?.getPolicy().dynamicWorkerReady&&(t.info.ready=!0),this.initWorkerNodeUsage(t),this.checkAndEmitDynamicWorkerCreationEvents(),e}createAndSetupWorkerNode(){const e=this.createWorkerNode();e.registerWorkerEventHandler("online",this.opts.onlineHandler??m),e.registerWorkerEventHandler("message",this.opts.messageHandler??m),e.registerWorkerEventHandler("error",this.opts.errorHandler??m),e.registerOnceWorkerEventHandler("error",(t=>{e.info.ready=!1,this.emitter?.emit(d.error,t),this.started&&!this.destroying&&!0===this.opts.restartWorkerOnError&&(e.info.dynamic?this.createAndSetupDynamicWorkerNode():this.startingMinimumNumberOfWorkers||this.startMinimumNumberOfWorkers(!0)),this.started&&!this.destroying&&!0===this.opts.enableTasksQueue&&this.redistributeQueuedTasks(this.workerNodes.indexOf(e)),e?.terminate().catch((e=>{this.emitter?.emit(d.error,e)}))})),e.registerWorkerEventHandler("exit",this.opts.exitHandler??m),e.registerOnceWorkerEventHandler("exit",(()=>{this.removeWorkerNode(e),!this.started||this.startingMinimumNumberOfWorkers||this.destroying||this.startMinimumNumberOfWorkers(!0)}));const t=this.addWorkerNode(e);return this.afterWorkerNodeSetup(t),t}async destroyWorkerNode(e){this.flagWorkerNodeAsNotReady(e);const t=this.flushTasksQueue(e),r=this.workerNodes[e];await(async(e,t,r,s)=>await new Promise((i=>{let o=0;if(0!==r){switch(t){case"backPressure":case"idle":case"taskFinished":e.on(t,(()=>{++o,o===r&&i(o)}));break;default:throw new Error("Invalid worker node event")}s>=0&&setTimeout((()=>{i(o)}),s)}else i(o)})))(r,"taskFinished",t,this.opts.tasksQueueOptions?.tasksFinishedTimeout??P(this.maximumNumberOfWorkers??this.minimumNumberOfWorkers).tasksFinishedTimeout),await this.sendKillMessageToWorker(e),await r.terminate()}flagWorkerNodeAsNotReady(e){const t=this.getWorkerInfo(e);null!=t&&(t.ready=!1)}flushTasksQueue(e){let t=0;for(;this.tasksQueueSize(e)>0;)this.executeTask(e,this.dequeueTask(e)),++t;return this.workerNodes[e].clearTasksQueue(),t}getWorkerInfo(e){return this.workerNodes[e]?.info}internalBackPressure(){return this.workerNodes.reduce(((e,t,r)=>this.isWorkerNodeBackPressured(r)?e+1:e),0)===this.workerNodes.length}internalBusy(){return this.workerNodes.reduce(((e,t,r)=>this.isWorkerNodeBusy(r)?e+1:e),0)===this.workerNodes.length}setupHook(){}addWorkerNode(e){this.workerNodes.push(e);const t=this.workerNodes.indexOf(e);if(-1===t)throw new Error("Worker added not found in worker nodes");return t}buildTasksQueueOptions(e){return{...P(this.maximumNumberOfWorkers??this.minimumNumberOfWorkers),...this.opts.tasksQueueOptions,...e}}cannotStealTask(){return this.workerNodes.length<=1||0===this.info.queuedTasks}checkAndEmitReadyEvent(){null!=this.emitter&&!this.readyEventEmitted&&this.ready&&(this.emitter.emit(d.ready,this.info),this.readyEventEmitted=!0)}checkAndEmitTaskDequeuingEvents(){null!=this.emitter&&this.backPressureEventEmitted&&!this.backPressure&&(this.emitter.emit(d.backPressureEnd,this.info),this.backPressureEventEmitted=!1)}checkAndEmitTaskExecutionEvents(){null!=this.emitter&&!this.busyEventEmitted&&this.busy&&(this.emitter.emit(d.busy,this.info),this.busyEventEmitted=!0)}checkAndEmitTaskExecutionFinishedEvents(){null!=this.emitter&&this.busyEventEmitted&&!this.busy&&(this.emitter.emit(d.busyEnd,this.info),this.busyEventEmitted=!1)}checkAndEmitTaskQueuingEvents(){null!=this.emitter&&!this.backPressureEventEmitted&&this.backPressure&&(this.emitter.emit(d.backPressure,this.info),this.backPressureEventEmitted=!0)}checkMessageWorkerId(e){if(null==e.workerId)throw new Error("Worker message received without worker id");if(-1===this.getWorkerNodeKeyByWorkerId(e.workerId))throw new Error(`Worker message received from unknown worker '${e.workerId.toString()}'`)}checkMinimumNumberOfWorkers(e){if(null==e)throw new Error("Cannot instantiate a pool without specifying the number of workers");if(!Number.isSafeInteger(e))throw new TypeError("Cannot instantiate a pool with a non safe integer number of workers");if(e<0)throw new RangeError("Cannot instantiate a pool with a negative number of workers");if(this.type===c.fixed&&0===e)throw new RangeError("Cannot instantiate a fixed pool with zero worker")}checkPoolOptions(e){if(!y(e))throw new TypeError("Invalid pool options: must be a plain object");this.opts.startWorkers=e.startWorkers??!0,A(e.workerChoiceStrategy),this.opts.workerChoiceStrategy=e.workerChoiceStrategy??v.ROUND_ROBIN,this.checkValidWorkerChoiceStrategyOptions(e.workerChoiceStrategyOptions),null!=e.workerChoiceStrategyOptions&&(this.opts.workerChoiceStrategyOptions=e.workerChoiceStrategyOptions),this.opts.restartWorkerOnError=e.restartWorkerOnError??!0,this.opts.enableEvents=e.enableEvents??!0,this.opts.enableTasksQueue=e.enableTasksQueue??!1,this.opts.enableTasksQueue&&(q(e.tasksQueueOptions),this.opts.tasksQueueOptions=this.buildTasksQueueOptions(e.tasksQueueOptions))}checkPoolType(){if(this.type===c.fixed&&null!=this.maximumNumberOfWorkers)throw new Error("Cannot instantiate a fixed pool with a maximum number of workers specified at initialization")}checkValidWorkerChoiceStrategyOptions(e){if(null!=e&&!y(e))throw new TypeError("Invalid worker choice strategy options: must be a plain object");if(null!=e?.weights&&Object.keys(e.weights).length!==(this.maximumNumberOfWorkers??this.minimumNumberOfWorkers))throw new Error("Invalid worker choice strategy options: must have a weight for each worker node");if(null!=e?.measurement&&!Object.values(x).includes(e.measurement))throw new Error(`Invalid worker choice strategy options: invalid measurement '${e.measurement}'`)}chooseWorkerNode(e){if(this.shallCreateDynamicWorker()){const e=this.createAndSetupDynamicWorkerNode();if(!0===this.workerChoiceStrategiesContext?.getPolicy().dynamicWorkerUsage)return e}return this.workerChoiceStrategiesContext.execute(this.getTaskFunctionWorkerChoiceStrategy(e))}createWorkerNode(){const e=new ke(this.worker,this.filePath,{env:this.opts.env,tasksQueueBackPressureSize:this.opts.tasksQueueOptions?.size??P(this.maximumNumberOfWorkers??this.minimumNumberOfWorkers).size,tasksQueueBucketSize:2048,tasksQueuePriority:this.getTasksQueuePriority(),workerOptions:this.opts.workerOptions});return this.starting&&(e.info.ready=!0),e}dequeueTask(e){const t=this.workerNodes[e].dequeueTask();return this.checkAndEmitTaskDequeuingEvents(),t}enqueueTask(e,t){const r=this.workerNodes[e].enqueueTask(t);return this.checkAndEmitTaskQueuingEvents(),r}executeTask(e,t){this.beforeTaskExecutionHook(e,t),this.sendToWorker(e,t,t.transferList),this.checkAndEmitTaskExecutionEvents()}flushTasksQueues(){for(const e of this.workerNodes.keys())this.flushTasksQueue(e)}getTasksQueuePriority(){return this.listTaskFunctionsProperties().some((e=>null!=e.priority))}getWorkerNodeKeyByWorkerId(e){return this.workerNodes.findIndex((t=>t.info.id===e))}handleTask(e,t){this.shallExecuteTask(e)?this.executeTask(e,t):this.enqueueTask(e,t)}handleTaskExecutionResponse(e){const{data:t,taskId:r,workerError:s}=e,i=this.promiseResponseMap.get(r);if(null!=i){const{asyncResource:o,reject:n,resolve:a,workerNodeKey:u}=i,h=this.workerNodes[u];if(null!=s){this.emitter?.emit(d.taskError,s);const e=this.handleWorkerError(s);null!=o?o.runInAsyncScope(n,this.emitter,e):n(e)}else null!=o?o.runInAsyncScope(a,this.emitter,t):a(t);o?.emitDestroy(),this.afterTaskExecutionHook(u,e),queueMicrotask((()=>{this.checkAndEmitTaskExecutionFinishedEvents(),h?.emit("taskFinished",r),this.promiseResponseMap.delete(r),!0!==this.opts.enableTasksQueue||this.destroying||(!this.isWorkerNodeBusy(u)&&this.tasksQueueSize(u)>0&&this.executeTask(u,this.dequeueTask(u)),this.isWorkerNodeIdle(u)&&h.emit("idle",{workerNodeKey:u})),this.shallCreateDynamicWorker()&&this.createAndSetupDynamicWorkerNode()}))}}handleWorkerError(e){if(null!=e.error)return e.error;const t=new Error(e.message);return t.stack=e.stack,t}handleWorkerReadyResponse(e){const{ready:t,taskFunctionsProperties:r,workerId:s}=e;if(null==t||!t)throw new Error(`Worker ${s?.toString()} failed to initialize`);const i=this.getWorkerNodeKeyByWorkerId(s),o=this.workerNodes[i];o.info.ready=t,o.info.taskFunctionsProperties=r,this.sendStatisticsMessageToWorker(i),this.setTasksQueuePriority(i),this.checkAndEmitReadyEvent()}initEventEmitter(){this.emitter=new a.EventEmitterAsyncResource({name:`poolifier:${this.type}-${this.worker}-pool`})}initWorkerNodeUsage(e){!0===this.workerChoiceStrategiesContext?.getTaskStatisticsRequirements().runTime.aggregate&&(e.usage.runTime.aggregate=W(...this.workerNodes.map((e=>e.usage.runTime.aggregate??Number.POSITIVE_INFINITY)))),!0===this.workerChoiceStrategiesContext?.getTaskStatisticsRequirements().waitTime.aggregate&&(e.usage.waitTime.aggregate=W(...this.workerNodes.map((e=>e.usage.waitTime.aggregate??Number.POSITIVE_INFINITY)))),!0===this.workerChoiceStrategiesContext?.getTaskStatisticsRequirements().elu.aggregate&&(e.usage.elu.active.aggregate=W(...this.workerNodes.map((e=>e.usage.elu.active.aggregate??Number.POSITIVE_INFINITY))))}async internalExecute(e,t,r){return await new Promise(((s,o)=>{const a=u.performance.now(),h=this.chooseWorkerNode(t),k={data:e??{},name:t??l,priority:this.getWorkerNodeTaskFunctionPriority(h,t),strategy:this.getWorkerNodeTaskFunctionWorkerChoiceStrategy(h,t),taskId:i.randomUUID(),timestamp:a,transferList:r};!1===this.opts.enableTasksQueue||!0===this.opts.enableTasksQueue&&this.shallExecuteTask(h)?this.executeTask(h,k):this.enqueueTask(h,k),queueMicrotask((()=>{this.promiseResponseMap.set(k.taskId,{reject:o,resolve:s,workerNodeKey:h,...null!=this.emitter&&{asyncResource:new n.AsyncResource("poolifier:task",{requireManualDestroy:!0,triggerAsyncId:this.emitter.asyncId})}})}))}))}isWorkerNodeBackPressured(e){const t=this.workerNodes[e];return t.info.ready&&t.info.backPressure}isWorkerNodeBusy(e){const t=this.workerNodes[e];return!0===this.opts.enableTasksQueue?t.info.ready&&t.usage.tasks.executing>=this.opts.tasksQueueOptions.concurrency:t.info.ready&&t.usage.tasks.executing>0}isWorkerNodeIdle(e){const t=this.workerNodes[e];return!0===this.opts.enableTasksQueue?t.info.ready&&0===t.usage.tasks.executing&&0===this.tasksQueueSize(e):t.info.ready&&0===t.usage.tasks.executing}isWorkerNodeStealing(e){const t=this.workerNodes[e];return t.info.ready&&(t.info.continuousStealing||t.info.backPressureStealing)}redistributeQueuedTasks(e){if(-1!==e&&!this.cannotStealTask())for(;this.tasksQueueSize(e)>0;){const t=this.workerNodes.reduce(((t,r,s,i)=>e!==s&&r.info.ready&&r.usage.tasks.queued{if(null==this.workerNodes[e])return void t();this.registerWorkerMessageListener(e,(e=>{this.checkMessageWorkerId(e),"success"===e.kill?t():"failure"===e.kill&&r(new Error(`Kill message handling failed on worker ${e.workerId?.toString()}`))})),this.sendToWorker(e,{kill:!0})}))}sendStatisticsMessageToWorker(e){this.sendToWorker(e,{statistics:{elu:this.workerChoiceStrategiesContext?.getTaskStatisticsRequirements().elu.aggregate??!1,runTime:this.workerChoiceStrategiesContext?.getTaskStatisticsRequirements().runTime.aggregate??!1}})}async sendTaskFunctionOperationToWorker(e,t){return await new Promise(((r,s)=>{const i=t=>{this.checkMessageWorkerId(t);const o=this.getWorkerInfo(e)?.id;null!=t.taskFunctionOperationStatus&&t.workerId===o&&(t.taskFunctionOperationStatus?r(!0):s(new Error(`Task function operation '${t.taskFunctionOperation?.toString()}' failed on worker ${t.workerId?.toString()} with error: '${t.workerError?.message}'`)),this.deregisterWorkerMessageListener(this.getWorkerNodeKeyByWorkerId(t.workerId),i))};this.registerWorkerMessageListener(e,i),this.sendToWorker(e,t)}))}async sendTaskFunctionOperationToWorkers(e){return await new Promise(((t,r)=>{const s=new Array,i=e=>{if(this.checkMessageWorkerId(e),null!=e.taskFunctionOperationStatus&&(s.push(e),s.length===this.workerNodes.length)){if(s.every((e=>!0===e.taskFunctionOperationStatus)))t(!0);else if(s.some((e=>!1===e.taskFunctionOperationStatus))){const t=s.find((e=>!1===e.taskFunctionOperationStatus));r(new Error(`Task function operation '${e.taskFunctionOperation}' failed on worker ${t?.workerId?.toString()} with error: '${t?.workerError?.message}'`))}this.deregisterWorkerMessageListener(this.getWorkerNodeKeyByWorkerId(e.workerId),i)}};for(const t of this.workerNodes.keys())this.registerWorkerMessageListener(t,i),this.sendToWorker(t,e)}))}setTasksQueuePriority(e){this.workerNodes[e].setTasksQueuePriority(this.getTasksQueuePriority())}setTasksQueueSize(e){for(const t of this.workerNodes)t.tasksQueueBackPressureSize=e}setTasksStealingOnBackPressure(){for(const e of this.workerNodes.keys())this.workerNodes[e].on("backPressure",this.handleWorkerNodeBackPressureEvent)}setTaskStealing(){for(const e of this.workerNodes.keys())this.workerNodes[e].on("idle",this.handleWorkerNodeIdleEvent)}shallExecuteTask(e){return 0===this.tasksQueueSize(e)&&this.workerNodes[e].usage.tasks.executing2}startMinimumNumberOfWorkers(e=!1){if(0!==this.minimumNumberOfWorkers){for(this.startingMinimumNumberOfWorkers=!0;this.workerNodes.reduce(((e,t)=>t.info.dynamic?e:e+1),0)0?++e.tasks.sequentiallyStolen:e.tasks.sequentiallyStolen>0&&(e.tasks.sequentiallyStolen=0)}}updateTaskStolenStatisticsWorkerUsage(e,t){const r=this.workerNodes[e];null!=r?.usage&&++r.usage.tasks.stolen,this.shallUpdateTaskFunctionWorkerUsage(e)&&null!=r.getTaskFunctionWorkerUsage(t)&&++r.getTaskFunctionWorkerUsage(t).tasks.stolen}async addTaskFunction(e,t){if("string"!=typeof e)throw new TypeError("name argument must be a string");if("string"==typeof e&&0===e.trim().length)throw new TypeError("name argument must not be an empty string");if("function"==typeof t&&(t={taskFunction:t}),"function"!=typeof t.taskFunction)throw new TypeError("taskFunction property must be a function");R(t.priority),A(t.strategy);const r=await this.sendTaskFunctionOperationToWorkers({taskFunction:t.taskFunction.toString(),taskFunctionOperation:"add",taskFunctionProperties:S(e,t)});this.taskFunctions.set(e,t),this.workerChoiceStrategiesContext?.syncWorkerChoiceStrategies(this.getWorkerChoiceStrategies());for(const e of this.workerNodes.keys())this.sendStatisticsMessageToWorker(e);return r}async destroy(){if(!this.started)throw new Error("Cannot destroy an already destroyed pool");if(this.starting)throw new Error("Cannot destroy an starting pool");if(this.destroying)throw new Error("Cannot destroy an already destroying pool");this.destroying=!0,await Promise.all(this.workerNodes.map((async(e,t)=>{await this.destroyWorkerNode(t)}))),null!=this.emitter&&(this.emitter.emit(d.destroy,this.info),this.emitter.emitDestroy(),this.readyEventEmitted=!1),delete this.startTimestamp,this.destroying=!1,this.started=!1}enableTasksQueue(e,t){!0!==this.opts.enableTasksQueue||e||(this.unsetTaskStealing(),this.unsetTasksStealingOnBackPressure(),this.flushTasksQueues()),this.opts.enableTasksQueue=e,this.setTasksQueueOptions(t)}async execute(e,t,r){if(!this.started)throw new Error("Cannot execute a task on not started pool");if(this.destroying)throw new Error("Cannot execute a task on destroying pool");if(null!=t&&"string"!=typeof t)throw new TypeError("name argument must be a string");if(null!=t&&"string"==typeof t&&0===t.trim().length)throw new TypeError("name argument must not be an empty string");if(null!=r&&!Array.isArray(r))throw new TypeError("transferList argument must be an array");return await this.internalExecute(e,t,r)}hasTaskFunction(e){return this.listTaskFunctionsProperties().some((t=>t.name===e))}listTaskFunctionsProperties(){for(const e of this.workerNodes)if(Array.isArray(e.info.taskFunctionsProperties)&&e.info.taskFunctionsProperties.length>0)return e.info.taskFunctionsProperties;return[]}async mapExecute(e,t,r){if(!this.started)throw new Error("Cannot execute task(s) on not started pool");if(this.destroying)throw new Error("Cannot execute task(s) on destroying pool");if(null==e)throw new TypeError("data argument must be a defined iterable");if("function"!=typeof e[Symbol.iterator])throw new TypeError("data argument must be an iterable");if(null!=t&&"string"!=typeof t)throw new TypeError("name argument must be a string");if(null!=t&&"string"==typeof t&&0===t.trim().length)throw new TypeError("name argument must not be an empty string");if(null!=r&&!Array.isArray(r))throw new TypeError("transferList argument must be an array");return Array.isArray(e)||(e=[...e]),await Promise.all(e.map((e=>this.internalExecute(e,t,r))))}async removeTaskFunction(e){if(!this.taskFunctions.has(e))throw new Error("Cannot remove a task function not handled on the pool side");const t=await this.sendTaskFunctionOperationToWorkers({taskFunctionOperation:"remove",taskFunctionProperties:S(e,this.taskFunctions.get(e))});for(const t of this.workerNodes)t.deleteTaskFunctionWorkerUsage(e);this.taskFunctions.delete(e),this.workerChoiceStrategiesContext?.syncWorkerChoiceStrategies(this.getWorkerChoiceStrategies());for(const e of this.workerNodes.keys())this.sendStatisticsMessageToWorker(e);return t}async setDefaultTaskFunction(e){return await this.sendTaskFunctionOperationToWorkers({taskFunctionOperation:"default",taskFunctionProperties:S(e,this.taskFunctions.get(e))})}setTasksQueueOptions(e){!0===this.opts.enableTasksQueue?(q(e),this.opts.tasksQueueOptions=this.buildTasksQueueOptions(e),this.setTasksQueueSize(this.opts.tasksQueueOptions.size),!0===this.opts.tasksQueueOptions.taskStealing?(this.unsetTaskStealing(),this.setTaskStealing()):this.unsetTaskStealing(),!0===this.opts.tasksQueueOptions.tasksStealingOnBackPressure?(this.unsetTasksStealingOnBackPressure(),this.setTasksStealingOnBackPressure()):this.unsetTasksStealingOnBackPressure()):null!=this.opts.tasksQueueOptions&&delete this.opts.tasksQueueOptions}setWorkerChoiceStrategy(e,t){let r=!1;if(A(e),null!=t&&(r=!this.setWorkerChoiceStrategyOptions(t)),e!==this.opts.workerChoiceStrategy&&(this.opts.workerChoiceStrategy=e,this.workerChoiceStrategiesContext?.setDefaultWorkerChoiceStrategy(this.opts.workerChoiceStrategy,this.opts.workerChoiceStrategyOptions),r=!0),r){this.workerChoiceStrategiesContext?.syncWorkerChoiceStrategies(this.getWorkerChoiceStrategies(),this.opts.workerChoiceStrategyOptions);for(const e of this.workerNodes.keys())this.sendStatisticsMessageToWorker(e)}}setWorkerChoiceStrategyOptions(e){if(this.checkValidWorkerChoiceStrategyOptions(e),null!=e){this.opts.workerChoiceStrategyOptions={...this.opts.workerChoiceStrategyOptions,...e},this.workerChoiceStrategiesContext?.setOptions(this.opts.workerChoiceStrategyOptions),this.workerChoiceStrategiesContext?.syncWorkerChoiceStrategies(this.getWorkerChoiceStrategies(),this.opts.workerChoiceStrategyOptions);for(const e of this.workerNodes.keys())this.sendStatisticsMessageToWorker(e);return!0}return!1}start(){if(this.started)throw new Error("Cannot start an already started pool");if(this.starting)throw new Error("Cannot start an already starting pool");if(this.destroying)throw new Error("Cannot start a destroying pool");this.starting=!0,this.startMinimumNumberOfWorkers(),this.startTimestamp=u.performance.now(),this.starting=!1,this.started=!0}get info(){return{defaultStrategy:this.opts.workerChoiceStrategy,maxSize:this.maximumNumberOfWorkers??this.minimumNumberOfWorkers,minSize:this.minimumNumberOfWorkers,ready:this.ready,started:this.started,strategyRetries:this.workerChoiceStrategiesContext?.retriesCount??0,type:this.type,version:"4.4.5",worker:this.worker,...!0===this.workerChoiceStrategiesContext?.getTaskStatisticsRequirements().runTime.aggregate&&this.workerChoiceStrategiesContext.getTaskStatisticsRequirements().waitTime.aggregate&&{utilization:p(this.utilization)},busyWorkerNodes:this.workerNodes.reduce(((e,t,r)=>this.isWorkerNodeBusy(r)?e+1:e),0),executedTasks:this.workerNodes.reduce(((e,t)=>e+t.usage.tasks.executed),0),executingTasks:this.workerNodes.reduce(((e,t)=>e+t.usage.tasks.executing),0),failedTasks:this.workerNodes.reduce(((e,t)=>e+t.usage.tasks.failed),0),idleWorkerNodes:this.workerNodes.reduce(((e,t,r)=>this.isWorkerNodeIdle(r)?e+1:e),0),workerNodes:this.workerNodes.length,...this.type===c.dynamic&&{dynamicWorkerNodes:this.workerNodes.reduce(((e,t)=>t.info.dynamic?e+1:e),0)},...!0===this.opts.enableTasksQueue&&{backPressure:this.backPressure,backPressureWorkerNodes:this.workerNodes.reduce(((e,t,r)=>this.isWorkerNodeBackPressured(r)?e+1:e),0),maxQueuedTasks:this.workerNodes.reduce(((e,t)=>e+(t.usage.tasks.maxQueued??0)),0),queuedTasks:this.workerNodes.reduce(((e,t)=>e+t.usage.tasks.queued),0),stealingWorkerNodes:this.workerNodes.reduce(((e,t,r)=>this.isWorkerNodeStealing(r)?e+1:e),0),stolenTasks:this.workerNodes.reduce(((e,t)=>e+t.usage.tasks.stolen),0)},...!0===this.workerChoiceStrategiesContext?.getTaskStatisticsRequirements().runTime.aggregate&&{runTime:{maximum:p(E(...this.workerNodes.map((e=>e.usage.runTime.maximum??Number.NEGATIVE_INFINITY)))),minimum:p(W(...this.workerNodes.map((e=>e.usage.runTime.minimum??Number.POSITIVE_INFINITY)))),...this.workerChoiceStrategiesContext.getTaskStatisticsRequirements().runTime.average&&{average:p(g(this.workerNodes.reduce(((e,t)=>e.concat(t.usage.runTime.history.toArray())),[])))},...this.workerChoiceStrategiesContext.getTaskStatisticsRequirements().runTime.median&&{median:p(w(this.workerNodes.reduce(((e,t)=>e.concat(t.usage.runTime.history.toArray())),[])))}}},...!0===this.workerChoiceStrategiesContext?.getTaskStatisticsRequirements().waitTime.aggregate&&{waitTime:{maximum:p(E(...this.workerNodes.map((e=>e.usage.waitTime.maximum??Number.NEGATIVE_INFINITY)))),minimum:p(W(...this.workerNodes.map((e=>e.usage.waitTime.minimum??Number.POSITIVE_INFINITY)))),...this.workerChoiceStrategiesContext.getTaskStatisticsRequirements().waitTime.average&&{average:p(g(this.workerNodes.reduce(((e,t)=>e.concat(t.usage.waitTime.history.toArray())),[])))},...this.workerChoiceStrategiesContext.getTaskStatisticsRequirements().waitTime.median&&{median:p(w(this.workerNodes.reduce(((e,t)=>e.concat(t.usage.waitTime.history.toArray())),[])))}}},...!0===this.workerChoiceStrategiesContext?.getTaskStatisticsRequirements().elu.aggregate&&{elu:{active:{maximum:p(E(...this.workerNodes.map((e=>e.usage.elu.active.maximum??Number.NEGATIVE_INFINITY)))),minimum:p(W(...this.workerNodes.map((e=>e.usage.elu.active.minimum??Number.POSITIVE_INFINITY)))),...this.workerChoiceStrategiesContext.getTaskStatisticsRequirements().elu.average&&{average:p(g(this.workerNodes.reduce(((e,t)=>e.concat(t.usage.elu.active.history.toArray())),[])))},...this.workerChoiceStrategiesContext.getTaskStatisticsRequirements().elu.median&&{median:p(w(this.workerNodes.reduce(((e,t)=>e.concat(t.usage.elu.active.history.toArray())),[])))}},idle:{maximum:p(E(...this.workerNodes.map((e=>e.usage.elu.idle.maximum??Number.NEGATIVE_INFINITY)))),minimum:p(W(...this.workerNodes.map((e=>e.usage.elu.idle.minimum??Number.POSITIVE_INFINITY)))),...this.workerChoiceStrategiesContext.getTaskStatisticsRequirements().elu.average&&{average:p(g(this.workerNodes.reduce(((e,t)=>e.concat(t.usage.elu.idle.history.toArray())),[])))},...this.workerChoiceStrategiesContext.getTaskStatisticsRequirements().elu.median&&{median:p(w(this.workerNodes.reduce(((e,t)=>e.concat(t.usage.elu.idle.history.toArray())),[])))}},utilization:{average:p(g(this.workerNodes.map((e=>e.usage.elu.utilization??0)))),median:p(w(this.workerNodes.map((e=>e.usage.elu.utilization??0))))}}}}}get ready(){return!!this.started&&this.workerNodes.reduce(((e,t)=>!t.info.dynamic&&t.info.ready?e+1:e),0)>=this.minimumNumberOfWorkers}get utilization(){if(null==this.startTimestamp)return 0;const e=(u.performance.now()-this.startTimestamp)*(this.maximumNumberOfWorkers??this.minimumNumberOfWorkers);return(this.workerNodes.reduce(((e,t)=>e+(t.usage.runTime.aggregate??0)),0)+this.workerNodes.reduce(((e,t)=>e+(t.usage.waitTime.aggregate??0)),0))/e}}class de extends ce{constructor(e,t,r={},s){super(e,t,r,s)}checkAndEmitDynamicWorkerCreationEvents(){}checkAndEmitDynamicWorkerDestructionEvents(){}deregisterWorkerMessageListener(e,t){this.workerNodes[e].worker.off("message",t)}isMain(){return e.isPrimary}registerOnceWorkerMessageListener(e,t){this.workerNodes[e].worker.once("message",t)}registerWorkerMessageListener(e,t){this.workerNodes[e].worker.on("message",t)}sendStartupMessageToWorker(e){this.sendToWorker(e,{ready:!1})}sendToWorker(e,t){this.workerNodes[e]?.worker.send({...t,workerId:this.getWorkerInfo(e)?.id})}setupHook(){e.setupPrimary({...this.opts.settings,exec:this.filePath})}shallCreateDynamicWorker(){return!1}get backPressure(){return this.internalBackPressure()}get busy(){return this.internalBusy()}get type(){return c.fixed}get worker(){return I.cluster}}class le extends ce{constructor(e,t,r={},s){super(e,t,r,s)}checkAndEmitDynamicWorkerCreationEvents(){}checkAndEmitDynamicWorkerDestructionEvents(){}deregisterWorkerMessageListener(e,t){this.workerNodes[e].messageChannel?.port1.off("message",t)}isMain(){return s.isMainThread}registerOnceWorkerMessageListener(e,t){this.workerNodes[e].messageChannel?.port1.once("message",t)}registerWorkerMessageListener(e,t){this.workerNodes[e].messageChannel?.port1.on("message",t)}sendStartupMessageToWorker(e){const t=this.workerNodes[e],r=t.messageChannel.port2;t.worker.postMessage({port:r,ready:!1,workerId:this.getWorkerInfo(e)?.id},[r])}sendToWorker(e,t,r){this.workerNodes[e]?.messageChannel?.port1.postMessage({...t,workerId:this.getWorkerInfo(e)?.id},r)}shallCreateDynamicWorker(){return!1}get backPressure(){return this.internalBackPressure()}get busy(){return this.internalBusy()}get type(){return c.fixed}get worker(){return I.thread}}const me=(e,t)=>{if("string"!=typeof e)throw new TypeError("A taskFunctions parameter object key is not a string");if("string"==typeof e&&0===e.trim().length)throw new TypeError("A taskFunctions parameter object key is an empty string");if("function"!=typeof t.taskFunction)throw new TypeError(`taskFunction object 'taskFunction' property '${t.taskFunction}' is not a function`);R(t.priority),A(t.strategy)},ge=e=>{if("string"!=typeof e)throw new TypeError("name parameter is not a string");if("string"==typeof e&&0===e.trim().length)throw new TypeError("name parameter is an empty string")},we=6e4,pe={killBehavior:_.SOFT,killHandler:m,maxInactiveTime:we};class ye{isMain;mainWorker;opts;activeInterval;lastTaskTimestamp;run=e=>{const{data:t,name:r,taskId:s}=e,i=r??l;if(!this.taskFunctions.has(i))return void this.sendToMainWorker({taskId:s,workerError:{data:t,name:r,...this.handleError(new Error(`Task function '${r}' not found`))}});const o=this.taskFunctions.get(i)?.taskFunction;T(o)?this.runAsync(o,e):this.runSync(o,e)};runAsync=(e,t)=>{const{data:r,name:s,taskId:i}=t;let o=this.beginTaskPerformance(s);e(r).then((e=>{o=this.endTaskPerformance(o),this.sendToMainWorker({data:e,taskId:i,taskPerformance:o})})).catch((e=>{this.sendToMainWorker({taskId:i,workerError:{data:r,name:s,...this.handleError(e)}})})).finally((()=>{this.updateLastTaskTimestamp()})).catch(m)};runSync=(e,t)=>{const{data:r,name:s,taskId:i}=t;try{let t=this.beginTaskPerformance(s);const o=e(r);t=this.endTaskPerformance(t),this.sendToMainWorker({data:o,taskId:i,taskPerformance:t})}catch(e){this.sendToMainWorker({taskId:i,workerError:{data:r,name:s,...this.handleError(e)}})}finally{this.updateLastTaskTimestamp()}};statistics;taskFunctions;constructor(e,t,r,s=pe){if(this.isMain=e,this.mainWorker=t,this.opts=s,null==this.isMain)throw new Error("isMain parameter is mandatory");this.checkTaskFunctions(r),this.checkWorkerOptions(this.opts),this.isMain||this.getMainWorker().on("message",this.handleReadyMessage.bind(this))}getMainWorker(){if(null==this.mainWorker)throw new Error("Main worker not set");return this.mainWorker}handleKillMessage(e){if(this.stopCheckActive(),T(this.opts.killHandler))this.opts.killHandler().then((()=>{this.sendToMainWorker({kill:"success"})})).catch((()=>{this.sendToMainWorker({kill:"failure"})}));else try{this.opts.killHandler?.(),this.sendToMainWorker({kill:"success"})}catch{this.sendToMainWorker({kill:"failure"})}}handleTaskFunctionOperationMessage(e){const{taskFunction:t,taskFunctionOperation:r,taskFunctionProperties:s}=e;if(null==s)throw new Error("Cannot handle task function operation message without task function properties");let i;switch(r){case"add":if("string"!=typeof t)throw new Error(`Cannot handle task function operation ${r} message without task function`);i=this.addTaskFunction(s.name,{taskFunction:new Function(`return ${t}`)(),...null!=s.priority&&{priority:s.priority},...null!=s.strategy&&{strategy:s.strategy}});break;case"default":i=this.setDefaultTaskFunction(s.name);break;case"remove":i=this.removeTaskFunction(s.name);break;default:i={error:new Error("Unknown task operation"),status:!1}}const{error:o,status:n}=i;this.sendToMainWorker({taskFunctionOperation:r,taskFunctionOperationStatus:n,taskFunctionProperties:s,...!n&&null!=o&&{workerError:{name:s.name,...this.handleError(o)}}})}messageListener(e){this.checkMessageWorkerId(e);const{checkActive:t,data:r,kill:s,statistics:i,taskFunctionOperation:o,taskId:n}=e;null!=i?this.statistics=i:null!=t?t?this.startCheckActive():this.stopCheckActive():null!=o?this.handleTaskFunctionOperationMessage(e):null!=n&&null!=r?this.run(e):!0===s&&this.handleKillMessage(e)}sendTaskFunctionsPropertiesToMainWorker(){this.sendToMainWorker({taskFunctionsProperties:this.listTaskFunctionsProperties()})}beginTaskPerformance(e){if(null==this.statistics)throw new Error("Performance statistics computation requirements not set");return{name:e??l,timestamp:u.performance.now(),...this.statistics.elu&&{elu:u.performance.eventLoopUtilization()}}}checkActive(){u.performance.now()-this.lastTaskTimestamp>(this.opts.maxInactiveTime??we)&&this.sendToMainWorker({kill:this.opts.killBehavior})}checkMessageWorkerId(e){if(null==e.workerId)throw new Error("Message worker id is not set");if(e.workerId!==this.id)throw new Error(`Message worker id ${e.workerId.toString()} does not match the worker id ${this.id.toString()}`)}checkTaskFunctions(e){if(null==e)throw new Error("taskFunctions parameter is mandatory");if(this.taskFunctions=new Map,"function"==typeof e){const t={taskFunction:e.bind(this)};this.taskFunctions.set(l,t),this.taskFunctions.set("string"==typeof e.name&&e.name.trim().length>0?e.name:"fn1",t)}else{if(!y(e))throw new TypeError("taskFunctions parameter is not a function or a plain object");{let t=!0;for(let[r,s]of Object.entries(e))"function"==typeof s&&(s={taskFunction:s}),me(r,s),s.taskFunction=s.taskFunction.bind(this),t&&(this.taskFunctions.set(l,s),t=!1),this.taskFunctions.set(r,s);if(t)throw new Error("taskFunctions parameter object is empty")}}}checkWorkerOptions(e){(e=>{if(null!=e&&!y(e))throw new TypeError("opts worker options parameter is not a plain object");if(null!=e?.killBehavior&&!Object.values(_).includes(e.killBehavior))throw new TypeError(`killBehavior option '${e.killBehavior}' is not valid`);if(null!=e?.maxInactiveTime&&!Number.isSafeInteger(e.maxInactiveTime))throw new TypeError("maxInactiveTime option is not an integer");if(null!=e?.maxInactiveTime&&e.maxInactiveTime<5)throw new TypeError("maxInactiveTime option is not a positive integer greater or equal than 5");if(null!=e?.killHandler&&"function"!=typeof e.killHandler)throw new TypeError("killHandler option is not a function")})(e),this.opts={...pe,...e}}endTaskPerformance(e){if(null==this.statistics)throw new Error("Performance statistics computation requirements not set");return{...e,...this.statistics.runTime&&{runTime:u.performance.now()-e.timestamp},...this.statistics.elu&&{elu:u.performance.eventLoopUtilization(e.elu)}}}startCheckActive(){this.lastTaskTimestamp=u.performance.now(),this.activeInterval=setInterval(this.checkActive.bind(this),(this.opts.maxInactiveTime??we)/2)}stopCheckActive(){null!=this.activeInterval&&(clearInterval(this.activeInterval),delete this.activeInterval)}updateLastTaskTimestamp(){null!=this.activeInterval&&(this.lastTaskTimestamp=u.performance.now())}addTaskFunction(e,t){try{if(ge(e),e===l)throw new Error("Cannot add a task function with the default reserved name");return"function"==typeof t&&(t={taskFunction:t}),me(e,t),t.taskFunction=t.taskFunction.bind(this),this.taskFunctions.get(e)===this.taskFunctions.get(l)&&this.taskFunctions.set(l,t),this.taskFunctions.set(e,t),this.sendTaskFunctionsPropertiesToMainWorker(),{status:!0}}catch(e){return{error:e,status:!1}}}hasTaskFunction(e){try{ge(e)}catch(e){return{error:e,status:!1}}return{status:this.taskFunctions.has(e)}}listTaskFunctionsProperties(){let e=l;for(const[t,r]of this.taskFunctions)if(t!==l&&r===this.taskFunctions.get(l)){e=t;break}const t=[];for(const[r,s]of this.taskFunctions)r!==l&&r!==e&&t.push(S(r,s));return[S(l,this.taskFunctions.get(l)),S(e,this.taskFunctions.get(e)),...t]}removeTaskFunction(e){try{if(ge(e),e===l)throw new Error("Cannot remove the task function with the default reserved name");if(this.taskFunctions.get(e)===this.taskFunctions.get(l))throw new Error("Cannot remove the task function used as the default task function");const t=this.taskFunctions.delete(e);return this.sendTaskFunctionsPropertiesToMainWorker(),{status:t}}catch(e){return{error:e,status:!1}}}setDefaultTaskFunction(e){try{if(ge(e),e===l)throw new Error("Cannot set the default task function reserved name as the default task function");if(!this.taskFunctions.has(e))throw new Error("Cannot set the default task function to a non-existing task function");return this.taskFunctions.set(l,this.taskFunctions.get(e)),this.sendTaskFunctionsPropertiesToMainWorker(),{status:!0}}catch(e){return{error:e,status:!1}}}}exports.ClusterWorker=class extends ye{sendToMainWorker=e=>{this.getMainWorker().send({...e,workerId:this.id})};constructor(t,r={}){super(e.isPrimary,e.worker,t,r)}handleError(e){return{message:e.message,stack:e.stack}}handleReadyMessage(e){if(e.workerId===this.id&&!1===e.ready)try{this.getMainWorker().on("message",this.messageListener.bind(this)),this.sendToMainWorker({ready:!0,taskFunctionsProperties:this.listTaskFunctionsProperties()})}catch{this.sendToMainWorker({ready:!1,taskFunctionsProperties:this.listTaskFunctionsProperties()})}}get id(){return this.getMainWorker().id}},exports.DynamicClusterPool=class extends de{emptyEventEmitted;fullEventEmitted;constructor(e,t,r,s={}){super(e,r,s,t),O(this.minimumNumberOfWorkers,this.maximumNumberOfWorkers),this.emptyEventEmitted=!1,this.fullEventEmitted=!1}checkAndEmitDynamicWorkerCreationEvents(){null!=this.emitter&&(!this.fullEventEmitted&&this.full&&(this.emitter.emit(d.full,this.info),this.fullEventEmitted=!0),this.emptyEventEmitted&&!this.empty&&(this.emptyEventEmitted=!1))}checkAndEmitDynamicWorkerDestructionEvents(){null!=this.emitter&&(this.fullEventEmitted&&!this.full&&(this.emitter.emit(d.fullEnd,this.info),this.fullEventEmitted=!1),!this.emptyEventEmitted&&this.empty&&(this.emitter.emit(d.empty,this.info),this.emptyEventEmitted=!0))}shallCreateDynamicWorker(){return!this.full&&this.internalBusy()||this.empty}get backPressure(){return this.full&&this.internalBackPressure()}get busy(){return this.full&&this.internalBusy()}get empty(){return 0===this.minimumNumberOfWorkers&&this.workerNodes.length===this.minimumNumberOfWorkers}get full(){return this.workerNodes.length>=(this.maximumNumberOfWorkers??this.minimumNumberOfWorkers)}get type(){return c.dynamic}},exports.DynamicThreadPool=class extends le{emptyEventEmitted;fullEventEmitted;constructor(e,t,r,s={}){super(e,r,s,t),O(this.minimumNumberOfWorkers,this.maximumNumberOfWorkers),this.emptyEventEmitted=!1,this.fullEventEmitted=!1}checkAndEmitDynamicWorkerCreationEvents(){null!=this.emitter&&(!this.fullEventEmitted&&this.full&&(this.emitter.emit(d.full,this.info),this.fullEventEmitted=!0),this.emptyEventEmitted&&!this.empty&&(this.emptyEventEmitted=!1))}checkAndEmitDynamicWorkerDestructionEvents(){null!=this.emitter&&(this.fullEventEmitted&&!this.full&&(this.emitter.emit(d.fullEnd,this.info),this.fullEventEmitted=!1),!this.emptyEventEmitted&&this.empty&&(this.emitter.emit(d.empty,this.info),this.emptyEventEmitted=!0))}shallCreateDynamicWorker(){return!this.full&&this.internalBusy()||this.empty}get backPressure(){return this.full&&this.internalBackPressure()}get busy(){return this.full&&this.internalBusy()}get empty(){return 0===this.minimumNumberOfWorkers&&this.workerNodes.length===this.minimumNumberOfWorkers}get full(){return this.workerNodes.length>=(this.maximumNumberOfWorkers??this.minimumNumberOfWorkers)}get type(){return c.dynamic}},exports.FixedClusterPool=de,exports.FixedThreadPool=le,exports.KillBehaviors=_,exports.Measurements=x,exports.PoolEvents=d,exports.PoolTypes=c,exports.ThreadWorker=class extends ye{sendToMainWorker=e=>{this.port?.postMessage({...e,workerId:this.id})};port;constructor(e,t={}){super(s.isMainThread,s.parentPort,e,t)}handleError(e){return{error:e,message:e.message,stack:e.stack}}handleKillMessage(e){super.handleKillMessage(e),this.port?.unref(),this.port?.close()}handleReadyMessage(e){if(e.workerId===this.id&&!1===e.ready&&null!=e.port)try{this.port=e.port,this.port.on("message",this.messageListener.bind(this)),this.sendToMainWorker({ready:!0,taskFunctionsProperties:this.listTaskFunctionsProperties()})}catch{this.sendToMainWorker({ready:!1,taskFunctionsProperties:this.listTaskFunctionsProperties()})}}get id(){return s.threadId}},exports.WorkerChoiceStrategies=v,exports.WorkerTypes=I,exports.availableParallelism=()=>{let e=1;try{e=k.availableParallelism()}catch{const t=k.cpus();Array.isArray(t)&&t.length>0&&(e=t.length)}return e}; //# sourceMappingURL=index.cjs.map