UNPKG

@yuebai008/cli

Version:

Command line interface for rapid qg-minigame development

1 lines 2.42 kB
import*as Common from"../../core/common/common.js";const MAX_WORKERS=Math.min(2,navigator.hardwareConcurrency-1);let formatterWorkerPoolInstance;export class FormatterWorkerPool{taskQueue;workerTasks;constructor(){this.taskQueue=[],this.workerTasks=new Map}static instance(){return formatterWorkerPoolInstance||(formatterWorkerPoolInstance=new FormatterWorkerPool),formatterWorkerPoolInstance}createWorker(){const t=Common.Worker.WorkerWrapper.fromURL(new URL("../../entrypoints/formatter_worker/formatter_worker-entrypoint.js",import.meta.url));return t.onmessage=this.onWorkerMessage.bind(this,t),t.onerror=this.onWorkerError.bind(this,t),t}processNextTask(){if(!this.taskQueue.length)return;let t=[...this.workerTasks.keys()].find((t=>!this.workerTasks.get(t)));if(!t&&this.workerTasks.size<MAX_WORKERS&&(t=this.createWorker()),!t)return;const r=this.taskQueue.shift();r&&(this.workerTasks.set(t,r),t.postMessage({method:r.method,params:r.params}))}onWorkerMessage(t,r){const e=this.workerTasks.get(t);e&&(e.isChunked&&r.data&&!r.data.isLastChunk?e.callback(r.data):(this.workerTasks.set(t,null),this.processNextTask(),e.callback(r.data?r.data:null)))}onWorkerError(t,r){console.error(r);const e=this.workerTasks.get(t);t.terminate(),this.workerTasks.delete(t);const s=this.createWorker();this.workerTasks.set(s,null),this.processNextTask(),e&&e.callback(null)}runChunkedTask(t,r,e){const s=new Task(t,r,(function(t){if(!t)return void e(!0,null);const r="isLastChunk"in t&&Boolean(t.isLastChunk),s="chunk"in t&&t.chunk;e(r,s)}),!0);this.taskQueue.push(s),this.processNextTask()}runTask(t,r){return new Promise((e=>{const s=new Task(t,r,e,!1);this.taskQueue.push(s),this.processNextTask()}))}format(t,r,e){const s={mimeType:t,content:r,indentString:e};return this.runTask("format",s)}javaScriptSubstitute(t,r){return this.runTask("javaScriptSubstitute",{content:t,mapping:r}).then((t=>t||""))}javaScriptScopeTree(t,r="script"){return this.runTask("javaScriptScopeTree",{content:t,sourceType:r}).then((t=>t||null))}evaluatableJavaScriptSubstring(t){return this.runTask("evaluatableJavaScriptSubstring",{content:t}).then((t=>t||""))}parseCSS(t,r){this.runChunkedTask("parseCSS",{content:t},(function(t,e){r(t,e||[])}))}}class Task{method;params;callback;isChunked;constructor(t,r,e,s){this.method=t,this.params=r,this.callback=e,this.isChunked=s}}export function formatterWorkerPool(){return FormatterWorkerPool.instance()}