-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimjoy-rpc.min.js
2 lines (2 loc) · 55.1 KB
/
imjoy-rpc.min.js
1
2
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define("imjoyRPC",[],t):"object"==typeof exports?exports.imjoyRPC=t():e.imjoyRPC=t()}(window,(function(){return function(e){var t={};function r(n){if(t[n])return t[n].exports;var i=t[n]={i:n,l:!1,exports:{}};return e[n].call(i.exports,i,i.exports,r),i.l=!0,i.exports}return r.m=e,r.c=t,r.d=function(e,t,n){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var i in e)r.d(n,i,function(t){return e[t]}.bind(null,i));return n},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=14)}([,function(module,__webpack_exports__,__webpack_require__){"use strict";function randId(){return Math.random().toString(36).substr(2,10)+(new Date).getTime()}__webpack_require__.d(__webpack_exports__,"f",(function(){return randId})),__webpack_require__.d(__webpack_exports__,"b",(function(){return dtypeToTypedArray})),__webpack_require__.d(__webpack_exports__,"d",(function(){return loadRequirementsInWindow})),__webpack_require__.d(__webpack_exports__,"c",(function(){return loadRequirements})),__webpack_require__.d(__webpack_exports__,"e",(function(){return normalizeConfig})),__webpack_require__.d(__webpack_exports__,"h",(function(){return typedArrayToDtype})),__webpack_require__.d(__webpack_exports__,"g",(function(){return setupServiceWorker})),__webpack_require__.d(__webpack_exports__,"a",(function(){return MessageEmitter}));const dtypeToTypedArray={int8:Int8Array,int16:Int16Array,int32:Int32Array,uint8:Uint8Array,uint16:Uint16Array,uint32:Uint32Array,float32:Float32Array,float64:Float64Array,array:Array};async function loadRequirementsInWindow(e){function t(e){return new Promise((t,r)=>{var n=document.createElement("script");n.src=e,n.type="text/javascript",n.onload=t,n.onreadystatechange=function(){"loaded"!==this.readyState&&"complete"!==this.readyState||t()},n.onerror=r,document.head.appendChild(n)})}async function r(){for(var e=Array.prototype.slice.call(arguments),r=e.length,n=0;n<r;n++)await t(e[n])}if(e&&(Array.isArray(e)||"string"==typeof e))try{var n;if(e="string"==typeof e?[e]:e,!Array.isArray(e))throw"unsupported requirements definition";for(var i=0;i<e.length;i++)e[i].toLowerCase().endsWith(".css")||e[i].startsWith("css:")?(e[i].startsWith("css:")&&(e[i]=e[i].slice(4)),(n=document.createElement("link")).rel="stylesheet",n.href=e[i],document.head.appendChild(n)):e[i].toLowerCase().endsWith(".mjs")||e[i].startsWith("mjs:")?(e[i].startsWith("mjs:")&&(e[i]=e[i].slice(4)),await import(e[i])):e[i].toLowerCase().endsWith(".js")||e[i].startsWith("js:")?(e[i].startsWith("js:")&&(e[i]=e[i].slice(3)),await r(e[i])):e[i].startsWith("http")?await r(e[i]):e[i].startsWith("cache:")||console.log("Unprocessed requirements url: "+e[i])}catch(t){throw"failed to import required scripts: "+e.toString()}}async function loadRequirementsInWebworker(e){if(e&&(Array.isArray(e)||"string"==typeof e))try{Array.isArray(e)||(e=[e]);for(var t=0;t<e.length;t++){if(e[t].toLowerCase().endsWith(".css")||e[t].startsWith("css:"))throw"unable to import css in a webworker";e[t].toLowerCase().endsWith(".js")||e[t].startsWith("js:")?(e[t].startsWith("js:")&&(e[t]=e[t].slice(3)),importScripts(e[t])):e[t].startsWith("http")?importScripts(e[t]):e[t].startsWith("cache:")||console.log("Unprocessed requirements url: "+e[t])}}catch(t){throw"failed to import required scripts: "+e.toString()}}function loadRequirements(e){return"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope?loadRequirementsInWebworker(e):loadRequirementsInWindow(e)}function normalizeConfig(e){return e.version=e.version||"0.1.0",e.description=e.description||`[TODO: add description for ${e.name} ]`,e.type=e.type||"rpc-window",e.id=e.id||randId(),e.target_origin=e.target_origin||"*",e.allow_execution=e.allow_execution||!1,e=Object.keys(e).reduce((t,r)=>("function"!=typeof e[r]&&(t[r]=e[r]),t),{})}const typedArrayToDtypeMapping={Int8Array:"int8",Int16Array:"int16",Int32Array:"int32",Uint8Array:"uint8",Uint16Array:"uint16",Uint32Array:"uint32",Float32Array:"float32",Float64Array:"float64",Array:"array"},typedArrayToDtypeKeys=[];for(const arrType of Object.keys(typedArrayToDtypeMapping))typedArrayToDtypeKeys.push(eval(arrType));function typedArrayToDtype(e){let t=typedArrayToDtypeMapping[e.constructor.name];if(!t){const r=Object.getPrototypeOf(e);for(const e of typedArrayToDtypeKeys)if(r instanceof e){t=typedArrayToDtypeMapping[e.name];break}}return t}function cacheUrlInServiceWorker(e){return new Promise((function(t,r){const n={command:"add",url:e};if(!navigator.serviceWorker||!navigator.serviceWorker.register)return void r("Service worker is not supported.");const i=new MessageChannel;i.port1.onmessage=function(e){e.data&&e.data.error?r(e.data.error):t(e.data&&e.data.result)},navigator.serviceWorker&&navigator.serviceWorker.controller?navigator.serviceWorker.controller.postMessage(n,[i.port2]):r("Service worker controller is not available")}))}async function cacheRequirements(e){e=e||[],Array.isArray(e)||(e=[e]);for(let t of e)t.startsWith("js:")&&(t=t.slice(3)),t.startsWith("css:")&&(t=t.slice(4)),t.startsWith("cache:")&&(t=t.slice(6)),t.startsWith("http")&&await cacheUrlInServiceWorker(t).catch(e=>{console.error(e)})}function setupServiceWorker(e,t,r){if("serviceWorker"in navigator){if(e=e||"/",navigator.serviceWorker.register(e+"plugin-service-worker.js").then((function(e){console.log("ServiceWorker registration successful with scope: ",e.scope)}),(function(e){console.log("ServiceWorker registration failed: ",e)})),t=t||"*",(r=r||cacheRequirements)&&"function"!=typeof r)throw new Error("config.cache_requirements must be a function");window.addEventListener("message",(function(e){if("*"===t||e.origin===t){const t=e.data;"cacheRequirements"===t.type&&r(t.requirements)}}))}}function urlJoin(...e){return e.join("/").replace(/[\/]+/g,"/").replace(/^(.+):\//,"$1://").replace(/^file:/,"file:/").replace(/\/(\?|&|#[^!])/g,"$1").replace(/\?/g,"&").replace("&","?")}class MessageEmitter{constructor(e){this._event_handlers={},this._once_handlers={},this._debug=e}emit(){throw new Error("emit is not implemented")}on(e,t){this._event_handlers[e]||(this._event_handlers[e]=[]),this._event_handlers[e].push(t)}once(e,t){t.___event_run_once=!0,this.on(e,t)}off(e,t){if(e||t){if(e&&!t)this._event_handlers[e]&&(this._event_handlers[e]=[]);else if(this._event_handlers[e]){const r=this._event_handlers[e].indexOf(t);r>=0&&this._event_handlers[e].splice(r,1)}}else this._event_handlers={}}_fire(e,t){if(this._event_handlers[e])for(var r=this._event_handlers[e].length;r--;){const n=this._event_handlers[e][r];try{n(t)}catch(e){console.error(e)}finally{n.___event_run_once&&this._event_handlers[e].splice(r,1)}}else this._debug&&console.warn("unhandled event",e,t)}}},function(e,t,r){"use strict";r.d(t,"a",(function(){return i})),r.d(t,"b",(function(){return c}));var n=r(1);const i="0.2.3",o=Object.getPrototypeOf(Object.getPrototypeOf(new Uint8Array)).constructor;function s(e,t){const r=new Uint8Array(e.byteLength+t.byteLength);return r.set(new Uint8Array(e),0),r.set(new Uint8Array(t),e.byteLength),r.buffer}function a(e,t){if(!t)throw new Error("undefined index");return"string"==typeof t?a(e,t.split(".")):0===t.length?e:a(e[t[0]],t.slice(1))}class c extends n.a{constructor(e,t,r){super(t&&t.debug),this._connection=e,this.config=t||{},this._codecs=r||{},this._object_store={},this._method_weakmap=new WeakMap,this._object_weakmap=new WeakMap,this._local_api=null,this._remote_set=!1;const n=this.config.name;this._connection.execute=this._connection.execute||function(){throw new Error(`connection.execute not implemented (in "${n}")`)},this._store=new _,this._method_refs=new _,this._method_refs.onReady(()=>{this._fire("remoteIdle")}),this._method_refs.onBusy(()=>{this._fire("remoteBusy")}),this._setupMessageHanlders()}init(){this._connection.emit({type:"initialized",config:this.config,peer_id:this._connection.peer_id})}setConfig(e){if(e)for(const t of Object.keys(e))this.config[t]=e[t]}getRemoteCallStack(){return this._method_refs.getStack()}getRemote(){return this._remote_interface}setInterface(e,t){if(t=t||{},this.config.name=t.name||this.config.name,this.config.description=t.description||this.config.description,this.config.forwarding_functions)for(let t of this.config.forwarding_functions){const r=this._remote_interface;r[t]&&(e.constructor===Object?e[t]||(e[t]=(...e)=>{r[t](...e)}):e.constructor.constructor===Function&&(e.constructor.prototype[t]||(e.constructor.prototype[t]=(...e)=>{r[t](...e)})))}return this._local_api=e,this._remote_set?this.sendInterface():this._fire("interfaceAvailable"),new Promise(e=>{this.once("interfaceSetAsRemote",e)})}sendInterface(){if(!this._local_api)throw new Error("interface is not set.");this._encode(this._local_api,!0).then(e=>{this._connection.emit({type:"setInterface",api:e})})}_disposeObject(e){if(!this._object_store[e])throw new Error(`Object (id=${e}) not found.`);delete this._object_store[e]}disposeObject(e){return new Promise((t,r)=>{if(!this._object_weakmap.has(e))throw new Error("Invalid object");{const n=this._object_weakmap.get(e);this._connection.once("disposed",e=>{e.error?r(new Error(e.error)):t()}),this._connection.emit({type:"disposeObject",object_id:n})}})}_setupMessageHanlders(){this._connection.on("init",this.init),this._connection.on("execute",e=>{Promise.resolve(this._connection.execute(e.code)).then(()=>{this._connection.emit({type:"executed"})}).catch(e=>{console.error(e),this._connection.emit({type:"executed",error:String(e)})})}),this._connection.on("method",async e=>{let t,r,n,i,o,s;try{e.promise&&([t,r]=await this._unwrap(e.promise,!1));const c=this._object_store[e.object_id];if(n=a(c,e.name),e.name.includes(".")){const t=e.name.split(".");i=a(c,t.slice(0,t.length-1).join("."))}else i=c;o=await this._unwrap(e.args,!0),e.promise?(s=n.apply(i,o),s instanceof Promise||n.constructor&&"AsyncFunction"===n.constructor.name?s.then(t).catch(r):t(s)):n.apply(i,o)}catch(e){console.error(this.config.name,e),r&&r(e)}}),this._connection.on("callback",async e=>{let t,r,n,i,o;try{if(e.promise&&([t,r]=await this._unwrap(e.promise,!1)),e.promise){if(n=this._store.fetch(e.id),i=await this._unwrap(e.args,!0),!n)throw new Error("Callback function can only called once, if you want to call a function for multiple times, please make it as a plugin api function. See https://imjoy.io/docs for more details.");o=n.apply(null,i),o instanceof Promise||n.constructor&&"AsyncFunction"===n.constructor.name?o.then(t).catch(r):t(o)}else{if(n=this._store.fetch(e.id),i=await this._unwrap(e.args,!0),!n)throw new Error("Please notice that callback function can only called once, if you want to call a function for multiple times, please make it as a plugin api function. See https://imjoy.io/docs for more details.");n.apply(null,i)}}catch(e){console.error(this.config.name,e),r&&r(e)}}),this._connection.on("disposeObject",e=>{try{this._disposeObject(e.object_id),this._connection.emit({type:"disposed"})}catch(e){console.error(e),this._connection.emit({type:"disposed",error:String(e)})}}),this._connection.on("setInterface",e=>{this._setRemoteInterface(e.api)}),this._connection.on("getInterface",()=>{this._fire("getInterface"),this._local_api?this.sendInterface():this.once("interfaceAvailable",()=>{this.sendInterface()})}),this._connection.on("interfaceSetAsRemote",()=>{this._remote_set=!0,this._fire("interfaceSetAsRemote")}),this._connection.on("disconnect",()=>{this._fire("beforeDisconnect"),this._connection.disconnect(),this._fire("disconnected")})}requestRemote(){this._connection.emit({type:"getInterface"})}_ndarray(e,t,r){const i=Object(n.h)(e);if(r&&r!==i)throw"dtype doesn't match the type of the array: "+i+" != "+r;return t=t||[e.length],{_rtype:"ndarray",_rvalue:e.buffer,_rshape:t,_rdtype:i}}_setRemoteInterface(e){this._decode(e).then(e=>{if(this._remote_interface){for(let e in this._remote_interface)delete this._remote_interface[e];Object.assign(this._remote_interface,e)}else this._remote_interface=e;this._fire("remoteReady"),this._reportRemoteSet()})}_genRemoteMethod(e,t,r){const n=this,i=function(){return new Promise(async(i,o)=>{let s=null;try{s=n._method_refs.put(r?r+"/"+t:t);const a=function(){return null!==s&&n._method_refs.fetch(s),i.apply(this,arguments)},c=function(){return null!==s&&n._method_refs.fetch(s),o.apply(this,arguments)},_=await n._wrap([a,c]);a.__promise_pair=_[1]._rvalue,c.__promise_pair=_[0]._rvalue;let l=Array.prototype.slice.call(arguments);const d=l.length,f=d>0&&"object"==typeof l[d-1]&&null!==l[d-1]&&l[d-1]._rkwargs;f&&delete l[d-1]._rkwargs,l="register"===t||"registerService"===t||"register_service"===t||"export"===t||"on"===t?await n._wrap(l,!0):await n._wrap(l);const p=l.__transferables__;p&&delete l.__transferables__,n._connection.emit({type:"method",target_id:e,name:t,object_id:r,args:l,promise:_,with_kwargs:f},p)}catch(e){s&&n._method_refs.fetch(s),o(`Failed to exectue remote method (interface: ${r||n.id}, method: ${t}), error: ${e}`)}})};return i.__remote_method=!0,i}_reportRemoteSet(){this._connection.emit({type:"interfaceSetAsRemote"})}async _encode(e,t,r){const i=typeof e;if("number"===i||"string"===i||"boolean"===i||null==e||e instanceof ArrayBuffer)return e;let s;if("function"==typeof e){if(t){if(!r)throw new Error("objectId is not specified.");s={_rtype:"interface",_rtarget_id:this._connection.peer_id,_rintf:r,_rvalue:t},this._method_weakmap.set(e,s)}else if(this._method_weakmap.has(e))s=this._method_weakmap.get(e);else{const t=this._store.put(e);s={_rtype:"callback",_rtarget_id:this._connection.peer_id,_rname:e.constructor&&e.constructor.name||t,_rvalue:t}}return s}if(e.constructor instanceof Object&&e._rtype){if(e._rintf){const n=e._rtype;delete e._rtype,s=await this._encode(e,t,r),s._rtype=n}else s=e;return s}const a=[],c=e._transfer,_=Array.isArray(e);for(let n of Object.keys(this._codecs)){const i=this._codecs[n];if(i.encoder&&e instanceof i.type){let n=await Promise.resolve(i.encoder(e));if(n&&!n._rtype&&(n._rtype=i.name),n&&n._rintf){const e=n._rtype;delete n._rtype,n=await this._encode(n,t,r),n._rtype=e}return s=n,s}}if("undefined"!=typeof tf&&tf.Tensor&&e instanceof tf.Tensor){const t=e.dataSync();(e._transfer||c)&&(a.push(t.buffer),delete e._transfer),s={_rtype:"ndarray",_rvalue:t.buffer,_rshape:e.shape,_rdtype:e.dtype}}else if("undefined"!=typeof nj&&nj.NdArray&&e instanceof nj.NdArray){const t=Object(n.h)(e.selection.data);(e._transfer||c)&&(a.push(e.selection.data.buffer),delete e._transfer),s={_rtype:"ndarray",_rvalue:e.selection.data.buffer,_rshape:e.shape,_rdtype:t}}else if(e instanceof Error)console.error(e),s={_rtype:"error",_rvalue:e.toString()};else if("undefined"!=typeof File&&e instanceof File)s={_rtype:"file",_rvalue:e,_rpath:e._path||e.webkitRelativePath};else if(e!==Object(e)||e instanceof Boolean||e instanceof String||e instanceof Date||e instanceof RegExp||e instanceof ImageData||"undefined"!=typeof FileList&&e instanceof FileList||"undefined"!=typeof FileSystemDirectoryHandle&&e instanceof FileSystemDirectoryHandle||"undefined"!=typeof FileSystemFileHandle&&e instanceof FileSystemFileHandle||"undefined"!=typeof FileSystemHandle&&e instanceof FileSystemHandle||"undefined"!=typeof FileSystemWritableFileStream&&e instanceof FileSystemWritableFileStream)s=e;else if("undefined"!=typeof File&&e instanceof File)s={_rtype:"file",_rname:e.name,_rmime:e.type,_rvalue:e,_rpath:e._path||e.webkitRelativePath};else if(e instanceof Blob)s={_rtype:"blob",_rvalue:e};else if(e instanceof o){(e._transfer||c)&&(a.push(e.buffer),delete e._transfer);const t=Object(n.h)(e);s={_rtype:"typedarray",_rvalue:e.buffer,_rdtype:t}}else if(e instanceof DataView)(e._transfer||c)&&(a.push(e.buffer),delete e._transfer),s={_rtype:"memoryview",_rvalue:e.buffer};else if(e instanceof Set)s={_rtype:"set",_rvalue:await this._encode(Array.from(e),t)};else if(e instanceof Map)s={_rtype:"orderedmap",_rvalue:await this._encode(Array.from(e),t)};else if(e.constructor instanceof Object||Array.isArray(e)){let i;if(s=_?[]:{},e.constructor===Object||Array.isArray(e))i=Object.keys(e);else{if(e.constructor===Function)throw new Error("Please instantiate the class before exportting it.");if(e.constructor.constructor!==Function)throw Error("Unsupported interface type");i=Object.getOwnPropertyNames(Object.getPrototypeOf(e)).concat(Object.keys(e)),t=!0}let o=!1;if(e._rintf||t){r||(r="string"==typeof e._rintf&&e._rintf.length>0?e._rintf:Object(n.f)(),this._object_store[r]&&console.warn("Overwritting interface object with the same id: "+r),this._object_store[r]=e);for(let n of i)"constructor"!==n&&(n.startsWith("_")||(s[n]=await this._encode(e[n],"string"==typeof t?t+"."+n:n,r),"function"==typeof e[n]&&(o=!0)));o&&(s._rintf=r),e.on&&"function"==typeof e.on&&e.on("close",()=>{delete this._object_store[r]})}else for(let t of i)["hasOwnProperty","constructor"].includes(t)||(s[t]=await this._encode(e[t]))}else{if("object"!=typeof e)throw"imjoy-rpc: Unsupported data type:"+e;{const t=Object.getOwnPropertyNames(Object.getPrototypeOf(e)).concat(Object.keys(e)),r=Object(n.f)();for(let r of t)["hasOwnProperty","constructor"].includes(r)||(s[r]=await this._encode(e[r],r,s));s._rintf=r}}if(a.length>0&&(s.__transferables__=a),!s)throw new Error("Failed to encode object");return s}async _decode(e,t){if(!e)return e;let r;if(e._rtype)if(this._codecs[e._rtype]&&this._codecs[e._rtype].decoder){if(e._rintf){const r=e._rtype;delete e._rtype,(e=await this._decode(e,t))._rtype=r}r=await Promise.resolve(this._codecs[e._rtype].decoder(e))}else if("callback"===e._rtype)r=this._genRemoteCallback(e._rtarget_id,e._rvalue,t);else if("interface"===e._rtype)r=this._genRemoteMethod(e._rtarget_id,e._rvalue,e._rintf);else if("ndarray"===e._rtype)if("undefined"!=typeof nj&&nj.array)Array.isArray(e._rvalue)&&(e._rvalue=e._rvalue.reduce(s)),r=nj.array(new Uint8(e._rvalue),e._rdtype).reshape(e._rshape);else if("undefined"!=typeof tf&&tf.Tensor){Array.isArray(e._rvalue)&&(e._rvalue=e._rvalue.reduce(s));const t=n.b[e._rdtype];r=tf.tensor(new t(e._rvalue),e._rshape,e._rdtype)}else r=e;else if("error"===e._rtype)r=new Error(e._rvalue);else if("file"===e._rtype)e._rvalue instanceof File?(r=e._rvalue,r._path=e._rpath):(r=new File([e._rvalue],e._rname,{type:e._rmime}),r._path=e._rpath);else if("typedarray"===e._rtype){const t=n.b[e._rdtype];if(!t)throw new Error("unsupported dtype: "+e._rdtype);r=new t(e._rvalue)}else if("memoryview"===e._rtype)r=new DataView(e._rvalue);else if("blob"===e._rtype)r=e._rvalue instanceof Blob?e._rvalue:new Blob([e._rvalue],{type:e._rmime});else if("orderedmap"===e._rtype)r=new Map(await this._decode(e._rvalue,t));else if("set"===e._rtype)r=new Set(await this._decode(e._rvalue,t));else if(e._rintf){const n=e._rtype;delete e._rtype,r=await this._decode(e,t),r._rtype=n}else r=e;else if(e.constructor===Object||Array.isArray(e)){const n=Array.isArray(e);r=n?[]:{};for(let i of Object.keys(e))if(n||e.hasOwnProperty(i)){const n=e[i];r[i]=await this._decode(n,t)}}else r=e;if(void 0===r)throw new Error("Failed to decode object");return e._rintf&&this._object_weakmap.set(r,e._rintf),r}async _wrap(e,t){return await this._encode(e,t)}async _unwrap(e,t){return await this._decode(e,t)}_genRemoteCallback(e,t,r){const n=this;let i;return r?(i=function(){return new Promise(async(r,i)=>{const o=await n._wrap(Array.prototype.slice.call(arguments)),s=o.length,a=s>0&&"object"==typeof o[s-1]&&null!==o[s-1]&&o[s-1]._rkwargs;a&&delete o[s-1]._rkwargs;const c=o.__transferables__;c&&delete o.__transferables__;const _=await n._wrap([r,i]);r.__promise_pair=_[1]._rvalue,i.__promise_pair=_[0]._rvalue;try{n._connection.emit({type:"callback",target_id:e,id:t,args:o,promise:_,with_kwargs:a},c)}catch(e){i(`Failed to exectue remote callback ( id: ${t}).`)}})},i):(i=async function(){const r=await n._wrap(Array.prototype.slice.call(arguments)),i=r.length,o=i>0&&"object"==typeof r[i-1]&&null!==r[i-1]&&r[i-1]._rkwargs;o&&delete r[i-1]._rkwargs;const s=r.__transferables__;return s&&delete r.__transferables__,n._connection.emit({type:"callback",target_id:e,id:t,args:r,with_kwargs:o},s)},i)}reset(){this._event_handlers={},this._once_handlers={},this._remote_interface=null,this._object_store={},this._method_weakmap=new WeakMap,this._object_weakmap=new WeakMap,this._local_api=null,this._store=new _,this._method_refs=new _}disconnect(){this._connection.emit({type:"disconnect"}),this.reset(),setTimeout(()=>{this._connection.disconnect()},2e3)}}class _{constructor(){this._store={},this._indices=[0],this._readyHandler=function(){},this._busyHandler=function(){},this._readyHandler()}onReady(e){this._readyHandler=e||function(){}}onBusy(e){this._busyHandler=e||function(){}}getStack(){return Object.keys(this._store).length}_genId(){let e;return e=1===this._indices.length?this._indices[0]++:this._indices.shift(),e}_releaseId(e){for(let t=0;t<this._indices.length;t++)if(e<this._indices[t]){this._indices.splice(t,0,e);break}for(let e=this._indices.length-1;e>=0&&this._indices[e]-1===this._indices[e-1];e--)this._indices.pop()}put(e){this._busyHandler&&0===Object.keys(this._store).length&&this._busyHandler();const t=this._genId();return this._store[t]=e,t}fetch(e){const t=this._store[e];return t&&!t.__remote_method&&(delete this._store[e],this._releaseId(e),this._readyHandler&&0===Object.keys(this._store).length&&this._readyHandler()),t&&t.__promise_pair&&this.fetch(t.__promise_pair),t}}},,,,function(module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.d(__webpack_exports__,"a",(function(){return setupIframe}));var _pluginCore_js__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__(10),_rpc_js__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__(2),_utils_js__WEBPACK_IMPORTED_MODULE_2__=__webpack_require__(1);function _htmlToElement(e){var t=document.createElement("template");return e=e.trim(),t.innerHTML=e,t.content.firstChild}const _inWebWorker="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope;async function executeEsModule(e){const t="data:text/javascript;charset=utf-8,"+encodeURIComponent(e);await import(t)}class Connection extends _utils_js__WEBPACK_IMPORTED_MODULE_2__.a{constructor(e){super(e&&e.debug),this.config=e||{},this.peer_id=Object(_utils_js__WEBPACK_IMPORTED_MODULE_2__.f)()}connect(){this.config.target_origin=this.config.target_origin||"*",this.config.broadcastChannel?this.broadcastChannel=new BroadcastChannel(this.config.broadcastChannel):this.broadcastChannel=null,this.broadcastChannel?this.broadcastChannel.addEventListener("message",this):globalThis.addEventListener("message",this),this.emit({type:"initialized",config:this.config,origin:globalThis.location.origin,peer_id:this.peer_id}),this._fire("connected")}handleEvent(e){"message"!==e.type||!this.broadcastChannel&&"*"!==this.config.target_origin&&e.origin&&e.origin!==this.config.target_origin||(e.data.peer_id===this.peer_id?this._fire(e.data.type,e.data):this.config.debug&&console.log(`connection peer id mismatch ${e.data.peer_id} !== ${this.peer_id}`))}disconnect(){this._fire("beforeDisconnect"),globalThis.removeEventListener("message",this),this._fire("disconnected")}emit(e){let t;this.broadcastChannel?this.broadcastChannel.postMessage(e):e.__transferables__?(t=e.__transferables__,delete e.__transferables__):_inWebWorker?self.postMessage(e,t):parent.postMessage(e,this.config.target_origin,t)}async execute(code){try{if("requirements"===code.type)await Object(_utils_js__WEBPACK_IMPORTED_MODULE_2__.d)(code.requirements);else if("script"===code.type)if(code.src){var script_node=document.createElement("script");script_node.setAttribute("type",code.attrs.type),script_node.setAttribute("src",code.src),document.head.appendChild(script_node)}else if(code.content&&"javascript"===code.attrs.lang)"module"===code.attrs.type?await executeEsModule(code.content):eval(code.content);else{var node=document.createElement("script");for(let e in code.attrs)node.setAttribute(e,code.attrs[e]);node.appendChild(document.createTextNode(code.content)),document.body.appendChild(node)}else if("style"===code.type){const e=document.createElement("style");code.src&&(e.src=code.src),e.innerHTML=code.content,document.head.appendChild(e)}else if("link"===code.type){const e=document.createElement("link");code.rel&&(e.rel=code.rel),code.href&&(e.href=code.href),code.attrs&&code.attrs.type&&(e.type=code.attrs.type),document.head.appendChild(e)}else{if("html"!==code.type)throw"unsupported code type.";document.body.appendChild(_htmlToElement(code.content))}_inWebWorker?self.postMessage({type:"executed"}):parent.postMessage({type:"executed"},this.config.target_origin)}catch(e){console.error("failed to execute scripts: ",code,e),_inWebWorker?self.postMessage({type:"executed",error:e.stack||String(e)}):parent.postMessage({type:"executed",error:e.stack||String(e)},this.config.target_origin)}}}function setupIframe(e){(e=e||{}).dedicated_thread=!1,e.lang="javascript",e.api_version=_rpc_js__WEBPACK_IMPORTED_MODULE_1__.a;const t=new Connection(e);Object(_pluginCore_js__WEBPACK_IMPORTED_MODULE_0__.a)(t,e),t.connect()}},,function(e){e.exports=JSON.parse('{"a":"0.5.9"}')},,function(e,t,r){"use strict";r.d(t,"a",(function(){return i}));var n=r(2);function i(e,t){t=t||{};const r={},i=new n.b(e,t,r);i.on("getInterface",(function(){a()})),i.on("remoteReady",(function(){const e=i.getRemote()||{};e.registerCodec=function(e){if(!e.name||!e.encoder&&!e.decoder)throw new Error("Invalid codec format, please make sure you provide a name, type, encoder and decoder.");if(e.type)for(let t of Object.keys(r))r[t].type!==e.type&&t!==e.name||(delete r[t],console.warn("Remove duplicated codec: "+t));r[e.name]=e},e.init=function(e){i.setInterface({setup(){}},e)},e.disposeObject=function(e){i.disposeObject(e)},e.export=function(e,t){i.setInterface(e,t)},e.onLoad=function(e){e=c(e),o?e():s.push(e)},e.dispose=function(e){i.disconnect()},e._rpc=i,"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope?(self.api=e,self.postMessage({type:"imjoy_remote_api_ready"}),self.dispatchEvent(new CustomEvent("imjoy_remote_api_ready",{detail:e}))):window.dispatchEvent(new CustomEvent("imjoy_remote_api_ready",{detail:e}))}));let o=!1;const s=[],a=function(){if(!o){let e;for(o=!0;e=s.pop();)e()}},c=function(e){const t=typeof e;if("function"!==t){throw new Error("A function may only be subsribed to the event, "+t+" was provided instead")}return e};return i}},,,,function(e,t,r){"use strict";r.r(t),r.d(t,"waitForInitialization",(function(){return l})),r.d(t,"setupRPC",(function(){return d}));var n=r(15),i=r.n(n),o=r(6),s=r(1);r.d(t,"loadRequirements",(function(){return s.c}));var a=r(2);r.d(t,"RPC",(function(){return a.b})),r.d(t,"API_VERSION",(function(){return a.a}));var c=r(8);function _(){return"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope}function l(e){_()&&(globalThis.parent=self),(e=e||{}).enable_service_worker&&(Object(s.g)(e.base_url,e.target_origin,e.cache_requirements),e.enable_service_worker=!1),e.cache_requirements&&delete e.cache_requirements;const t=e.target_origin||"*";if(e.credential_required&&"function"!=typeof e.verify_credential)throw new Error("Please also provide the `verify_credential` function with `credential_required`.");if(e.credential_required&&"*"===t)throw new Error("`target_origin` was set to `*` with `credential_required=true`, there is a security risk that you may leak the credential to website from other origin. Please specify the `target_origin` explicitly.");const r=Object(s.f)(),n=i=>{if("message"===i.type&&(!i.origin||"*"===t||i.origin===t)){if("initialize"!==i.data.type)throw new Error("unrecognized message: "+i.data);{globalThis.removeEventListener("message",n),i.data.peer_id!==r&&console.warn(`${i.data.config&&i.data.config.name}: connection peer id mismatch ${i.data.peer_id} !== ${r}`);const o=i.data.config;"*"!==t&&(o.target_origin=t),e.credential_required?e.verify_credential(o.credential).then(e=>{if(!e||!e.auth||e.error)throw new Error("Failed to verify the credentail:"+(e&&e.error));o.auth=e.auth,d(o).then(()=>{console.log("ImJoy RPC loaded successfully!")})}):d(o).then(()=>{console.log("ImJoy RPC loaded successfully!")})}}};globalThis.addEventListener("message",n),_()?parent.postMessage({type:"imjoyRPCReady",config:e,peer_id:r}):parent.postMessage({type:"imjoyRPCReady",config:e,peer_id:r},"*")}function d(e){return(e=e||{}).name=e.name||Object(s.f)(),(e=Object(s.e)(e)).enable_service_worker&&Object(s.g)(e.base_url,e.target_origin,e.cache_requirements),e.cache_requirements&&delete e.cache_requirements,new Promise((t,r)=>{const n=r=>{const i=r.detail;e.expose_api_globally&&(globalThis.api=i),t(i),globalThis.removeEventListener("imjoy_remote_api_ready",n)};if(function(){try{return window.self!==window.top}catch(e){return!0}}()){if("web-worker"===e.type)try{!function(e){if(!e.allow_execution)throw new Error("web-worker plugin can only work with allow_execution=true");let t=null;e.broadcastChannel&&(t=new BroadcastChannel(e.broadcastChannel));const r=new i.a,n=setTimeout((function(){r.terminate(),console.warn("Plugin failed to start as a web-worker, running in an iframe instead."),Object(o.a)(e)}),2e3),a=Object(s.f)();r.addEventListener("message",(function(i){let o=void 0;const s=i.data;if("worker-ready"===s.type)return r.postMessage({type:"connectRPC",config:e}),void clearTimeout(n);"initialized"===s.type?(s.config=Object.assign({},e,s.config),s.origin=window.location.origin,s.peer_id=a):"imjoy_remote_api_ready"===s.type?window.dispatchEvent(new CustomEvent("imjoy_remote_api_ready",{detail:null})):"cacheRequirements"===s.type&&"function"==typeof cache_requirements?cache_requirements(s.requirements):"disconnect"===s.type?r.terminate():s.__transferables__&&(o=s.__transferables__,delete s.__transferables__),t?t.postMessage(s):parent.postMessage(s,e.target_origin||"*",o)})),(t||window).addEventListener("message",(function(n){if("message"===n.type&&(t||"*"===e.target_origin||n.origin===e.target_origin)){let t=void 0;const i=n.data;i.__transferables__&&(t=i.__transferables__,delete i.__transferables__),i.peer_id===a?r.postMessage(i,t):e.debug&&console.log(`connection peer id mismatch ${i.peer_id} !== ${a}`)}}))}(e)}catch(t){Object(o.a)(e)}else{if(!["rpc-window","rpc-worker","iframe","window"].includes(e.type))return console.error("Unsupported plugin type: "+e.type),void r("Unsupported plugin type: "+e.type);Object(o.a)(e)}globalThis.addEventListener("imjoy_remote_api_ready",n)}else _()?Object(o.a)(e):r(new Error("imjoy-rpc should only run inside an iframe or a webworker."))})}r.d(t,"VERSION",(function(){return c.a}))},function(e,t,r){e.exports=function(){return r(18)('!function(e){var t={};function r(n){if(t[n])return t[n].exports;var i=t[n]={i:n,l:!1,exports:{}};return e[n].call(i.exports,i,i.exports,r),i.l=!0,i.exports}r.m=e,r.c=t,r.d=function(e,t,n){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var i in e)r.d(n,i,function(t){return e[t]}.bind(null,i));return n},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=3)}([function(module,__webpack_exports__,__webpack_require__){"use strict";function randId(){return Math.random().toString(36).substr(2,10)+(new Date).getTime()}__webpack_require__.d(__webpack_exports__,"d",(function(){return randId})),__webpack_require__.d(__webpack_exports__,"b",(function(){return dtypeToTypedArray})),__webpack_require__.d(__webpack_exports__,"c",(function(){return loadRequirementsInWebworker})),__webpack_require__.d(__webpack_exports__,"e",(function(){return typedArrayToDtype})),__webpack_require__.d(__webpack_exports__,"a",(function(){return MessageEmitter}));const dtypeToTypedArray={int8:Int8Array,int16:Int16Array,int32:Int32Array,uint8:Uint8Array,uint16:Uint16Array,uint32:Uint32Array,float32:Float32Array,float64:Float64Array,array:Array};async function loadRequirementsInWindow(e){function t(e){return new Promise((t,r)=>{var n=document.createElement("script");n.src=e,n.type="text/javascript",n.onload=t,n.onreadystatechange=function(){"loaded"!==this.readyState&&"complete"!==this.readyState||t()},n.onerror=r,document.head.appendChild(n)})}async function r(){for(var e=Array.prototype.slice.call(arguments),r=e.length,n=0;n<r;n++)await t(e[n])}if(e&&(Array.isArray(e)||"string"==typeof e))try{var n;if(e="string"==typeof e?[e]:e,!Array.isArray(e))throw"unsupported requirements definition";for(var i=0;i<e.length;i++)e[i].toLowerCase().endsWith(".css")||e[i].startsWith("css:")?(e[i].startsWith("css:")&&(e[i]=e[i].slice(4)),(n=document.createElement("link")).rel="stylesheet",n.href=e[i],document.head.appendChild(n)):e[i].toLowerCase().endsWith(".mjs")||e[i].startsWith("mjs:")?(e[i].startsWith("mjs:")&&(e[i]=e[i].slice(4)),await import(e[i])):e[i].toLowerCase().endsWith(".js")||e[i].startsWith("js:")?(e[i].startsWith("js:")&&(e[i]=e[i].slice(3)),await r(e[i])):e[i].startsWith("http")?await r(e[i]):e[i].startsWith("cache:")||console.log("Unprocessed requirements url: "+e[i])}catch(t){throw"failed to import required scripts: "+e.toString()}}async function loadRequirementsInWebworker(e){if(e&&(Array.isArray(e)||"string"==typeof e))try{Array.isArray(e)||(e=[e]);for(var t=0;t<e.length;t++){if(e[t].toLowerCase().endsWith(".css")||e[t].startsWith("css:"))throw"unable to import css in a webworker";e[t].toLowerCase().endsWith(".js")||e[t].startsWith("js:")?(e[t].startsWith("js:")&&(e[t]=e[t].slice(3)),importScripts(e[t])):e[t].startsWith("http")?importScripts(e[t]):e[t].startsWith("cache:")||console.log("Unprocessed requirements url: "+e[t])}}catch(t){throw"failed to import required scripts: "+e.toString()}}function loadRequirements(e){return"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope?loadRequirementsInWebworker(e):loadRequirementsInWindow(e)}function normalizeConfig(e){return e.version=e.version||"0.1.0",e.description=e.description||`[TODO: add description for ${e.name} ]`,e.type=e.type||"rpc-window",e.id=e.id||randId(),e.target_origin=e.target_origin||"*",e.allow_execution=e.allow_execution||!1,e=Object.keys(e).reduce((t,r)=>("function"!=typeof e[r]&&(t[r]=e[r]),t),{})}const typedArrayToDtypeMapping={Int8Array:"int8",Int16Array:"int16",Int32Array:"int32",Uint8Array:"uint8",Uint16Array:"uint16",Uint32Array:"uint32",Float32Array:"float32",Float64Array:"float64",Array:"array"},typedArrayToDtypeKeys=[];for(const arrType of Object.keys(typedArrayToDtypeMapping))typedArrayToDtypeKeys.push(eval(arrType));function typedArrayToDtype(e){let t=typedArrayToDtypeMapping[e.constructor.name];if(!t){const r=Object.getPrototypeOf(e);for(const e of typedArrayToDtypeKeys)if(r instanceof e){t=typedArrayToDtypeMapping[e.name];break}}return t}function cacheUrlInServiceWorker(e){return new Promise((function(t,r){const n={command:"add",url:e};if(!navigator.serviceWorker||!navigator.serviceWorker.register)return void r("Service worker is not supported.");const i=new MessageChannel;i.port1.onmessage=function(e){e.data&&e.data.error?r(e.data.error):t(e.data&&e.data.result)},navigator.serviceWorker&&navigator.serviceWorker.controller?navigator.serviceWorker.controller.postMessage(n,[i.port2]):r("Service worker controller is not available")}))}async function cacheRequirements(e){e=e||[],Array.isArray(e)||(e=[e]);for(let t of e)t.startsWith("js:")&&(t=t.slice(3)),t.startsWith("css:")&&(t=t.slice(4)),t.startsWith("cache:")&&(t=t.slice(6)),t.startsWith("http")&&await cacheUrlInServiceWorker(t).catch(e=>{console.error(e)})}function setupServiceWorker(e,t,r){if("serviceWorker"in navigator){if(e=e||"/",navigator.serviceWorker.register(e+"plugin-service-worker.js").then((function(e){console.log("ServiceWorker registration successful with scope: ",e.scope)}),(function(e){console.log("ServiceWorker registration failed: ",e)})),t=t||"*",(r=r||cacheRequirements)&&"function"!=typeof r)throw new Error("config.cache_requirements must be a function");window.addEventListener("message",(function(e){if("*"===t||e.origin===t){const t=e.data;"cacheRequirements"===t.type&&r(t.requirements)}}))}}function urlJoin(...e){return e.join("/").replace(/[\\/]+/g,"/").replace(/^(.+):\\//,"$1://").replace(/^file:/,"file:/").replace(/\\/(\\?|&|#[^!])/g,"$1").replace(/\\?/g,"&").replace("&","?")}class MessageEmitter{constructor(e){this._event_handlers={},this._once_handlers={},this._debug=e}emit(){throw new Error("emit is not implemented")}on(e,t){this._event_handlers[e]||(this._event_handlers[e]=[]),this._event_handlers[e].push(t)}once(e,t){t.___event_run_once=!0,this.on(e,t)}off(e,t){if(e||t){if(e&&!t)this._event_handlers[e]&&(this._event_handlers[e]=[]);else if(this._event_handlers[e]){const r=this._event_handlers[e].indexOf(t);r>=0&&this._event_handlers[e].splice(r,1)}}else this._event_handlers={}}_fire(e,t){if(this._event_handlers[e])for(var r=this._event_handlers[e].length;r--;){const n=this._event_handlers[e][r];try{n(t)}catch(e){console.error(e)}finally{n.___event_run_once&&this._event_handlers[e].splice(r,1)}}else this._debug&&console.warn("unhandled event",e,t)}}},function(e,t,r){"use strict";r.d(t,"a",(function(){return i})),r.d(t,"b",(function(){return c}));var n=r(0);const i="0.2.3",o=Object.getPrototypeOf(Object.getPrototypeOf(new Uint8Array)).constructor;function s(e,t){const r=new Uint8Array(e.byteLength+t.byteLength);return r.set(new Uint8Array(e),0),r.set(new Uint8Array(t),e.byteLength),r.buffer}function a(e,t){if(!t)throw new Error("undefined index");return"string"==typeof t?a(e,t.split(".")):0===t.length?e:a(e[t[0]],t.slice(1))}class c extends n.a{constructor(e,t,r){super(t&&t.debug),this._connection=e,this.config=t||{},this._codecs=r||{},this._object_store={},this._method_weakmap=new WeakMap,this._object_weakmap=new WeakMap,this._local_api=null,this._remote_set=!1;const n=this.config.name;this._connection.execute=this._connection.execute||function(){throw new Error(`connection.execute not implemented (in "${n}")`)},this._store=new _,this._method_refs=new _,this._method_refs.onReady(()=>{this._fire("remoteIdle")}),this._method_refs.onBusy(()=>{this._fire("remoteBusy")}),this._setupMessageHanlders()}init(){this._connection.emit({type:"initialized",config:this.config,peer_id:this._connection.peer_id})}setConfig(e){if(e)for(const t of Object.keys(e))this.config[t]=e[t]}getRemoteCallStack(){return this._method_refs.getStack()}getRemote(){return this._remote_interface}setInterface(e,t){if(t=t||{},this.config.name=t.name||this.config.name,this.config.description=t.description||this.config.description,this.config.forwarding_functions)for(let t of this.config.forwarding_functions){const r=this._remote_interface;r[t]&&(e.constructor===Object?e[t]||(e[t]=(...e)=>{r[t](...e)}):e.constructor.constructor===Function&&(e.constructor.prototype[t]||(e.constructor.prototype[t]=(...e)=>{r[t](...e)})))}return this._local_api=e,this._remote_set?this.sendInterface():this._fire("interfaceAvailable"),new Promise(e=>{this.once("interfaceSetAsRemote",e)})}sendInterface(){if(!this._local_api)throw new Error("interface is not set.");this._encode(this._local_api,!0).then(e=>{this._connection.emit({type:"setInterface",api:e})})}_disposeObject(e){if(!this._object_store[e])throw new Error(`Object (id=${e}) not found.`);delete this._object_store[e]}disposeObject(e){return new Promise((t,r)=>{if(!this._object_weakmap.has(e))throw new Error("Invalid object");{const n=this._object_weakmap.get(e);this._connection.once("disposed",e=>{e.error?r(new Error(e.error)):t()}),this._connection.emit({type:"disposeObject",object_id:n})}})}_setupMessageHanlders(){this._connection.on("init",this.init),this._connection.on("execute",e=>{Promise.resolve(this._connection.execute(e.code)).then(()=>{this._connection.emit({type:"executed"})}).catch(e=>{console.error(e),this._connection.emit({type:"executed",error:String(e)})})}),this._connection.on("method",async e=>{let t,r,n,i,o,s;try{e.promise&&([t,r]=await this._unwrap(e.promise,!1));const c=this._object_store[e.object_id];if(n=a(c,e.name),e.name.includes(".")){const t=e.name.split(".");i=a(c,t.slice(0,t.length-1).join("."))}else i=c;o=await this._unwrap(e.args,!0),e.promise?(s=n.apply(i,o),s instanceof Promise||n.constructor&&"AsyncFunction"===n.constructor.name?s.then(t).catch(r):t(s)):n.apply(i,o)}catch(e){console.error(this.config.name,e),r&&r(e)}}),this._connection.on("callback",async e=>{let t,r,n,i,o;try{if(e.promise&&([t,r]=await this._unwrap(e.promise,!1)),e.promise){if(n=this._store.fetch(e.id),i=await this._unwrap(e.args,!0),!n)throw new Error("Callback function can only called once, if you want to call a function for multiple times, please make it as a plugin api function. See https://imjoy.io/docs for more details.");o=n.apply(null,i),o instanceof Promise||n.constructor&&"AsyncFunction"===n.constructor.name?o.then(t).catch(r):t(o)}else{if(n=this._store.fetch(e.id),i=await this._unwrap(e.args,!0),!n)throw new Error("Please notice that callback function can only called once, if you want to call a function for multiple times, please make it as a plugin api function. See https://imjoy.io/docs for more details.");n.apply(null,i)}}catch(e){console.error(this.config.name,e),r&&r(e)}}),this._connection.on("disposeObject",e=>{try{this._disposeObject(e.object_id),this._connection.emit({type:"disposed"})}catch(e){console.error(e),this._connection.emit({type:"disposed",error:String(e)})}}),this._connection.on("setInterface",e=>{this._setRemoteInterface(e.api)}),this._connection.on("getInterface",()=>{this._fire("getInterface"),this._local_api?this.sendInterface():this.once("interfaceAvailable",()=>{this.sendInterface()})}),this._connection.on("interfaceSetAsRemote",()=>{this._remote_set=!0,this._fire("interfaceSetAsRemote")}),this._connection.on("disconnect",()=>{this._fire("beforeDisconnect"),this._connection.disconnect(),this._fire("disconnected")})}requestRemote(){this._connection.emit({type:"getInterface"})}_ndarray(e,t,r){const i=Object(n.e)(e);if(r&&r!==i)throw"dtype doesn\'t match the type of the array: "+i+" != "+r;return t=t||[e.length],{_rtype:"ndarray",_rvalue:e.buffer,_rshape:t,_rdtype:i}}_setRemoteInterface(e){this._decode(e).then(e=>{if(this._remote_interface){for(let e in this._remote_interface)delete this._remote_interface[e];Object.assign(this._remote_interface,e)}else this._remote_interface=e;this._fire("remoteReady"),this._reportRemoteSet()})}_genRemoteMethod(e,t,r){const n=this,i=function(){return new Promise(async(i,o)=>{let s=null;try{s=n._method_refs.put(r?r+"/"+t:t);const a=function(){return null!==s&&n._method_refs.fetch(s),i.apply(this,arguments)},c=function(){return null!==s&&n._method_refs.fetch(s),o.apply(this,arguments)},_=await n._wrap([a,c]);a.__promise_pair=_[1]._rvalue,c.__promise_pair=_[0]._rvalue;let l=Array.prototype.slice.call(arguments);const f=l.length,d=f>0&&"object"==typeof l[f-1]&&null!==l[f-1]&&l[f-1]._rkwargs;d&&delete l[f-1]._rkwargs,l="register"===t||"registerService"===t||"register_service"===t||"export"===t||"on"===t?await n._wrap(l,!0):await n._wrap(l);const p=l.__transferables__;p&&delete l.__transferables__,n._connection.emit({type:"method",target_id:e,name:t,object_id:r,args:l,promise:_,with_kwargs:d},p)}catch(e){s&&n._method_refs.fetch(s),o(`Failed to exectue remote method (interface: ${r||n.id}, method: ${t}), error: ${e}`)}})};return i.__remote_method=!0,i}_reportRemoteSet(){this._connection.emit({type:"interfaceSetAsRemote"})}async _encode(e,t,r){const i=typeof e;if("number"===i||"string"===i||"boolean"===i||null==e||e instanceof ArrayBuffer)return e;let s;if("function"==typeof e){if(t){if(!r)throw new Error("objectId is not specified.");s={_rtype:"interface",_rtarget_id:this._connection.peer_id,_rintf:r,_rvalue:t},this._method_weakmap.set(e,s)}else if(this._method_weakmap.has(e))s=this._method_weakmap.get(e);else{const t=this._store.put(e);s={_rtype:"callback",_rtarget_id:this._connection.peer_id,_rname:e.constructor&&e.constructor.name||t,_rvalue:t}}return s}if(e.constructor instanceof Object&&e._rtype){if(e._rintf){const n=e._rtype;delete e._rtype,s=await this._encode(e,t,r),s._rtype=n}else s=e;return s}const a=[],c=e._transfer,_=Array.isArray(e);for(let n of Object.keys(this._codecs)){const i=this._codecs[n];if(i.encoder&&e instanceof i.type){let n=await Promise.resolve(i.encoder(e));if(n&&!n._rtype&&(n._rtype=i.name),n&&n._rintf){const e=n._rtype;delete n._rtype,n=await this._encode(n,t,r),n._rtype=e}return s=n,s}}if("undefined"!=typeof tf&&tf.Tensor&&e instanceof tf.Tensor){const t=e.dataSync();(e._transfer||c)&&(a.push(t.buffer),delete e._transfer),s={_rtype:"ndarray",_rvalue:t.buffer,_rshape:e.shape,_rdtype:e.dtype}}else if("undefined"!=typeof nj&&nj.NdArray&&e instanceof nj.NdArray){const t=Object(n.e)(e.selection.data);(e._transfer||c)&&(a.push(e.selection.data.buffer),delete e._transfer),s={_rtype:"ndarray",_rvalue:e.selection.data.buffer,_rshape:e.shape,_rdtype:t}}else if(e instanceof Error)console.error(e),s={_rtype:"error",_rvalue:e.toString()};else if("undefined"!=typeof File&&e instanceof File)s={_rtype:"file",_rvalue:e,_rpath:e._path||e.webkitRelativePath};else if(e!==Object(e)||e instanceof Boolean||e instanceof String||e instanceof Date||e instanceof RegExp||e instanceof ImageData||"undefined"!=typeof FileList&&e instanceof FileList||"undefined"!=typeof FileSystemDirectoryHandle&&e instanceof FileSystemDirectoryHandle||"undefined"!=typeof FileSystemFileHandle&&e instanceof FileSystemFileHandle||"undefined"!=typeof FileSystemHandle&&e instanceof FileSystemHandle||"undefined"!=typeof FileSystemWritableFileStream&&e instanceof FileSystemWritableFileStream)s=e;else if("undefined"!=typeof File&&e instanceof File)s={_rtype:"file",_rname:e.name,_rmime:e.type,_rvalue:e,_rpath:e._path||e.webkitRelativePath};else if(e instanceof Blob)s={_rtype:"blob",_rvalue:e};else if(e instanceof o){(e._transfer||c)&&(a.push(e.buffer),delete e._transfer);const t=Object(n.e)(e);s={_rtype:"typedarray",_rvalue:e.buffer,_rdtype:t}}else if(e instanceof DataView)(e._transfer||c)&&(a.push(e.buffer),delete e._transfer),s={_rtype:"memoryview",_rvalue:e.buffer};else if(e instanceof Set)s={_rtype:"set",_rvalue:await this._encode(Array.from(e),t)};else if(e instanceof Map)s={_rtype:"orderedmap",_rvalue:await this._encode(Array.from(e),t)};else if(e.constructor instanceof Object||Array.isArray(e)){let i;if(s=_?[]:{},e.constructor===Object||Array.isArray(e))i=Object.keys(e);else{if(e.constructor===Function)throw new Error("Please instantiate the class before exportting it.");if(e.constructor.constructor!==Function)throw Error("Unsupported interface type");i=Object.getOwnPropertyNames(Object.getPrototypeOf(e)).concat(Object.keys(e)),t=!0}let o=!1;if(e._rintf||t){r||(r="string"==typeof e._rintf&&e._rintf.length>0?e._rintf:Object(n.d)(),this._object_store[r]&&console.warn("Overwritting interface object with the same id: "+r),this._object_store[r]=e);for(let n of i)"constructor"!==n&&(n.startsWith("_")||(s[n]=await this._encode(e[n],"string"==typeof t?t+"."+n:n,r),"function"==typeof e[n]&&(o=!0)));o&&(s._rintf=r),e.on&&"function"==typeof e.on&&e.on("close",()=>{delete this._object_store[r]})}else for(let t of i)["hasOwnProperty","constructor"].includes(t)||(s[t]=await this._encode(e[t]))}else{if("object"!=typeof e)throw"imjoy-rpc: Unsupported data type:"+e;{const t=Object.getOwnPropertyNames(Object.getPrototypeOf(e)).concat(Object.keys(e)),r=Object(n.d)();for(let r of t)["hasOwnProperty","constructor"].includes(r)||(s[r]=await this._encode(e[r],r,s));s._rintf=r}}if(a.length>0&&(s.__transferables__=a),!s)throw new Error("Failed to encode object");return s}async _decode(e,t){if(!e)return e;let r;if(e._rtype)if(this._codecs[e._rtype]&&this._codecs[e._rtype].decoder){if(e._rintf){const r=e._rtype;delete e._rtype,(e=await this._decode(e,t))._rtype=r}r=await Promise.resolve(this._codecs[e._rtype].decoder(e))}else if("callback"===e._rtype)r=this._genRemoteCallback(e._rtarget_id,e._rvalue,t);else if("interface"===e._rtype)r=this._genRemoteMethod(e._rtarget_id,e._rvalue,e._rintf);else if("ndarray"===e._rtype)if("undefined"!=typeof nj&&nj.array)Array.isArray(e._rvalue)&&(e._rvalue=e._rvalue.reduce(s)),r=nj.array(new Uint8(e._rvalue),e._rdtype).reshape(e._rshape);else if("undefined"!=typeof tf&&tf.Tensor){Array.isArray(e._rvalue)&&(e._rvalue=e._rvalue.reduce(s));const t=n.b[e._rdtype];r=tf.tensor(new t(e._rvalue),e._rshape,e._rdtype)}else r=e;else if("error"===e._rtype)r=new Error(e._rvalue);else if("file"===e._rtype)e._rvalue instanceof File?(r=e._rvalue,r._path=e._rpath):(r=new File([e._rvalue],e._rname,{type:e._rmime}),r._path=e._rpath);else if("typedarray"===e._rtype){const t=n.b[e._rdtype];if(!t)throw new Error("unsupported dtype: "+e._rdtype);r=new t(e._rvalue)}else if("memoryview"===e._rtype)r=new DataView(e._rvalue);else if("blob"===e._rtype)r=e._rvalue instanceof Blob?e._rvalue:new Blob([e._rvalue],{type:e._rmime});else if("orderedmap"===e._rtype)r=new Map(await this._decode(e._rvalue,t));else if("set"===e._rtype)r=new Set(await this._decode(e._rvalue,t));else if(e._rintf){const n=e._rtype;delete e._rtype,r=await this._decode(e,t),r._rtype=n}else r=e;else if(e.constructor===Object||Array.isArray(e)){const n=Array.isArray(e);r=n?[]:{};for(let i of Object.keys(e))if(n||e.hasOwnProperty(i)){const n=e[i];r[i]=await this._decode(n,t)}}else r=e;if(void 0===r)throw new Error("Failed to decode object");return e._rintf&&this._object_weakmap.set(r,e._rintf),r}async _wrap(e,t){return await this._encode(e,t)}async _unwrap(e,t){return await this._decode(e,t)}_genRemoteCallback(e,t,r){const n=this;let i;return r?(i=function(){return new Promise(async(r,i)=>{const o=await n._wrap(Array.prototype.slice.call(arguments)),s=o.length,a=s>0&&"object"==typeof o[s-1]&&null!==o[s-1]&&o[s-1]._rkwargs;a&&delete o[s-1]._rkwargs;const c=o.__transferables__;c&&delete o.__transferables__;const _=await n._wrap([r,i]);r.__promise_pair=_[1]._rvalue,i.__promise_pair=_[0]._rvalue;try{n._connection.emit({type:"callback",target_id:e,id:t,args:o,promise:_,with_kwargs:a},c)}catch(e){i(`Failed to exectue remote callback ( id: ${t}).`)}})},i):(i=async function(){const r=await n._wrap(Array.prototype.slice.call(arguments)),i=r.length,o=i>0&&"object"==typeof r[i-1]&&null!==r[i-1]&&r[i-1]._rkwargs;o&&delete r[i-1]._rkwargs;const s=r.__transferables__;return s&&delete r.__transferables__,n._connection.emit({type:"callback",target_id:e,id:t,args:r,with_kwargs:o},s)},i)}reset(){this._event_handlers={},this._once_handlers={},this._remote_interface=null,this._object_store={},this._method_weakmap=new WeakMap,this._object_weakmap=new WeakMap,this._local_api=null,this._store=new _,this._method_refs=new _}disconnect(){this._connection.emit({type:"disconnect"}),this.reset(),setTimeout(()=>{this._connection.disconnect()},2e3)}}class _{constructor(){this._store={},this._indices=[0],this._readyHandler=function(){},this._busyHandler=function(){},this._readyHandler()}onReady(e){this._readyHandler=e||function(){}}onBusy(e){this._busyHandler=e||function(){}}getStack(){return Object.keys(this._store).length}_genId(){let e;return e=1===this._indices.length?this._indices[0]++:this._indices.shift(),e}_releaseId(e){for(let t=0;t<this._indices.length;t++)if(e<this._indices[t]){this._indices.splice(t,0,e);break}for(let e=this._indices.length-1;e>=0&&this._indices[e]-1===this._indices[e-1];e--)this._indices.pop()}put(e){this._busyHandler&&0===Object.keys(this._store).length&&this._busyHandler();const t=this._genId();return this._store[t]=e,t}fetch(e){const t=this._store[e];return t&&!t.__remote_method&&(delete this._store[e],this._releaseId(e),this._readyHandler&&0===Object.keys(this._store).length&&this._readyHandler()),t&&t.__promise_pair&&this.fetch(t.__promise_pair),t}}},function(e,t,r){"use strict";r.d(t,"a",(function(){return i}));var n=r(1);function i(e,t){t=t||{};const r={},i=new n.b(e,t,r);i.on("getInterface",(function(){a()})),i.on("remoteReady",(function(){const e=i.getRemote()||{};e.registerCodec=function(e){if(!e.name||!e.encoder&&!e.decoder)throw new Error("Invalid codec format, please make sure you provide a name, type, encoder and decoder.");if(e.type)for(let t of Object.keys(r))r[t].type!==e.type&&t!==e.name||(delete r[t],console.warn("Remove duplicated codec: "+t));r[e.name]=e},e.init=function(e){i.setInterface({setup(){}},e)},e.disposeObject=function(e){i.disposeObject(e)},e.export=function(e,t){i.setInterface(e,t)},e.onLoad=function(e){e=c(e),o?e():s.push(e)},e.dispose=function(e){i.disconnect()},e._rpc=i,"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope?(self.api=e,self.postMessage({type:"imjoy_remote_api_ready"}),self.dispatchEvent(new CustomEvent("imjoy_remote_api_ready",{detail:e}))):window.dispatchEvent(new CustomEvent("imjoy_remote_api_ready",{detail:e}))}));let o=!1;const s=[],a=function(){if(!o){let e;for(o=!0;e=s.pop();)e()}},c=function(e){const t=typeof e;if("function"!==t){throw new Error("A function may only be subsribed to the event, "+t+" was provided instead")}return e};return i}},function(module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.r(__webpack_exports__);var _pluginCore_js__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__(2),_rpc_js__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__(1),_utils_js__WEBPACK_IMPORTED_MODULE_2__=__webpack_require__(0);if(!("undefined"!=typeof WorkerGlobalScope&&self&&self instanceof WorkerGlobalScope))throw new Error("This script can only loaded in a webworker");async function executeEsModule(e){const t="data:text/javascript;charset=utf-8,"+encodeURIComponent(e);await import(t)}class Connection extends _utils_js__WEBPACK_IMPORTED_MODULE_2__.a{constructor(e){super(e&&e.debug),this.config=e||{}}connect(){self.addEventListener("message",e=>{this._fire(e.data.type,e.data)}),this.emit({type:"initialized",config:this.config})}disconnect(){this._fire("beforeDisconnect"),self.close(),this._fire("disconnected")}emit(e){let t=void 0;e.__transferables__&&(t=e.__transferables__,delete e.__transferables__),self.postMessage(e,t)}async execute(code){if("requirements"===code.type)await Object(_utils_js__WEBPACK_IMPORTED_MODULE_2__.c)(code.requirements);else{if("script"!==code.type)throw"unsupported code type.";try{"module"===code.attrs.type?await executeEsModule(code.content):eval(code.content)}catch(e){throw console.error(e.message,e.stack),e}}"requirements"===code.type&&self.postMessage({type:"cacheRequirements",requirements:code.requirements})}}const config={type:"web-worker",dedicated_thread:!0,allow_execution:!0,lang:"javascript",api_version:_rpc_js__WEBPACK_IMPORTED_MODULE_1__.a},conn=new Connection(config);conn.on("connectRPC",e=>{Object(_pluginCore_js__WEBPACK_IMPORTED_MODULE_0__.a)(conn,Object.assign(e.config,config))}),conn.connect(),self.postMessage({type:"worker-ready"})}]);\n//# sourceMappingURL=plugin.webworker.js.map',null)}},,,function(e,t,r){"use strict";var n=window.URL||window.webkitURL;e.exports=function(e,t){try{try{var r;try{(r=new(window.BlobBuilder||window.WebKitBlobBuilder||window.MozBlobBuilder||window.MSBlobBuilder)).append(e),r=r.getBlob()}catch(t){r=new Blob([e])}return new Worker(n.createObjectURL(r))}catch(t){return new Worker("data:application/javascript,"+encodeURIComponent(e))}}catch(e){if(!t)throw Error("Inline worker is not supported");return new Worker(t)}}}])}));
//# sourceMappingURL=imjoy-rpc.min.js.map