/*
All material copyright ESRI, All Rights Reserved, unless otherwise specified.
See https://js.arcgis.com/4.24/esri/copyright.txt for details.
*/
define(["../../chunks/_rollupPluginBabelHelpers","../../kernel","../Error","../Logger","../maybe","../promiseUtils","./utils","./workerFactory"],(function(e,t,o,r,s,n,i,a){"use strict";const c=r.getLogger("esri.core.workers"),{ABORT:l,INVOKE:u,OPEN:b,OPENED:d,RESPONSE:h}=i.MessageType;let p=function(){function r(e,t){this._outJobs=new Map,this._inJobs=new Map,this.worker=e,this.id=t,e.addEventListener("message",this._onMessage.bind(this)),e.addEventListener("error",(e=>{e.preventDefault(),c.error(e)}))}r.create=function(){var t=e._asyncToGenerator((function*(e){return new r(yield a.createWorker(),e)}));function o(e){return t.apply(this,arguments)}return o}();var p=r.prototype;return p.terminate=function(){this.worker.terminate()},p.open=function(){var t=e._asyncToGenerator((function*(e,t={}){const{signal:o}=t,r=i.newJobId();return new Promise(((t,s)=>{const i={resolve:t,reject:s,abortHandle:n.onAbortOrThrow(o,(()=>{this._outJobs.delete(r),this._post({type:l,jobId:r})}))};this._outJobs.set(r,i),this._post({type:b,jobId:r,modulePath:e})}))}));function o(e){return t.apply(this,arguments)}return o}(),p._onMessage=function(e){const t=i.receiveMessage(e);if(t)switch(t.type){case d:this._onOpenedMessage(t);break;case h:this._onResponseMessage(t);break;case l:this._onAbortMessage(t);break;case u:this._onInvokeMessage(t)}},p._onAbortMessage=function(e){const t=this._inJobs,o=e.jobId,r=t.get(o);r&&(r.controller&&r.controller.abort(),t.delete(o))},p._onInvokeMessage=function(e){const{methodName:o,jobId:r,data:s,abortable:a}=e,c=a?new AbortController:null,l=this._inJobs,u=t.workerMessages[o];let b;try{if("function"!=typeof u)throw new TypeError(`${o} is not a function`);b=u.call(null,s,{signal:c?c.signal:null})}catch(d){return void this._post({type:h,jobId:r,error:i.toInvokeError(d)})}n.isPromiseLike(b)?(l.set(r,{controller:c,promise:b}),b.then((e=>{l.has(r)&&(l.delete(r),this._post({type:h,jobId:r},e))}),(e=>{l.has(r)&&(l.delete(r),e||(e={message:"Error encountered at method"+o}),n.isAbortError(e)||this._post({type:h,jobId:r,error:i.toInvokeError(e||{message:`Error encountered at method ${o}`})}))}))):this._post({type:h,jobId:r},b)},p._onOpenedMessage=function(e){const{jobId:t,data:o}=e,r=this._outJobs.get(t);r&&(this._outJobs.delete(t),s.removeMaybe(r.abortHandle),r.resolve(o))},p._onResponseMessage=function(e){const{jobId:t,error:r,data:n}=e,i=this._outJobs.get(t);i&&(this._outJobs.delete(t),s.removeMaybe(i.abortHandle),r?i.reject(o.fromJSON(JSON.parse(r))):i.resolve(n))},p._post=function(e,t,o){return i.postMessage(this.worker,e,t,o)},r}();return p}));
