-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhypha-rpc.min.js
More file actions
2 lines (2 loc) · 49 KB
/
hypha-rpc.min.js
File metadata and controls
2 lines (2 loc) · 49 KB
1
2
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define("hyphaRPC",[],t):"object"==typeof exports?exports.hyphaRPC=t():e.hyphaRPC=t()}(window,(function(){return function(e){var t={};function r(i){if(t[i])return t[i].exports;var n=t[i]={i:i,l:!1,exports:{}};return e[i].call(n.exports,n,n.exports,r),n.l=!0,n.exports}return r.m=e,r.c=t,r.d=function(e,t,i){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:i})},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 i=Object.create(null);if(r.r(i),Object.defineProperty(i,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var n in e)r.d(i,n,function(t){return e[t]}.bind(null,n));return i},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=11)}({0: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__,"e",(function(){return randId})),__webpack_require__.d(__webpack_exports__,"c",(function(){return dtypeToTypedArray})),__webpack_require__.d(__webpack_exports__,"d",(function(){return loadRequirements})),__webpack_require__.d(__webpack_exports__,"f",(function(){return typedArrayToDtype})),__webpack_require__.d(__webpack_exports__,"b",(function(){return assert})),__webpack_require__.d(__webpack_exports__,"g",(function(){return waitFor})),__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 i=document.createElement("script");i.src=e,i.type="text/javascript",i.onload=t,i.onreadystatechange=function(){"loaded"!==this.readyState&&"complete"!==this.readyState||t()},i.onerror=r,document.head.appendChild(i)})}async function r(){for(var e=Array.prototype.slice.call(arguments),r=e.length,i=0;i<r;i++)await t(e[i])}if(e&&(Array.isArray(e)||"string"==typeof e))try{var i;if(e="string"==typeof e?[e]:e,!Array.isArray(e))throw"unsupported requirements definition";for(var n=0;n<e.length;n++)e[n].toLowerCase().endsWith(".css")||e[n].startsWith("css:")?(e[n].startsWith("css:")&&(e[n]=e[n].slice(4)),(i=document.createElement("link")).rel="stylesheet",i.href=e[n],document.head.appendChild(i)):e[n].toLowerCase().endsWith(".mjs")||e[n].startsWith("mjs:")?(e[n].startsWith("mjs:")&&(e[n]=e[n].slice(4)),await import(e[n])):e[n].toLowerCase().endsWith(".js")||e[n].startsWith("js:")?(e[n].startsWith("js:")&&(e[n]=e[n].slice(3)),await r(e[n])):e[n].startsWith("http")?await r(e[n]):e[n].startsWith("cache:")||console.log("Unprocessed requirements url: "+e[n])}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 i={command:"add",url:e};if(!navigator.serviceWorker||!navigator.serviceWorker.register)return void r("Service worker is not supported.");const n=new MessageChannel;n.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(i,[n.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 assert(e,t){if(!e)throw new Error(t||"Assertion failed")}function urlJoin(...e){return e.join("/").replace(/[\/]+/g,"/").replace(/^(.+):\//,"$1://").replace(/^file:/,"file:/").replace(/\/(\?|&|#[^!])/g,"$1").replace(/\?/g,"&").replace("&","?")}function waitFor(e,t,r){let i;return Promise.race([e,new Promise((e,n)=>i=setTimeout(()=>{n(r||"Timeout Error")},1e3*t))]).finally(()=>clearTimeout(i))}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 i=this._event_handlers[e][r];try{i(t)}catch(e){console.error(e)}finally{i.___event_run_once&&this._event_handlers[e].splice(r,1)}}else this._debug&&console.warn("unhandled event",e,t)}}},11:function(e,t,r){"use strict";r.r(t),r.d(t,"API_VERSION",(function(){return C})),r.d(t,"RPC",(function(){return N}));var i=r(0);function n(e){return(e<0?"-":"")+"0x"+Math.abs(e).toString(16).padStart(2,"0")}var s,o=function(e,t){this.type=e,this.data=t},a=(s=function(e,t){return(s=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])})(e,t)},function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e}s(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}),c=function(e){function t(r){var i=e.call(this,r)||this,n=Object.create(t.prototype);return Object.setPrototypeOf(i,n),Object.defineProperty(i,"name",{configurable:!0,enumerable:!1,value:t.name}),i}return a(t,e),t}(Error);function h(e,t,r){var i=Math.floor(r/4294967296),n=r;e.setUint32(t,i),e.setUint32(t+4,n)}function f(e,t){return 4294967296*e.getInt32(t)+e.getUint32(t+4)}var l={type:-1,encode:function(e){var t,r,i,n;return e instanceof Date?function(e){var t,r=e.sec,i=e.nsec;if(r>=0&&i>=0&&r<=17179869183){if(0===i&&r<=4294967295){var n=new Uint8Array(4);return(t=new DataView(n.buffer)).setUint32(0,r),n}var s=r/4294967296,o=4294967295&r;n=new Uint8Array(8);return(t=new DataView(n.buffer)).setUint32(0,i<<2|3&s),t.setUint32(4,o),n}return n=new Uint8Array(12),(t=new DataView(n.buffer)).setUint32(0,i),h(t,4,r),n}((t=e.getTime(),r=Math.floor(t/1e3),i=1e6*(t-1e3*r),n=Math.floor(i/1e9),{sec:r+n,nsec:i-1e9*n})):null},decode:function(e){var t=function(e){var t=new DataView(e.buffer,e.byteOffset,e.byteLength);switch(e.byteLength){case 4:return{sec:t.getUint32(0),nsec:0};case 8:var r=t.getUint32(0);return{sec:4294967296*(3&r)+t.getUint32(4),nsec:r>>>2};case 12:return{sec:f(t,4),nsec:t.getUint32(0)};default:throw new c("Unrecognized data size for timestamp (expected 4, 8, or 12): "+e.length)}}(e);return new Date(1e3*t.sec+t.nsec/1e6)}},u=function(){function e(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(l)}return e.prototype.register=function(e){var t=e.type,r=e.encode,i=e.decode;if(t>=0)this.encoders[t]=r,this.decoders[t]=i;else{var n=1+t;this.builtInEncoders[n]=r,this.builtInDecoders[n]=i}},e.prototype.tryToEncode=function(e,t){for(var r=0;r<this.builtInEncoders.length;r++){if(null!=(i=this.builtInEncoders[r]))if(null!=(n=i(e,t)))return new o(-1-r,n)}for(r=0;r<this.encoders.length;r++){var i,n;if(null!=(i=this.encoders[r]))if(null!=(n=i(e,t)))return new o(r,n)}return e instanceof o?e:null},e.prototype.decode=function(e,t,r){var i=t<0?this.builtInDecoders[-1-t]:this.decoders[t];return i?i(e,t,r):new o(t,e)},e.defaultCodec=new e,e}(),d=("undefined"==typeof process||"never"!==process.env.TEXT_ENCODING)&&"undefined"!=typeof TextEncoder&&"undefined"!=typeof TextDecoder;function p(e){for(var t=e.length,r=0,i=0;i<t;){var n=e.charCodeAt(i++);if(0!=(4294967168&n))if(0==(4294965248&n))r+=2;else{if(n>=55296&&n<=56319&&i<t){var s=e.charCodeAt(i);56320==(64512&s)&&(++i,n=((1023&n)<<10)+(1023&s)+65536)}r+=0==(4294901760&n)?3:4}else r++}return r}var _=d?new TextEncoder:void 0,y=d?"undefined"!=typeof process&&"force"!==process.env.TEXT_ENCODING?200:0:4294967295;var w=(null==_?void 0:_.encodeInto)?function(e,t,r){_.encodeInto(e,t.subarray(r))}:function(e,t,r){t.set(_.encode(e),r)};function g(e,t,r){for(var i=t,n=i+r,s=[],o="";i<n;){var a=e[i++];if(0==(128&a))s.push(a);else if(192==(224&a)){var c=63&e[i++];s.push((31&a)<<6|c)}else if(224==(240&a)){c=63&e[i++];var h=63&e[i++];s.push((31&a)<<12|c<<6|h)}else if(240==(248&a)){var f=(7&a)<<18|(c=63&e[i++])<<12|(h=63&e[i++])<<6|63&e[i++];f>65535&&(f-=65536,s.push(f>>>10&1023|55296),f=56320|1023&f),s.push(f)}else s.push(a);s.length>=4096&&(o+=String.fromCharCode.apply(String,s),s.length=0)}return s.length>0&&(o+=String.fromCharCode.apply(String,s)),o}var m=d?new TextDecoder:null,v=d?"undefined"!=typeof process&&"force"!==process.env.TEXT_DECODER?200:0:4294967295;function b(e){return e instanceof Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e instanceof ArrayBuffer?new Uint8Array(e):Uint8Array.from(e)}var U=function(){function e(e,t){void 0===e&&(e=16),void 0===t&&(t=16),this.maxKeyLength=e,this.maxLengthPerKey=t,this.hit=0,this.miss=0,this.caches=[];for(var r=0;r<this.maxKeyLength;r++)this.caches.push([])}return e.prototype.canBeCached=function(e){return e>0&&e<=this.maxKeyLength},e.prototype.find=function(e,t,r){e:for(var i=0,n=this.caches[r-1];i<n.length;i++){for(var s=n[i],o=s.bytes,a=0;a<r;a++)if(o[a]!==e[t+a])continue e;return s.str}return null},e.prototype.store=function(e,t){var r=this.caches[e.length-1],i={bytes:e,str:t};r.length>=this.maxLengthPerKey?r[Math.random()*r.length|0]=i:r.push(i)},e.prototype.decode=function(e,t,r){var i=this.find(e,t,r);if(null!=i)return this.hit++,i;this.miss++;var n=g(e,t,r),s=Uint8Array.prototype.slice.call(e,t,t+r);return this.store(s,n),n},e}(),x=function(e,t,r,i){return new(r||(r=Promise))((function(n,s){function o(e){try{c(i.next(e))}catch(e){s(e)}}function a(e){try{c(i.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((i=i.apply(e,t||[])).next())}))},j=function(e,t){var r,i,n,s,o={label:0,sent:function(){if(1&n[0])throw n[1];return n[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(s){return function(a){return function(s){if(r)throw new TypeError("Generator is already executing.");for(;o;)try{if(r=1,i&&(n=2&s[0]?i.return:s[0]?i.throw||((n=i.return)&&n.call(i),0):i.next)&&!(n=n.call(i,s[1])).done)return n;switch(i=0,n&&(s=[2&s[0],n.value]),s[0]){case 0:case 1:n=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,i=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!(n=o.trys,(n=n.length>0&&n[n.length-1])||6!==s[0]&&2!==s[0])){o=0;continue}if(3===s[0]&&(!n||s[1]>n[0]&&s[1]<n[3])){o.label=s[1];break}if(6===s[0]&&o.label<n[1]){o.label=n[1],n=s;break}if(n&&o.label<n[2]){o.label=n[2],o.ops.push(s);break}n[2]&&o.ops.pop(),o.trys.pop();continue}s=t.call(e,o)}catch(e){s=[6,e],i=0}finally{r=n=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,a])}}},A=function(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,r=e[Symbol.asyncIterator];return r?r.call(e):(e="function"==typeof __values?__values(e):e[Symbol.iterator](),t={},i("next"),i("throw"),i("return"),t[Symbol.asyncIterator]=function(){return this},t);function i(r){t[r]=e[r]&&function(t){return new Promise((function(i,n){(function(e,t,r,i){Promise.resolve(i).then((function(t){e({value:t,done:r})}),t)})(i,n,(t=e[r](t)).done,t.value)}))}}},S=function(e){return this instanceof S?(this.v=e,this):new S(e)},k=function(e,t,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i,n=r.apply(e,t||[]),s=[];return i={},o("next"),o("throw"),o("return"),i[Symbol.asyncIterator]=function(){return this},i;function o(e){n[e]&&(i[e]=function(t){return new Promise((function(r,i){s.push([e,t,r,i])>1||a(e,t)}))})}function a(e,t){try{(r=n[e](t)).value instanceof S?Promise.resolve(r.value.v).then(c,h):f(s[0][2],r)}catch(e){f(s[0][3],e)}var r}function c(e){a("next",e)}function h(e){a("throw",e)}function f(e,t){e(t),s.shift(),s.length&&a(s[0][0],s[0][1])}},O=new DataView(new ArrayBuffer(0)),E=new Uint8Array(O.buffer),I=function(){try{O.getInt8(0)}catch(e){return e.constructor}throw new Error("never reached")}(),T=new I("Insufficient data"),B=new U,W=function(){function e(e,t,r,i,n,s,o,a){void 0===e&&(e=u.defaultCodec),void 0===t&&(t=void 0),void 0===r&&(r=4294967295),void 0===i&&(i=4294967295),void 0===n&&(n=4294967295),void 0===s&&(s=4294967295),void 0===o&&(o=4294967295),void 0===a&&(a=B),this.extensionCodec=e,this.context=t,this.maxStrLength=r,this.maxBinLength=i,this.maxArrayLength=n,this.maxMapLength=s,this.maxExtLength=o,this.keyDecoder=a,this.totalPos=0,this.pos=0,this.view=O,this.bytes=E,this.headByte=-1,this.stack=[]}return e.prototype.reinitializeState=function(){this.totalPos=0,this.headByte=-1,this.stack.length=0},e.prototype.setBuffer=function(e){this.bytes=b(e),this.view=function(e){if(e instanceof ArrayBuffer)return new DataView(e);var t=b(e);return new DataView(t.buffer,t.byteOffset,t.byteLength)}(this.bytes),this.pos=0},e.prototype.appendBuffer=function(e){if(-1!==this.headByte||this.hasRemaining(1)){var t=this.bytes.subarray(this.pos),r=b(e),i=new Uint8Array(t.length+r.length);i.set(t),i.set(r,t.length),this.setBuffer(i)}else this.setBuffer(e)},e.prototype.hasRemaining=function(e){return this.view.byteLength-this.pos>=e},e.prototype.createExtraByteError=function(e){var t=this.view,r=this.pos;return new RangeError("Extra "+(t.byteLength-r)+" of "+t.byteLength+" byte(s) found at buffer["+e+"]")},e.prototype.decode=function(e){this.reinitializeState(),this.setBuffer(e);var t=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return t},e.prototype.decodeMulti=function(e){return j(this,(function(t){switch(t.label){case 0:this.reinitializeState(),this.setBuffer(e),t.label=1;case 1:return this.hasRemaining(1)?[4,this.doDecodeSync()]:[3,3];case 2:return t.sent(),[3,1];case 3:return[2]}}))},e.prototype.decodeAsync=function(e){var t,r,i,s;return x(this,void 0,void 0,(function(){var o,a,c,h,f,l,u,d;return j(this,(function(p){switch(p.label){case 0:o=!1,p.label=1;case 1:p.trys.push([1,6,7,12]),t=A(e),p.label=2;case 2:return[4,t.next()];case 3:if((r=p.sent()).done)return[3,5];if(c=r.value,o)throw this.createExtraByteError(this.totalPos);this.appendBuffer(c);try{a=this.doDecodeSync(),o=!0}catch(e){if(!(e instanceof I))throw e}this.totalPos+=this.pos,p.label=4;case 4:return[3,2];case 5:return[3,12];case 6:return h=p.sent(),i={error:h},[3,12];case 7:return p.trys.push([7,,10,11]),r&&!r.done&&(s=t.return)?[4,s.call(t)]:[3,9];case 8:p.sent(),p.label=9;case 9:return[3,11];case 10:if(i)throw i.error;return[7];case 11:return[7];case 12:if(o){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return[2,a]}throw l=(f=this).headByte,u=f.pos,d=f.totalPos,new RangeError("Insufficient data in parsing "+n(l)+" at "+d+" ("+u+" in the current buffer)")}}))}))},e.prototype.decodeArrayStream=function(e){return this.decodeMultiAsync(e,!0)},e.prototype.decodeStream=function(e){return this.decodeMultiAsync(e,!1)},e.prototype.decodeMultiAsync=function(e,t){return k(this,arguments,(function(){var r,i,n,s,o,a,c,h,f;return j(this,(function(l){switch(l.label){case 0:r=t,i=-1,l.label=1;case 1:l.trys.push([1,13,14,19]),n=A(e),l.label=2;case 2:return[4,S(n.next())];case 3:if((s=l.sent()).done)return[3,12];if(o=s.value,t&&0===i)throw this.createExtraByteError(this.totalPos);this.appendBuffer(o),r&&(i=this.readArraySize(),r=!1,this.complete()),l.label=4;case 4:l.trys.push([4,9,,10]),l.label=5;case 5:return[4,S(this.doDecodeSync())];case 6:return[4,l.sent()];case 7:return l.sent(),0==--i?[3,8]:[3,5];case 8:return[3,10];case 9:if(!((a=l.sent())instanceof I))throw a;return[3,10];case 10:this.totalPos+=this.pos,l.label=11;case 11:return[3,2];case 12:return[3,19];case 13:return c=l.sent(),h={error:c},[3,19];case 14:return l.trys.push([14,,17,18]),s&&!s.done&&(f=n.return)?[4,S(f.call(n))]:[3,16];case 15:l.sent(),l.label=16;case 16:return[3,18];case 17:if(h)throw h.error;return[7];case 18:return[7];case 19:return[2]}}))}))},e.prototype.doDecodeSync=function(){e:for(;;){var e=this.readHeadByte(),t=void 0;if(e>=224)t=e-256;else if(e<192)if(e<128)t=e;else if(e<144){if(0!==(i=e-128)){this.pushMapState(i),this.complete();continue e}t={}}else if(e<160){if(0!==(i=e-144)){this.pushArrayState(i),this.complete();continue e}t=[]}else{var r=e-160;t=this.decodeUtf8String(r,0)}else if(192===e)t=null;else if(194===e)t=!1;else if(195===e)t=!0;else if(202===e)t=this.readF32();else if(203===e)t=this.readF64();else if(204===e)t=this.readU8();else if(205===e)t=this.readU16();else if(206===e)t=this.readU32();else if(207===e)t=this.readU64();else if(208===e)t=this.readI8();else if(209===e)t=this.readI16();else if(210===e)t=this.readI32();else if(211===e)t=this.readI64();else if(217===e){r=this.lookU8();t=this.decodeUtf8String(r,1)}else if(218===e){r=this.lookU16();t=this.decodeUtf8String(r,2)}else if(219===e){r=this.lookU32();t=this.decodeUtf8String(r,4)}else if(220===e){if(0!==(i=this.readU16())){this.pushArrayState(i),this.complete();continue e}t=[]}else if(221===e){if(0!==(i=this.readU32())){this.pushArrayState(i),this.complete();continue e}t=[]}else if(222===e){if(0!==(i=this.readU16())){this.pushMapState(i),this.complete();continue e}t={}}else if(223===e){if(0!==(i=this.readU32())){this.pushMapState(i),this.complete();continue e}t={}}else if(196===e){var i=this.lookU8();t=this.decodeBinary(i,1)}else if(197===e){i=this.lookU16();t=this.decodeBinary(i,2)}else if(198===e){i=this.lookU32();t=this.decodeBinary(i,4)}else if(212===e)t=this.decodeExtension(1,0);else if(213===e)t=this.decodeExtension(2,0);else if(214===e)t=this.decodeExtension(4,0);else if(215===e)t=this.decodeExtension(8,0);else if(216===e)t=this.decodeExtension(16,0);else if(199===e){i=this.lookU8();t=this.decodeExtension(i,1)}else if(200===e){i=this.lookU16();t=this.decodeExtension(i,2)}else{if(201!==e)throw new c("Unrecognized type byte: "+n(e));i=this.lookU32();t=this.decodeExtension(i,4)}this.complete();for(var s=this.stack;s.length>0;){var o=s[s.length-1];if(0===o.type){if(o.array[o.position]=t,o.position++,o.position!==o.size)continue e;s.pop(),t=o.array}else{if(1===o.type){if(a=void 0,"string"!==(a=typeof t)&&"number"!==a)throw new c("The type of key must be string or number but "+typeof t);if("__proto__"===t)throw new c("The key __proto__ is not allowed");o.key=t,o.type=2;continue e}if(o.map[o.key]=t,o.readCount++,o.readCount!==o.size){o.key=null,o.type=1;continue e}s.pop(),t=o.map}}return t}var a},e.prototype.readHeadByte=function(){return-1===this.headByte&&(this.headByte=this.readU8()),this.headByte},e.prototype.complete=function(){this.headByte=-1},e.prototype.readArraySize=function(){var e=this.readHeadByte();switch(e){case 220:return this.readU16();case 221:return this.readU32();default:if(e<160)return e-144;throw new c("Unrecognized array type byte: "+n(e))}},e.prototype.pushMapState=function(e){if(e>this.maxMapLength)throw new c("Max length exceeded: map length ("+e+") > maxMapLengthLength ("+this.maxMapLength+")");this.stack.push({type:1,size:e,key:null,readCount:0,map:{}})},e.prototype.pushArrayState=function(e){if(e>this.maxArrayLength)throw new c("Max length exceeded: array length ("+e+") > maxArrayLength ("+this.maxArrayLength+")");this.stack.push({type:0,size:e,array:new Array(e),position:0})},e.prototype.decodeUtf8String=function(e,t){var r;if(e>this.maxStrLength)throw new c("Max length exceeded: UTF-8 byte length ("+e+") > maxStrLength ("+this.maxStrLength+")");if(this.bytes.byteLength<this.pos+t+e)throw T;var i,n=this.pos+t;return i=this.stateIsMapKey()&&(null===(r=this.keyDecoder)||void 0===r?void 0:r.canBeCached(e))?this.keyDecoder.decode(this.bytes,n,e):e>v?function(e,t,r){var i=e.subarray(t,t+r);return m.decode(i)}(this.bytes,n,e):g(this.bytes,n,e),this.pos+=t+e,i},e.prototype.stateIsMapKey=function(){return this.stack.length>0&&1===this.stack[this.stack.length-1].type},e.prototype.decodeBinary=function(e,t){if(e>this.maxBinLength)throw new c("Max length exceeded: bin length ("+e+") > maxBinLength ("+this.maxBinLength+")");if(!this.hasRemaining(e+t))throw T;var r=this.pos+t,i=this.bytes.subarray(r,r+e);return this.pos+=t+e,i},e.prototype.decodeExtension=function(e,t){if(e>this.maxExtLength)throw new c("Max length exceeded: ext length ("+e+") > maxExtLength ("+this.maxExtLength+")");var r=this.view.getInt8(this.pos+t),i=this.decodeBinary(e,t+1);return this.extensionCodec.decode(i,r,this.context)},e.prototype.lookU8=function(){return this.view.getUint8(this.pos)},e.prototype.lookU16=function(){return this.view.getUint16(this.pos)},e.prototype.lookU32=function(){return this.view.getUint32(this.pos)},e.prototype.readU8=function(){var e=this.view.getUint8(this.pos);return this.pos++,e},e.prototype.readI8=function(){var e=this.view.getInt8(this.pos);return this.pos++,e},e.prototype.readU16=function(){var e=this.view.getUint16(this.pos);return this.pos+=2,e},e.prototype.readI16=function(){var e=this.view.getInt16(this.pos);return this.pos+=2,e},e.prototype.readU32=function(){var e=this.view.getUint32(this.pos);return this.pos+=4,e},e.prototype.readI32=function(){var e=this.view.getInt32(this.pos);return this.pos+=4,e},e.prototype.readU64=function(){var e,t,r=(e=this.view,t=this.pos,4294967296*e.getUint32(t)+e.getUint32(t+4));return this.pos+=8,r},e.prototype.readI64=function(){var e=f(this.view,this.pos);return this.pos+=8,e},e.prototype.readF32=function(){var e=this.view.getFloat32(this.pos);return this.pos+=4,e},e.prototype.readF64=function(){var e=this.view.getFloat64(this.pos);return this.pos+=8,e},e}(),L={};function M(e,t){return void 0===t&&(t=L),new W(t.extensionCodec,t.context,t.maxStrLength,t.maxBinLength,t.maxArrayLength,t.maxMapLength,t.maxExtLength).decodeMulti(e)}var F=function(){function e(e,t,r,i,n,s,o,a){void 0===e&&(e=u.defaultCodec),void 0===t&&(t=void 0),void 0===r&&(r=100),void 0===i&&(i=2048),void 0===n&&(n=!1),void 0===s&&(s=!1),void 0===o&&(o=!1),void 0===a&&(a=!1),this.extensionCodec=e,this.context=t,this.maxDepth=r,this.initialBufferSize=i,this.sortKeys=n,this.forceFloat32=s,this.ignoreUndefined=o,this.forceIntegerToFloat=a,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}return e.prototype.getUint8Array=function(){return this.bytes.subarray(0,this.pos)},e.prototype.reinitializeState=function(){this.pos=0},e.prototype.encode=function(e){return this.reinitializeState(),this.doEncode(e,1),this.getUint8Array()},e.prototype.doEncode=function(e,t){if(t>this.maxDepth)throw new Error("Too deep objects in depth "+t);null==e?this.encodeNil():"boolean"==typeof e?this.encodeBoolean(e):"number"==typeof e?this.encodeNumber(e):"string"==typeof e?this.encodeString(e):this.encodeObject(e,t)},e.prototype.ensureBufferSizeToWrite=function(e){var t=this.pos+e;this.view.byteLength<t&&this.resizeBuffer(2*t)},e.prototype.resizeBuffer=function(e){var t=new ArrayBuffer(e),r=new Uint8Array(t),i=new DataView(t);r.set(this.bytes),this.view=i,this.bytes=r},e.prototype.encodeNil=function(){this.writeU8(192)},e.prototype.encodeBoolean=function(e){!1===e?this.writeU8(194):this.writeU8(195)},e.prototype.encodeNumber=function(e){Number.isSafeInteger(e)&&!this.forceIntegerToFloat?e>=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):(this.writeU8(211),this.writeI64(e)):this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))},e.prototype.writeStringHeader=function(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else{if(!(e<4294967296))throw new Error("Too long string: "+e+" bytes in UTF-8");this.writeU8(219),this.writeU32(e)}},e.prototype.encodeString=function(e){if(e.length>y){var t=p(e);this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),w(e,this.bytes,this.pos),this.pos+=t}else{t=p(e);this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),function(e,t,r){for(var i=e.length,n=r,s=0;s<i;){var o=e.charCodeAt(s++);if(0!=(4294967168&o)){if(0==(4294965248&o))t[n++]=o>>6&31|192;else{if(o>=55296&&o<=56319&&s<i){var a=e.charCodeAt(s);56320==(64512&a)&&(++s,o=((1023&o)<<10)+(1023&a)+65536)}0==(4294901760&o)?(t[n++]=o>>12&15|224,t[n++]=o>>6&63|128):(t[n++]=o>>18&7|240,t[n++]=o>>12&63|128,t[n++]=o>>6&63|128)}t[n++]=63&o|128}else t[n++]=o}}(e,this.bytes,this.pos),this.pos+=t}},e.prototype.encodeObject=function(e,t){var r=this.extensionCodec.tryToEncode(e,this.context);if(null!=r)this.encodeExtension(r);else if(Array.isArray(e))this.encodeArray(e,t);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else{if("object"!=typeof e)throw new Error("Unrecognized object: "+Object.prototype.toString.apply(e));this.encodeMap(e,t)}},e.prototype.encodeBinary=function(e){var t=e.byteLength;if(t<256)this.writeU8(196),this.writeU8(t);else if(t<65536)this.writeU8(197),this.writeU16(t);else{if(!(t<4294967296))throw new Error("Too large binary: "+t);this.writeU8(198),this.writeU32(t)}var r=b(e);this.writeU8a(r)},e.prototype.encodeArray=function(e,t){var r=e.length;if(r<16)this.writeU8(144+r);else if(r<65536)this.writeU8(220),this.writeU16(r);else{if(!(r<4294967296))throw new Error("Too large array: "+r);this.writeU8(221),this.writeU32(r)}for(var i=0,n=e;i<n.length;i++){var s=n[i];this.doEncode(s,t+1)}},e.prototype.countWithoutUndefined=function(e,t){for(var r=0,i=0,n=t;i<n.length;i++){void 0!==e[n[i]]&&r++}return r},e.prototype.encodeMap=function(e,t){var r=Object.keys(e);this.sortKeys&&r.sort();var i=this.ignoreUndefined?this.countWithoutUndefined(e,r):r.length;if(i<16)this.writeU8(128+i);else if(i<65536)this.writeU8(222),this.writeU16(i);else{if(!(i<4294967296))throw new Error("Too large map object: "+i);this.writeU8(223),this.writeU32(i)}for(var n=0,s=r;n<s.length;n++){var o=s[n],a=e[o];this.ignoreUndefined&&void 0===a||(this.encodeString(o),this.doEncode(a,t+1))}},e.prototype.encodeExtension=function(e){var t=e.data.length;if(1===t)this.writeU8(212);else if(2===t)this.writeU8(213);else if(4===t)this.writeU8(214);else if(8===t)this.writeU8(215);else if(16===t)this.writeU8(216);else if(t<256)this.writeU8(199),this.writeU8(t);else if(t<65536)this.writeU8(200),this.writeU16(t);else{if(!(t<4294967296))throw new Error("Too large extension object: "+t);this.writeU8(201),this.writeU32(t)}this.writeI8(e.type),this.writeU8a(e.data)},e.prototype.writeU8=function(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++},e.prototype.writeU8a=function(e){var t=e.length;this.ensureBufferSizeToWrite(t),this.bytes.set(e,this.pos),this.pos+=t},e.prototype.writeI8=function(e){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,e),this.pos++},e.prototype.writeU16=function(e){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,e),this.pos+=2},e.prototype.writeI16=function(e){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,e),this.pos+=2},e.prototype.writeU32=function(e){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,e),this.pos+=4},e.prototype.writeI32=function(e){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,e),this.pos+=4},e.prototype.writeF32=function(e){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,e),this.pos+=4},e.prototype.writeF64=function(e){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,e),this.pos+=8},e.prototype.writeU64=function(e){this.ensureBufferSizeToWrite(8),function(e,t,r){var i=r/4294967296,n=r;e.setUint32(t,i),e.setUint32(t+4,n)}(this.view,this.pos,e),this.pos+=8},e.prototype.writeI64=function(e){this.ensureBufferSizeToWrite(8),h(this.view,this.pos,e),this.pos+=8},e}(),P={};function D(e,t){return void 0===t&&(t=P),new F(t.extensionCodec,t.context,t.maxDepth,t.initialBufferSize,t.sortKeys,t.forceFloat32,t.ignoreUndefined,t.forceIntegerToFloat).encode(e)}const C="0.3.0",$=Object.getPrototypeOf(Object.getPrototypeOf(new Uint8Array)).constructor;function z(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 q(e,t){if(!t)throw new Error("undefined index");return"string"==typeof t?q(e,t.split(".")):0===t.length?e:q(e[t[0]],t.slice(1))}class R{constructor(e,t,r,i){this._timeout=e,this._callback=t,this._args=r,this._label=i||"timer",this._task=null,this.started=!1}start(){this._task=setTimeout(()=>{this._callback.apply(this,this._args)},1e3*this._timeout),this.started=!0}clear(){this._task?(clearTimeout(this._task),this._task=null,this.started=!1):console.warn(`Clearing a timer (${this._label}) which is not started`)}reset(){Object(i.b)(this._task,`Timer (${this._label}) is not started`),clearTimeout(this._task),this.start()}}class N extends i.a{constructor(e,{client_id:t=null,manager_id:r=null,default_context:n=null,name:s=null,codecs:o=null,method_timeout:a=null,max_message_buffer_size:c=0,debug:h=!1}){super(h),this._codecs=o||{},Object(i.b)(t&&"string"==typeof t),Object(i.b)(t,"client_id is required"),this._client_id=t,this._name=s,this._connection_info=null,this._workspace=null,this.manager_id=r,this.default_context=n||{},this._method_annotations=new WeakMap,this._manager_service=null,this._max_message_buffer_size=c,this._chunk_store={},this._method_timeout=a||20,this._services={},this._object_store={services:this._services},e?(this.add_service({id:"built-in",type:"built-in",name:"RPC built-in services",config:{require_context:!0,visibility:"public"},ping:this._ping.bind(this),get_service:this.get_local_service.bind(this),register_service:this.register_service.bind(this),message_cache:{create:this._create_message.bind(this),append:this._append_message.bind(this),process:this._process_message.bind(this),remove:this._remove_message.bind(this)}}),this.on("method",this._handle_method.bind(this)),Object(i.b)(e.emit_message&&e.on_message),this._emit_message=e.emit_message.bind(e),e.on_message(this._on_message.bind(this)),this._connection=e,this._get_connection_info()):this._emit_message=function(){console.log("No connection to emit message")}}async _get_connection_info(){if(this.manager_id)try{if(await this.get_manager_service(5),Object(i.b)(this._manager_service),this._connection_info=await this._manager_service.get_connection_info(),this._connection_info.reconnection_token&&this._connection.set_reconnection_token){this._connection.set_reconnection_token(this._connection_info.reconnection_token);const e=.8*this._connection_info.reconnection_expires_in;console.info(`Reconnection token obtained: ${this._connection_info.reconnection_token}, will be refreshed in ${e} seconds`),this._get_connection_info_task=setTimeout(this._get_connection_info.bind(this),1e3*e)}}catch(e){console.warn("Failed to fetch user info from ",this.manager_id,e)}}register_codec(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(this._codecs))this._codecs[t].type!==e.type&&t!==e.name||(delete this._codecs[t],console.warn("Remove duplicated codec: "+t));this._codecs[e.name]=e}async _ping(e,t){return Object(i.b)("ping"==e),"pong"}async ping(e,t){let r=this._generate_remote_method({_rtarget:e,_rmethod:"services.built-in.ping",_rpromise:!0});Object(i.b)("pong"==await r("ping",t))}_create_message(e,t,r,i){if(t){if(!this._object_store[e])throw new Error("session does not exist anymore: "+e);this._object_store[e].timer.reset()}if(this._object_store.message_cache||(this._object_store.message_cache={}),!r&&this._object_store.message_cache[e])throw new Error(`Message with the same key (${e}) already exists in the cache store, please use overwrite=true or remove it first.`);this._object_store.message_cache[e]=[]}_append_message(e,t,r,n){if(r){if(!this._object_store[e])throw new Error("session does not exist anymore: "+e);this._object_store[e].timer.reset()}const s=this._object_store.message_cache;if(!s[e])throw new Error(`Message with key ${e} does not exists.`);Object(i.b)(t instanceof $),s[e].push(t)}_remove_message(e,t){const r=this._object_store.message_cache;if(!r[e])throw new Error(`Message with key ${e} does not exists.`);delete r[e]}_process_message(e,t,r){if(t){if(!this._object_store[e])throw new Error("session does not exist anymore: "+e);this._object_store[e].timer.reset()}const n=this._object_store.message_cache;if(Object(i.b)(!!r,"Context is required"),!n[e])throw new Error(`Message with key ${e} does not exists.`);var s,o,a,c;n[e]=(s=n[e],o=s.map((function(e){return e.byteLength})),a=o.reduce((function(e,t){return e+t}),0),c=new Uint8Array(a),o.reduce((function(e,t,r){return c.set(new Uint8Array(s[r]),e),e+t}),0),c.buffer),console.debug(`Processing message ${e} (size=${n[e].length})`);let h=M(n[e]);const{done:f,value:l}=h.next(),u=l;if(Object.assign(u,{from:r.from,to:r.to,user:r.user}),u.ctx=JSON.parse(JSON.stringify(u)),Object.assign(u.ctx,this.default_context),!f){let e=h.next();Object.assign(u,e.value)}this._fire(u.type,u),delete n[e]}_on_message(e){Object(i.b)(e instanceof ArrayBuffer);let t=M(e);const{done:r,value:n}=t.next(),s=n;if(s.ctx=JSON.parse(JSON.stringify(s)),Object.assign(s.ctx,this.default_context),!r){let e=t.next();Object.assign(s,e.value)}this._fire(s.type,s)}reset(){this._event_handlers={},this._services={}}async disconnect(){this._get_connection_info_task&&(clearTimeout(this._get_connection_info_task),this._get_connection_info_task=null),this._fire("disconnect")}async get_manager_service(e){this.manager_id&&!this._manager_service&&(this._manager_service=await this.get_remote_service(this.manager_id+":default",e))}get_all_local_services(){return this._services}get_local_service(e,t){Object(i.b)(e);const[r,n]=t.to.split("/");Object(i.b)(n===this._client_id);const s=this._services[e];if(!s)throw new Error("Service not found: "+e);if("public"==s.config.visibility)return s;if(t.from.startsWith(r+"/"))return s;throw new Error("Permission denied for service: "+e)}async get_remote_service(e,t){t=void 0===t?5:t,!e&&this.manager_id?e=this.manager_id:e.includes(":")||(e=this._client_id+":"+e);const r=e.split(":")[0];Object(i.b)(r);try{const n=this._generate_remote_method({_rtarget:r,_rmethod:"services.built-in.get_service",_rpromise:!0});return await Object(i.g)(n(e.split(":")[1]),t,"Timeout Error: Failed to get remote service: "+e)}catch(t){throw console.error("Failed to get remote service: "+e,t),t}}_annotate_service_methods(e,t,r,i,n){if("function"==typeof e){let s=t.split(".")[1];this._method_annotations.set(e,{require_context:Array.isArray(r)?r.includes(s):!!r,run_in_executor:i,method_id:"services."+t,visibility:n})}else if(e instanceof Array||e instanceof Object)for(let s of Object.keys(e)){let o=e[s];if("function"==typeof o&&o.__rpc_object__){let t=o.__rpc_object__._rtarget;if(t.includes("/")&&(t=t.split("/")[1]),this._client_id!==t)throw new Error(`Local method not found: ${o.__rpc_object__._rmethod}, client id mismatch ${this._client_id} != ${t}`);e instanceof Array&&(e=e.slice()),e[s]=q(this._object_store,o.__rpc_object__._rmethod),o=e[s]}this._annotate_service_methods(o,t+"."+s,r,i,n)}}add_service(e,t){if(!e||Array.isArray(e))throw new Error("Invalid service object");if(e.constructor===Object)e=Object.assign({},e);else{const t={},r=Object.getOwnPropertyNames(e).concat(Object.getOwnPropertyNames(Object.getPrototypeOf(e)));for(let i of r)"constructor"!==i&&("function"==typeof e[i]?t[i]=e[i].bind(e):t[i]=e[i]);e.id=e.id||"default",e=t}Object(i.b)(e.id&&"string"==typeof e.id,"Service id not found: "+e),e.name||(e.name=e.id),e.config||(e.config={}),e.type||(e.type="generic");let r=!1,n=!1;e.config.require_context&&(r=e.config.require_context),e.config.run_in_executor&&(n=!0);const s=e.config.visibility||"protected";if(Object(i.b)(["protected","public"].includes(s)),this._annotate_service_methods(e,e.id,r,n,s),this._services[e.id]){if(!t)throw new Error(`Service already exists: ${e.id}, please specify a different id (not ${e.id}) or overwrite=true`);delete this._services[e.id]}return this._services[e.id]=e,e}async register_service(e,t,r,n){if(void 0===r&&(r=!0),n){const[e,t]=n.to.split("/");Object(i.b)(t===this._client_id),Object(i.b)(e===n.from.split("/")[0],"Services can only be registered from the same workspace")}const s=this.add_service(e,t);return r&&(this._fire("service-updated",{service_id:s.id,api:s,type:"add"}),await this._notify_service_update()),{id:`${this._client_id}:${s.id}`,type:s.type,name:s.name,config:s.config}}async unregister_service(e,t){if(e instanceof Object&&(e=e.id),!this._services[e])throw new Error("Service not found: "+e);const r=this._services[e];delete this._services[e],this._fire("service-updated",{service_id:e,api:r,type:"remove"}),await this._notify_service_update()}_ndarray(e,t,r){const n=Object(i.f)(e);if(r&&r!==n)throw"dtype doesn't match the type of the array: "+n+" != "+r;return t=t||[e.length],{_rtype:"ndarray",_rvalue:e.buffer,_rshape:t,_rdtype:n}}_encode_callback(e,t,r,i,n,s){let o=`${r}.${e}`,a={_rtype:"method",_rtarget:s?`${s}/${this._client_id}`:this._client_id,_rmethod:o,_rpromise:!1};const c=this;return[a,function(){try{t.apply(null,Array.prototype.slice.call(arguments))}catch(e){console.error("Error in callback:",o,e)}finally{i&&c._object_store[r]&&(console.log("Deleting session",r,"from",c._client_id),delete c._object_store[r]),n&&n.started&&n.clear()}}]}async _encode_promise(e,t,r,n,s,o){let a=this._get_session_store(r,!0);Object(i.b)(a,`Failed to create session store ${r} due to invalid parent`);let c={};return s&&t&&this._method_timeout?(c.heartbeat=await this._encode(s.reset.bind(s),r,o),c.interval=this._method_timeout/2,a.timer=s):s=null,[c.resolve,a.resolve]=this._encode_callback("resolve",e,r,n,s,o),[c.reject,a.reject]=this._encode_callback("reject",t,r,n,s,o),c}async _send_chunks(e,t,r){let n=await this.get_remote_service(t+":built-in");Object(i.b)(n.message_cache,"Remote client does not support message caching for long message.");let s=n.message_cache,o=r||Object(i.e)();await s.create(o,!!r);let a=e.length,c=Math.ceil(a/512e3);for(let t=0;t<c;t++){let i=512e3*t;await s.append(o,e.slice(i,i+512e3),!!r),console.log(`Sending chunk ${t+1}/${c} (${a} bytes)`)}console.log(`All chunks sent (${c})`),await s.process(o,!!r)}_generate_remote_method(e,t,r,n,s){let o=e._rtarget;n&&!o.includes("/")&&(o=n+"/"+o,e._rtarget=o);let a=e._rmethod,c=e._rpromise;const h=this;function f(){return new Promise(async(e,n)=>{let f=Object(i.e)();r&&(f=r+"."+f);let l=h._get_session_store(f,!0);if(!l)return void n(new Error("Runtime Error: Failed to get session store "+f));l.target_id=o;const u=await h._encode(Array.prototype.slice.call(arguments),f,s),d=u.length,p=d>0&&"object"==typeof u[d-1]&&null!==u[d-1]&&u[d-1]._rkwargs;p&&delete u[d-1]._rkwargs;let _={type:"method",from:h._client_id,to:o,method:a},y={};u&&(y.args=u),p&&(y.with_kwargs=p),console.log(`Calling remote method ${o}:${a}, session: ${f}`),t&&(_.parent=t);let w=null;if(c){_.session=f;let t=`${o}:${a}`;w=new R(h._method_timeout,n,["Method call time out: "+t],t),y.promise=await h._encode_promise(e,n,f,!0,w,s)}let g=D(_);if(y){const e=D(y);g=new Uint8Array([...g,...e])}g.length<=513024?h._emit_message(g).then((function(){w&&(console.log("Start watchdog timer."),w.start())})):h._send_chunks(g,o,t).then((function(){w&&(console.log("Start watchdog timer."),w.start())}))})}return f.__rpc_object__=e,f}async _notify_service_update(){if(this.manager_id)try{await this.get_manager_service(5),Object(i.b)(this._manager_service),await this._manager_service.update_client_info(this.get_client_info())}catch(e){console.warn("Failed to notify service update to",this.manager_id,e)}}get_client_info(){const e=[];for(let t of Object.values(this._services))e.push({id:`${this._client_id}:${t.id}`,type:t.type,name:t.name,config:t.config});return{id:this._client_id,services:e}}async _handle_method(e){let t=null;try{Object(i.b)(e.method&&e.ctx&&e.from);const r=e.from+":"+e.method,n=e.from.split("/")[0],s=e.to.split("/")[0],o=e.parent;let a,c,h,f;if(e.promise){const r=await this._decode(e.promise,e.session,o,n,s);if(a=r.resolve,c=r.reject,r.heartbeat&&r.interval){t=setInterval((async function(){try{console.log("Reset heartbeat timer: "+e.method),await r.heartbeat()}catch(e){console.error(e)}}),1e3*r.interval)}}try{h=q(this._object_store,e.method)}catch(e){throw console.debug("Failed to find method",r,e),new Error("Method not found: "+r)}if(Object(i.b)(h&&"function"==typeof h,"Invalid method: "+r),this._method_annotations.has(h)){if("protected"===this._method_annotations.get(h).visibility&&s!==n)throw new Error("Permission denied for protected method "+r+", workspace mismatch: "+s+" != "+n)}else{let t=this._object_store[e.method.split(".")[0]].target_id;if(s===n&&t&&-1===t.indexOf("/")&&(t=s+"/"+t),t!==e.from)throw new Error("Access denied for method call ("+r+") from "+e.from)}if(o&&Object(i.b)(null!==this._get_session_store(o,!0),"Parent session was closed: "+o),f=e.args?await this._decode(e.args,e.session,null,n,null):[],this._method_annotations.has(h)&&this._method_annotations.get(h).require_context&&f.push(e.ctx),console.log("Executing method: "+r),e.promise){const e=h.apply(null,f);e instanceof Promise?e.then(e=>{a(e),clearInterval(t)}).catch(e=>{c(e),clearInterval(t)}):(a(e),clearInterval(t))}else h.apply(null,f),clearInterval(t)}catch(e){console.error("Error during calling method: ",e),clearInterval(t)}}encode(e,t){return this._encode(e,t)}_get_session_store(e,t){let r=this._object_store;const i=e.split(".");if(t){const e=i.length-1;for(let t of i.slice(0,e)){if(!r[t])return null;r=r[t]}return r[i[e]]||(r[i[e]]={}),r[i[e]]}for(let e of i){if(!r[e])return null;r=r[e]}return r}async _encode(e,t,r){const n=typeof e;if("number"===n||"string"===n||"boolean"===n||null==e||e instanceof Uint8Array)return e;if(e instanceof ArrayBuffer)return{_rtype:"memoryview",_rvalue:new Uint8Array(e)};if(e.__rpc_object__)return e.__rpc_object__;let s;if(e.constructor instanceof Object&&e._rtype){const i=e._rtype;return delete e._rtype,s=await this._encode(e,t,r),s._rtype=i,s}if("function"==typeof e){if(this._method_annotations.has(e)){let t=this._method_annotations.get(e);s={_rtype:"method",_rtarget:this._client_id,_rmethod:t.method_id,_rpromise:!0}}else{let r;Object(i.b)("string"==typeof t),r=e.__name__?`${Object(i.e)()}-${e.__name__}`:Object(i.e)(),s={_rtype:"method",_rtarget:this._client_id,_rmethod:`${t}.${r}`,_rpromise:!0};let n=this._get_session_store(t,!0);Object(i.b)(null!==n,`Failed to create session store ${t} due to invalid parent`),n[r]=e}return s}const o=Array.isArray(e);for(let i of Object.keys(this._codecs)){const n=this._codecs[i];if(n.encoder&&e instanceof n.type){let i=await Promise.resolve(n.encoder(e));if(i&&!i._rtype&&(i._rtype=n.name),"object"==typeof i){const e=i._rtype;delete i._rtype,i=await this._encode(i,t,r),i._rtype=e}return s=i,s}}if("undefined"!=typeof tf&&tf.Tensor&&e instanceof tf.Tensor){const t=e.dataSync();s={_rtype:"ndarray",_rvalue:new Uint8Array(t.buffer),_rshape:e.shape,_rdtype:e.dtype}}else if("undefined"!=typeof nj&&nj.NdArray&&e instanceof nj.NdArray){const t=Object(i.f)(e.selection.data);s={_rtype:"ndarray",_rvalue:new Uint8Array(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(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(e instanceof Blob){let i=0;s={_rtype:"iostream",_rnative:"js:blob",type:e.type,name:e.name,size:e.size,path:e._path||e.webkitRelativePath,read:await this._encode((async function(t){let r;r=t?e.slice(i,i+t):e.slice(i);const n=new Uint8Array(await r.arrayBuffer());return i+=n.byteLength,n}),t,r),seek:await this._encode((function(e){i=e}),t,r)}}else if(e instanceof $){const t=Object(i.f)(e);s={_rtype:"typedarray",_rvalue:new Uint8Array(e.buffer),_rdtype:t}}else if(e instanceof DataView)s={_rtype:"memoryview",_rvalue:new Uint8Array(e.buffer)};else if(e instanceof Set)s={_rtype:"set",_rvalue:await this._encode(Array.from(e),t,r)};else if(e instanceof Map)s={_rtype:"orderedmap",_rvalue:await this._encode(Array.from(e),t,r)};else{if(!(e.constructor instanceof Object||Array.isArray(e)))throw`imjoy-rpc: Unsupported data type: ${e}, you can register a custom codec to encode/decode the object.`;{s=o?[]:{};const i=Object.keys(e);for(let n of i)s[n]=await this._encode(e[n],t,r)}}if(!s)throw new Error("Failed to encode object");return s}async decode(e){return await this._decode(e)}async _decode(e,t,r,n,s){if(!e)return e;let o;if(e._rtype)if(this._codecs[e._rtype]&&this._codecs[e._rtype].decoder){const i=e._rtype;delete e._rtype,(e=await this._decode(e,t,r,n,s))._rtype=i,o=await Promise.resolve(this._codecs[e._rtype].decoder(e))}else if("method"===e._rtype)o=this._generate_remote_method(e,t,r,n,s);else if("ndarray"===e._rtype)if("undefined"!=typeof nj&&nj.array)Array.isArray(e._rvalue)&&(e._rvalue=e._rvalue.reduce(z)),o=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(z));const t=i.c[e._rdtype];o=tf.tensor(new t(e._rvalue),e._rshape,e._rdtype)}else o=e;else if("error"===e._rtype)o=new Error(e._rvalue);else if("typedarray"===e._rtype){const t=i.c[e._rdtype];if(!t)throw new Error("unsupported dtype: "+e._rdtype);o=new t(e._rvalue.buffer.slice(e._rvalue.byteOffset,e._rvalue.byteOffset+e._rvalue.byteLength))}else if("memoryview"===e._rtype)o=e._rvalue.buffer.slice(e._rvalue.byteOffset,e._rvalue.byteOffset+e._rvalue.byteLength);else if("iostream"===e._rtype){if("js:blob"===e._rnative){const i=await this._generate_remote_method(e.read,t,r,n,s),a=await i();o=new Blob([a],{type:e.type,name:e.name})}else{o={};for(let i of Object.keys(e))i.startsWith("_")||(o[i]=await this._decode(e[i],t,r,n,s))}o.__rpc_object__=e}else if("orderedmap"===e._rtype)o=new Map(await this._decode(e._rvalue,t,r,n,s));else if("set"===e._rtype)o=new Set(await this._decode(e._rvalue,t,r,n,s));else{const i=e._rtype;delete e._rtype,o=await this._decode(e,t,r,n,s),o._rtype=i}else if(e.constructor===Object||Array.isArray(e)){const i=Array.isArray(e);o=i?[]:{};for(let a of Object.keys(e))if(i||e.hasOwnProperty(a)){const i=e[a];o[a]=await this._decode(i,t,r,n,s)}}else o=e;if(void 0===o)throw new Error("Failed to decode object");return o}}}})}));
//# sourceMappingURL=hypha-rpc.min.js.map