hypha-debugger 0.1.1 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,49 +1,49 @@
1
1
  !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).hyphaDebugger={})}(this,function(exports){"use strict";var __webpack_modules__={"./src/http-client.js":
2
2
  /*!****************************!*\
3
3
  !*** ./src/http-client.js ***!
4
- \****************************/(e,t,n)=>{n.r(t),n.d(t,{HTTPStreamingRPCConnection:()=>a,_connectToServerHTTP:()=>_,connectToServerHTTP:()=>d,getRemoteServiceHTTP:()=>h,normalizeServerUrl:()=>l});var r=n(/*! ./rpc.js */"./src/rpc.js"),o=n(/*! ./utils/index.js */"./src/utils/index.js"),s=n(/*! ./utils/schema.js */"./src/utils/schema.js"),i=n(/*! @msgpack/msgpack */"./node_modules/@msgpack/msgpack/dist.es5+esm/encode.mjs"),c=n(/*! @msgpack/msgpack */"./node_modules/@msgpack/msgpack/dist.es5+esm/decode.mjs");class a{constructor(e,t,n=null,r=null,s=null,i=60,c=7200){(0,o.assert)(e&&t,"server_url and client_id are required"),this._server_url=e.replace(/\/$/,""),this._client_id=t,this._workspace=n,this._token=r,this._reconnection_token=s,this._timeout=i,this._token_refresh_interval=c,this._handle_message=null,this._handle_disconnected=null,this._handle_connected=null,this._closed=!1,this._enable_reconnect=!1,this._is_reconnection=!1,this.connection_info=null,this.manager_id=null,this._abort_controller=null,this._refresh_token_task=null}on_message(e){(0,o.assert)(e,"handler is required"),this._handle_message=e}on_disconnected(e){this._handle_disconnected=e}on_connected(e){this._handle_connected=e}_get_headers(e=!1){const t={"Content-Type":"application/msgpack"};return e&&(t.Accept="application/x-msgpack-stream"),this._token&&(t.Authorization=`Bearer ${this._token}`),t}async open(){console.info(`Opening HTTP streaming connection to ${this._server_url}`);const e=this._workspace||"public",t=`${this._server_url}/${e}/rpc?client_id=${this._client_id}`;this._startStreamLoop(t);const n=Date.now();for(;null===this.connection_info;){if(await new Promise(e=>setTimeout(e,100)),Date.now()-n>1e3*this._timeout)throw new Error("Timeout waiting for connection info");if(this._closed)throw new Error("Connection closed during setup")}if(this.manager_id=this.connection_info.manager_id,this._workspace){const e=this.connection_info.workspace;if(e!==this._workspace)throw new Error(`Connected to wrong workspace: ${e}, expected: ${this._workspace}`)}if(this._workspace=this.connection_info.workspace,this.connection_info.reconnection_token&&(this._reconnection_token=this.connection_info.reconnection_token),this.connection_info.reconnection_token_life_time){const e=this.connection_info.reconnection_token_life_time;this._token_refresh_interval>e/1.5&&(console.warn(`Token refresh interval (${this._token_refresh_interval}s) is too long, adjusting to ${(e/1.5).toFixed(0)}s based on token lifetime`),this._token_refresh_interval=e/1.5)}return console.info(`HTTP streaming connected to workspace: ${this._workspace}, manager_id: ${this.manager_id}`),this._token_refresh_interval>0&&this._startTokenRefresh(),this._handle_connected&&await this._handle_connected(this.connection_info),this.connection_info}_startTokenRefresh(){this._refresh_token_task&&clearInterval(this._refresh_token_task),setTimeout(()=>{this._sendRefreshToken(),this._refresh_token_task=setInterval(()=>{this._sendRefreshToken()},1e3*this._token_refresh_interval)},2e3)}async _sendRefreshToken(){if(!this._closed)try{const e=this._workspace||"public",t=`${this._server_url}/${e}/rpc?client_id=${this._client_id}`,n=(0,i.encode)({type:"refresh_token"}),r=await fetch(t,{method:"POST",headers:this._get_headers(!1),body:n});r.ok?console.debug("Token refresh requested successfully"):console.warn(`Token refresh request failed: ${r.status}`)}catch(e){console.warn(`Failed to send refresh token request: ${e.message}`)}}async _startStreamLoop(e){this._enable_reconnect=!0,this._closed=!1;let t=0;for(this._is_reconnection=!1;!this._closed&&t<1e6;){try{const e=this._workspace||"public";let n=`${this._server_url}/${e}/rpc?client_id=${this._client_id}`;this._reconnection_token&&(n+=`&reconnection_token=${encodeURIComponent(this._reconnection_token)}`),this._abort_controller=new AbortController;const r=await fetch(n,{method:"GET",headers:this._get_headers(!0),signal:this._abort_controller.signal});if(!r.ok){const e=await r.text();throw new Error(`Stream failed with status ${r.status}: ${e}`)}t=0,await this._processMsgpackStream(r)}catch(e){if(this._closed)break;if(console.error(`Connection error: ${e.message}`),!this._enable_reconnect)break}if(this._is_reconnection=!0,this._closed||!this._enable_reconnect)break;{t+=1;const e=Math.min(Math.pow(2,Math.min(t,6)),60);console.warn(`Stream disconnected, reconnecting in ${e.toFixed(1)}s (attempt ${t})`),await new Promise(t=>setTimeout(t,1e3*e))}}!this._closed&&this._handle_disconnected&&this._handle_disconnected("Stream ended")}_tryDecodeControlMessage(e){try{const t=(0,c.decode)(e);if("object"==typeof t&&null!==t&&t.type){if(["connection_info","ping","pong","reconnection_token","error"].includes(t.type))return t}return null}catch{return null}}async _processMsgpackStream(e){const t=e.body.getReader();let n=new Uint8Array(4096),r=0;for(;!this._closed;){const{done:e,value:o}=await t.read();if(e)break;const s=r+o.length;if(s>n.length){let e=n.length;for(;e<s;)e*=2;const t=new Uint8Array(e);t.set(n.subarray(0,r)),n=t}n.set(o,r),r+=o.length;let i=0;for(;r-i>=4;){const e=n[i]<<24|n[i+1]<<16|n[i+2]<<8|n[i+3];if(r-i<4+e)break;const t=n.slice(i+4,i+4+e);i+=4+e;const o=this._tryDecodeControlMessage(t);if(o){const e=o.type;if("connection_info"===e){this.connection_info=o,this._is_reconnection&&this._handleReconnection(o).catch(e=>{console.error(`Reconnection handling failed: ${e.message}`)});continue}if("ping"===e||"pong"===e)continue;if("reconnection_token"===e){this._reconnection_token=o.reconnection_token;continue}if("error"===e){console.error(`Server error: ${o.message}`);continue}}if(this._handle_message)try{await this._handle_message(t)}catch(e){console.error(`Error in message handler: ${e.message}`)}}if(i>0){const e=r-i;e>0&&n.copyWithin(0,i,r),r=e}}}async _handleReconnection(e){if(this.manager_id=e.manager_id,this._workspace=e.workspace,e.reconnection_token&&(this._reconnection_token=e.reconnection_token),e.reconnection_token_life_time){const t=e.reconnection_token_life_time;this._token_refresh_interval>t/1.5&&(this._token_refresh_interval=t/1.5)}console.warn(`Stream reconnected to workspace: ${this._workspace}, manager_id: ${this.manager_id}`),this._handle_connected&&await this._handle_connected(this.connection_info),await new Promise(e=>setTimeout(e,500))}async emit_message(e){if(this._closed)throw new Error("Connection is closed");const t=this._workspace||"public";let n=`${this._server_url}/${t}/rpc?client_id=${this._client_id}`;const r=e instanceof Uint8Array?e:new Uint8Array(e);for(let e=0;e<3;e++)try{const t=r.length<6e4,o=await fetch(n,{method:"POST",headers:this._get_headers(!1),body:r,...t&&{keepalive:!0}});if(!o.ok){const t=await o.text();if(400===o.status&&e<2){console.warn(`POST failed (attempt ${e+1}/3): ${t}, retrying...`),await new Promise(t=>setTimeout(t,500*(e+1)));continue}throw new Error(`POST failed with status ${o.status}: ${t}`)}return!0}catch(t){if(!(e<2)||this._closed)throw console.error(`Failed to send message: ${t.message}`),t;console.warn(`Failed to send message (attempt ${e+1}/3): ${t.message}, retrying...`),await new Promise(t=>setTimeout(t,500*(e+1)))}}set_reconnection(e){this._enable_reconnect=e}async disconnect(e="client disconnect"){this._closed||(this._closed=!0,this._refresh_token_task&&(clearInterval(this._refresh_token_task),this._refresh_token_task=null),this._abort_controller&&(this._abort_controller.abort(),this._abort_controller=null),this._handle_disconnected&&this._handle_disconnected(e))}}function l(e){if(!e)throw new Error("server_url is required");return e.startsWith("ws://")?e=e.replace("ws://","http://"):e.startsWith("wss://")&&(e=e.replace("wss://","https://")),e.endsWith("/ws")&&(e=e.slice(0,-3)),e.replace(/\/$/,"")}async function _(e){let t=e.clientId||e.client_id;t||(t=(0,o.randId)());const n=l(e.serverUrl||e.server_url),i=new a(n,t,e.workspace,e.token,e.reconnection_token,e.method_timeout||30,e.token_refresh_interval||7200),c=await i.open();(0,o.assert)(c,"Failed to connect to server"),await new Promise(e=>setTimeout(e,100));const _=c.workspace,d=new r.RPC(i,{client_id:t,workspace:_,default_context:{connection_type:"http_streaming"},name:e.name,method_timeout:e.method_timeout,app_id:e.app_id,server_base_url:c.public_base_url});await d.waitFor("services_registered",e.method_timeout||120);const h=await d.get_manager_service({timeout:e.method_timeout||30,case_conversion:"camel"});h.rpc=d,h.disconnect=(0,s.schemaFunction)(d.disconnect.bind(d),{name:"disconnect",description:"Disconnect from server",parameters:{properties:{},type:"object"}}),h.registerService=(0,s.schemaFunction)(d.register_service.bind(d),{name:"registerService",description:"Register a service",parameters:{properties:{service:{description:"Service to register",type:"object"}},required:["service"],type:"object"}});const u=h.getService;return h.getService=async(e,t={})=>await u(e,t),u.__schema__&&(h.getService.__schema__=u.__schema__),h.serve=(0,s.schemaFunction)(async function(){await new Promise(()=>{})},{name:"serve",description:"Run event loop forever",parameters:{type:"object",properties:{}}}),c&&(h.config=Object.assign(h.config||{},c)),i.manager_id&&d.on("force-exit",async e=>{e.from==="*/"+i.manager_id&&(console.info(`Disconnecting from server: ${e.reason}`),await d.disconnect())}),h}async function d(e={}){return await _(e)}async function h(e,t={}){const{serverUrl:n,workspace:r,clientId:s,serviceId:i,appId:c}=(0,o.parseServiceUrl)(e),a=`${r}/${s}:${i}@${c}`;if(t.serverUrl&&t.serverUrl!==n)throw new Error("server_url mismatch");t.serverUrl=n;const l=await d(t);return await l.getService(a)}},"./src/rpc.js":
4
+ \****************************/(e,t,n)=>{n.r(t),n.d(t,{HTTPStreamingRPCConnection:()=>a,_connectToServerHTTP:()=>d,connectToServerHTTP:()=>h,getRemoteServiceHTTP:()=>u,normalizeServerUrl:()=>l});var r=n(/*! ./rpc.js */"./src/rpc.js"),o=n(/*! ./utils/index.js */"./src/utils/index.js"),i=n(/*! ./utils/schema.js */"./src/utils/schema.js"),s=n(/*! @msgpack/msgpack */"./node_modules/@msgpack/msgpack/dist.es5+esm/encode.mjs"),c=n(/*! @msgpack/msgpack */"./node_modules/@msgpack/msgpack/dist.es5+esm/decode.mjs");class a{constructor(e,t,n=null,r=null,i=null,s=60,c=7200){(0,o.assert)(e&&t,"server_url and client_id are required"),this._server_url=e.replace(/\/$/,""),this._client_id=t,this._workspace=n,this._token=r,this._reconnection_token=i,this._timeout=s,this._token_refresh_interval=c,this._handle_message=null,this._handle_disconnected=null,this._handle_connected=null,this._closed=!1,this._enable_reconnect=!1,this._is_reconnection=!1,this.connection_info=null,this.manager_id=null,this._abort_controller=null,this._refresh_token_task=null}on_message(e){(0,o.assert)(e,"handler is required"),this._handle_message=e}on_disconnected(e){this._handle_disconnected=e}on_connected(e){this._handle_connected=e}_get_headers(e=!1){const t={"Content-Type":"application/msgpack"};return e&&(t.Accept="application/x-msgpack-stream"),this._token&&(t.Authorization=`Bearer ${this._token}`),t}async open(){console.info(`Opening HTTP streaming connection to ${this._server_url}`);const e=this._workspace||"public",t=`${this._server_url}/${e}/rpc?client_id=${this._client_id}`;this._startStreamLoop(t);const n=Date.now();for(;null===this.connection_info;){if(await new Promise(e=>setTimeout(e,100)),Date.now()-n>1e3*this._timeout)throw new Error("Timeout waiting for connection info");if(this._closed)throw new Error("Connection closed during setup")}if(this.manager_id=this.connection_info.manager_id,this._workspace){const e=this.connection_info.workspace;if(e!==this._workspace)throw new Error(`Connected to wrong workspace: ${e}, expected: ${this._workspace}`)}if(this._workspace=this.connection_info.workspace,this.connection_info.reconnection_token&&(this._reconnection_token=this.connection_info.reconnection_token),this.connection_info.reconnection_token_life_time){const e=this.connection_info.reconnection_token_life_time;this._token_refresh_interval>e/1.5&&(console.warn(`Token refresh interval (${this._token_refresh_interval}s) is too long, adjusting to ${(e/1.5).toFixed(0)}s based on token lifetime`),this._token_refresh_interval=e/1.5)}return console.info(`HTTP streaming connected to workspace: ${this._workspace}, manager_id: ${this.manager_id}`),this._token_refresh_interval>0&&this._startTokenRefresh(),this._handle_connected&&await this._handle_connected(this.connection_info),this.connection_info}_startTokenRefresh(){this._refresh_token_task&&clearInterval(this._refresh_token_task),setTimeout(()=>{this._sendRefreshToken(),this._refresh_token_task=setInterval(()=>{this._sendRefreshToken()},1e3*this._token_refresh_interval)},2e3)}async _sendRefreshToken(){if(!this._closed)try{const e=this._workspace||"public",t=`${this._server_url}/${e}/rpc?client_id=${this._client_id}`,n=(0,s.encode)({type:"refresh_token"}),r=await fetch(t,{method:"POST",headers:this._get_headers(!1),body:n});r.ok?console.debug("Token refresh requested successfully"):console.warn(`Token refresh request failed: ${r.status}`)}catch(e){console.warn(`Failed to send refresh token request: ${e.message}`)}}async _startStreamLoop(e){this._enable_reconnect=!0,this._closed=!1;let t=0;for(this._is_reconnection=!1;!this._closed&&t<1e6;){try{const e=this._workspace||"public";let n=`${this._server_url}/${e}/rpc?client_id=${this._client_id}`;this._reconnection_token&&(n+=`&reconnection_token=${encodeURIComponent(this._reconnection_token)}`),this._abort_controller=new AbortController;const r=await fetch(n,{method:"GET",headers:this._get_headers(!0),signal:this._abort_controller.signal});if(!r.ok){const e=await r.text();throw new Error(`Stream failed with status ${r.status}: ${e}`)}t=0,await this._processMsgpackStream(r)}catch(e){if(this._closed)break;if(console.error(`Connection error: ${e.message}`),!this._enable_reconnect)break}if(this._is_reconnection=!0,this._closed||!this._enable_reconnect)break;{t+=1;const e=Math.min(Math.pow(2,Math.min(t,6)),60);console.warn(`Stream disconnected, reconnecting in ${e.toFixed(1)}s (attempt ${t})`),await new Promise(t=>setTimeout(t,1e3*e))}}!this._closed&&this._handle_disconnected&&this._handle_disconnected("Stream ended")}_tryDecodeControlMessage(e){try{const t=(0,c.decode)(e);if("object"==typeof t&&null!==t&&t.type){if(["connection_info","ping","pong","reconnection_token","error"].includes(t.type))return t}return null}catch{return null}}async _processMsgpackStream(e){const t=e.body.getReader();let n=new Uint8Array(4096),r=0;for(;!this._closed;){const{done:e,value:o}=await t.read();if(e)break;const i=r+o.length;if(i>n.length){let e=n.length;for(;e<i;)e*=2;const t=new Uint8Array(e);t.set(n.subarray(0,r)),n=t}n.set(o,r),r+=o.length;let s=0;for(;r-s>=4;){const e=n[s]<<24|n[s+1]<<16|n[s+2]<<8|n[s+3];if(r-s<4+e)break;const t=n.slice(s+4,s+4+e);s+=4+e;const o=this._tryDecodeControlMessage(t);if(o){const e=o.type;if("connection_info"===e){this.connection_info=o,this._is_reconnection&&this._handleReconnection(o).catch(e=>{console.error(`Reconnection handling failed: ${e.message}`)});continue}if("ping"===e||"pong"===e)continue;if("reconnection_token"===e){this._reconnection_token=o.reconnection_token;continue}if("error"===e){console.error(`Server error: ${o.message}`);continue}}if(this._handle_message)try{await this._handle_message(t)}catch(e){console.error(`Error in message handler: ${e.message}`)}}if(s>0){const e=r-s;e>0&&n.copyWithin(0,s,r),r=e}}}async _handleReconnection(e){if(this.manager_id=e.manager_id,this._workspace=e.workspace,e.reconnection_token&&(this._reconnection_token=e.reconnection_token),e.reconnection_token_life_time){const t=e.reconnection_token_life_time;this._token_refresh_interval>t/1.5&&(this._token_refresh_interval=t/1.5)}console.warn(`Stream reconnected to workspace: ${this._workspace}, manager_id: ${this.manager_id}`),this._handle_connected&&await this._handle_connected(this.connection_info),await new Promise(e=>setTimeout(e,500))}async emit_message(e){if(this._closed)throw new Error("Connection is closed");const t=this._workspace||"public";let n=`${this._server_url}/${t}/rpc?client_id=${this._client_id}`;const r=e instanceof Uint8Array?e:new Uint8Array(e);for(let e=0;e<3;e++)try{const t=r.length<6e4,o=await fetch(n,{method:"POST",headers:this._get_headers(!1),body:r,...t&&{keepalive:!0}});if(!o.ok){const t=await o.text();if(400===o.status&&e<2){console.warn(`POST failed (attempt ${e+1}/3): ${t}, retrying...`),await new Promise(t=>setTimeout(t,500*(e+1)));continue}throw new Error(`POST failed with status ${o.status}: ${t}`)}return!0}catch(t){if(!(e<2)||this._closed)throw console.error(`Failed to send message: ${t.message}`),t;console.warn(`Failed to send message (attempt ${e+1}/3): ${t.message}, retrying...`),await new Promise(t=>setTimeout(t,500*(e+1)))}}set_reconnection(e){this._enable_reconnect=e}async disconnect(e="client disconnect"){this._closed||(this._closed=!0,this._refresh_token_task&&(clearInterval(this._refresh_token_task),this._refresh_token_task=null),this._abort_controller&&(this._abort_controller.abort(),this._abort_controller=null),this._handle_disconnected&&this._handle_disconnected(e))}}function l(e){if(!e)throw new Error("server_url is required");return e.startsWith("ws://")?e=e.replace("ws://","http://"):e.startsWith("wss://")&&(e=e.replace("wss://","https://")),e.endsWith("/ws")&&(e=e.slice(0,-3)),e.replace(/\/$/,"")}async function d(e){let t=e.clientId||e.client_id;t||(t=(0,o.randId)());const n=l(e.serverUrl||e.server_url),s=new a(n,t,e.workspace,e.token,e.reconnection_token,e.method_timeout||30,e.token_refresh_interval||7200),c=await s.open();(0,o.assert)(c,"Failed to connect to server"),await new Promise(e=>setTimeout(e,100));const d=c.workspace,h=new r.RPC(s,{client_id:t,workspace:d,default_context:{connection_type:"http_streaming"},name:e.name,method_timeout:e.method_timeout,app_id:e.app_id,server_base_url:c.public_base_url});await h.waitFor("services_registered",e.method_timeout||120);const u=await h.get_manager_service({timeout:e.method_timeout||30,case_conversion:"camel"});u.rpc=h,u.disconnect=(0,i.schemaFunction)(h.disconnect.bind(h),{name:"disconnect",description:"Disconnect from server",parameters:{properties:{},type:"object"}}),u.registerService=(0,i.schemaFunction)(h.register_service.bind(h),{name:"registerService",description:"Register a service",parameters:{properties:{service:{description:"Service to register",type:"object"}},required:["service"],type:"object"}});const _=u.getService;return u.getService=async(e,t={})=>await _(e,t),_.__schema__&&(u.getService.__schema__=_.__schema__),u.serve=(0,i.schemaFunction)(async function(){await new Promise(()=>{})},{name:"serve",description:"Run event loop forever",parameters:{type:"object",properties:{}}}),c&&(u.config=Object.assign(u.config||{},c)),s.manager_id&&h.on("force-exit",async e=>{e.from==="*/"+s.manager_id&&(console.info(`Disconnecting from server: ${e.reason}`),await h.disconnect())}),u}async function h(e={}){return await d(e)}async function u(e,t={}){const{serverUrl:n,workspace:r,clientId:i,serviceId:s,appId:c}=(0,o.parseServiceUrl)(e),a=`${r}/${i}:${s}@${c}`;if(t.serverUrl&&t.serverUrl!==n)throw new Error("server_url mismatch");t.serverUrl=n;const l=await h(t);return await l.getService(a)}},"./src/rpc.js":
5
5
  /*!********************!*\
6
6
  !*** ./src/rpc.js ***!
7
- \********************/(e,t,n)=>{n.r(t),n.d(t,{API_VERSION:()=>c,RPC:()=>y});var r=n(/*! ./utils/index.js */"./src/utils/index.js"),o=n(/*! ./utils/schema.js */"./src/utils/schema.js"),s=n(/*! @msgpack/msgpack */"./node_modules/@msgpack/msgpack/dist.es5+esm/decode.mjs"),i=n(/*! @msgpack/msgpack */"./node_modules/@msgpack/msgpack/dist.es5+esm/encode.mjs");const c=3,a=Object.getPrototypeOf(Object.getPrototypeOf(new Uint8Array)).constructor;function l(e){if(null==e)return!0;const t=typeof e;return"number"===t||"string"===t||"boolean"===t}function _(e){for(let t=0;t<e.length;t++){const n=e[t];if(!l(n)&&!(n instanceof Uint8Array))if(Array.isArray(n)){if(!_(n))return!1}else{if(!n||n.constructor!==Object)return!1;if("_rtype"in n)return!1;if(!d(n))return!1}}return!0}function d(e){const t=Object.values(e);for(let e=0;e<t.length;e++){const n=t[e];if(!l(n)&&!(n instanceof Uint8Array))if(Array.isArray(n)){if(!_(n))return!1}else{if(!n||n.constructor!==Object)return!1;if("_rtype"in n)return!1;if(!d(n))return!1}}return!0}function h(e,t){const n=new Uint8Array(e.byteLength+t.byteLength);return n.set(new Uint8Array(e),0),n.set(new Uint8Array(t),e.byteLength),n.buffer}function u(e,t,n="Operation timed out"){return new Promise((r,o)=>{const s=setTimeout(()=>{o(new Error(`TimeoutError: ${n}`))},t);e.then(e=>{clearTimeout(s),r(e)}).catch(e=>{clearTimeout(s),o(e)})})}function p(e,t){if(!t)throw new Error("undefined index");return"string"==typeof t?p(e,t.split(".")):0===t.length?e:p(e[t[0]],t.slice(1))}function f(e,t=null,n=!1){if(Array.isArray(e))return e.map((e,t)=>f(e,null,n));if("object"==typeof e&&null!==e){let t={};for(let r in e)t[r]=f(e[r],r,n);return t}if("function"==typeof e){if(e.__schema__){const r=JSON.parse(JSON.stringify(e.__schema__));if(t&&(r.name=t,e.__schema__.name=t),n&&(r.parameters&&r.parameters.properties&&delete r.parameters.properties.context,r.parameters&&r.parameters.required)){const e=r.parameters.required.indexOf("context");e>-1&&r.parameters.required.splice(e,1)}return{type:"function",function:r}}return{type:"function",function:{name:t||e.name||"function"}}}return"number"==typeof e?{type:"number"}:"string"==typeof e?{type:"string"}:"boolean"==typeof e?{type:"boolean"}:null===e?{type:"null"}:{}}class m{constructor(e,t,n,r){this._timeout=e,this._callback=t,this._args=n,this._label=r||"timer",this._task=null,this.started=!1}start(){this.started?this.reset():(this._task=setTimeout(()=>{this._callback.apply(this,this._args)},1e3*this._timeout),this.started=!0)}clear(){this._task&&this.started?(clearTimeout(this._task),this._task=null,this.started=!1):console.warn(`Clearing a timer (${this._label}) which is not started`)}reset(){this._task&&clearTimeout(this._task),this._task=setTimeout(()=>{this._callback.apply(this,this._args)},1e3*this._timeout),this.started=!0}}class g extends Object{}class y extends r.MessageEmitter{constructor(e,{client_id:t=null,default_context:n=null,name:o=null,codecs:s=null,method_timeout:i=null,max_message_buffer_size:a=0,debug:l=!1,workspace:_=null,silent:d=!1,app_id:h=null,server_base_url:p=null,long_message_chunk_size:f=null}){if(super(l),this._codecs=s||{},(0,r.assert)(t&&"string"==typeof t),(0,r.assert)(t,"client_id is required"),this._client_id=t,this._name=o,this._app_id=h||"*",this._local_workspace=_,this._silent=d,this.default_context=n||{},this._method_annotations=new WeakMap,this._max_message_buffer_size=a,this._chunk_store={},this._method_timeout=i||30,this._server_base_url=p,this._long_message_chunk_size=f||262144,this._services={},this._object_store={services:this._services},this._targetIdIndex={},this._background_tasks=new Set,this._sessionMaxAge=6e5,this._sessionSweepInterval=setInterval(()=>{this._sweepStaleSessions()},this._sessionMaxAge/2),this._unhandledRejectionHandler=e=>{const t=e.reason;if(t&&"object"==typeof t){const n=t.toString();if(n.includes("Method not found")||n.includes("Session not found")||n.includes("Method expired")||n.includes("Connection is closed")||n.includes("Client disconnected")||n.includes("RPC connection closed"))return console.debug("Ignoring expected disconnection/method error:",t),void e.preventDefault()}console.warn("Unhandled RPC promise rejection:",t)},this._unhandledRejectionNodeHandler=null,y._rejectionHandlerCount||(y._rejectionHandlerCount=0),y._rejectionHandlerCount++,1===y._rejectionHandlerCount&&("undefined"!=typeof window?window.addEventListener("unhandledrejection",this._unhandledRejectionHandler):"undefined"!=typeof process&&(this._unhandledRejectionNodeHandler=(e,t)=>{this._unhandledRejectionHandler({reason:e,promise:t,preventDefault:()=>{}})},process.on("unhandledRejection",this._unhandledRejectionNodeHandler))),e){this.add_service({id:"built-in",type:"built-in",name:`Built-in services for ${this._local_workspace}/${this._client_id}`,config:{require_context:!0,visibility:"public",api_version:c},ping:this._ping.bind(this),get_service:this.get_local_service.bind(this),message_cache:{create:this._create_message.bind(this),append:this._append_message.bind(this),set:this._set_message.bind(this),process:this._process_message.bind(this),remove:this._remove_message.bind(this)}}),this._boundHandleMethod=this._handle_method.bind(this),this._boundHandleError=console.error,this.on("method",this._boundHandleMethod),this.on("error",this._boundHandleError),(0,r.assert)(e.emit_message&&e.on_message),(0,r.assert)(void 0!==e.manager_id,"Connection must have manager_id"),this._emit_message=e.emit_message.bind(e),e.on_message(this._on_message.bind(this)),this._connection=e;const t=async e=>{if(!this._silent&&this._connection.manager_id){console.debug("Connection established, reporting services...");try{const e=await this.get_manager_service({timeout:20,case_conversion:"camel"}),t=Object.values(this._services),n=t.length;let r=0;const o=[],s=this._method_timeout||3e4;for(let n of t)try{const t=this._extract_service_info(n);await u(e.registerService(t),s,`Timeout registering service ${n.id||"unknown"}`),r++,console.debug(`Successfully registered service: ${n.id||"unknown"}`)}catch(e){o.push(n.id||"unknown"),e.message&&e.message.includes("TimeoutError")?console.error(`Timeout registering service ${n.id||"unknown"}`):console.error(`Failed to register service ${n.id||"unknown"}: ${e}`)}r===n?console.info(`Successfully registered all ${r} services with the server`):console.warn(`Only registered ${r} out of ${n} services with the server. Failed services: ${o.join(", ")}`),this._fire("services_registered",{total:n,registered:r,failed:o});try{if(e.subscribe&&"function"==typeof e.subscribe){console.debug("Subscribing to client_disconnected events");const t=async e=>{const t=e.data?.id||e.client,n=e.data?.workspace;if(t&&n){const e=`${n}/${t}`;console.debug(`Client ${e} disconnected, cleaning up sessions`),await this._handleClientDisconnected(e)}else t&&(console.debug(`Client ${t} disconnected, cleaning up sessions`),await this._handleClientDisconnected(t))};this._clientDisconnectedSubscription=await u(e.subscribe(["client_disconnected"]),s,"Timeout subscribing to client_disconnected events"),this.on("client_disconnected",t),console.debug("Successfully subscribed to client_disconnected events")}else console.debug("Manager does not support subscribe method, skipping client_disconnected handling"),this._clientDisconnectedSubscription=null}catch(e){console.debug(`Failed to subscribe to client_disconnected events: ${e}`),this._clientDisconnectedSubscription=null}}catch(e){console.error(`Failed to get manager service for registering services: ${e}`),this._fire("services_registration_failed",{error:e.toString(),total_services:Object.keys(this._services).length})}}e&&(e.public_base_url&&(this._server_base_url=e.public_base_url),this._fire("connected",e))};e.on_connected(t),"function"==typeof e.on_disconnected&&e.on_disconnected(t=>{e._enable_reconnect?console.info(`Connection lost (${t}), reconnection enabled - pending calls will be handled by timeout`):(console.warn(`Connection lost (${t}), rejecting all pending RPC calls`),this._rejectPendingCalls(`Connection lost: ${t||"unknown reason"}`))}),t()}else this._emit_message=function(){console.log("No connection to emit message")}}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(0,r.assert)("ping"==e),"pong"}async ping(e,t){let n=this._generate_remote_method({_rserver:this._server_base_url,_rtarget:e,_rmethod:"services.built-in.ping",_rpromise:!0,_rdoc:"Ping a remote client"});(0,r.assert)("pong"==await n("ping",t))}_create_message(e,t,n,r){if(t){if(!this._object_store[e])throw new Error(`session does not exist anymore: ${e}`);this._object_store[e].timer.reset()}this._object_store.message_cache||(this._object_store.message_cache={});const o=this._object_store.message_cache,s=Object.keys(o);if(s.length>=256){const e=Date.now();for(const t of s){const n=o[t];n&&n._cache_created_at&&e-n._cache_created_at>3e5&&delete o[t]}const t=Object.keys(o);t.length>=256&&t.sort((e,t)=>(o[e]._cache_created_at||0)-(o[t]._cache_created_at||0)).slice(0,t.length-256+1).forEach(e=>delete o[e])}if(!n&&o[e])throw new Error(`Message with the same key (${e}) already exists in the cache store, please use overwrite=true or remove it first.`);o[e]=[],o[e]._cache_created_at=Date.now()}_append_message(e,t,n,o){if(n){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.`);(0,r.assert)(t instanceof a),s[e].push(t)}_set_message(e,t,n,o,s){if(o){if(!this._object_store[e])throw new Error(`session does not exist anymore: ${e}`);this._object_store[e].timer.reset()}const i=this._object_store.message_cache;if(!i[e])throw new Error(`Message with key ${e} does not exists.`);(0,r.assert)(n instanceof a),i[e][t]=n}_remove_message(e,t){const n=this._object_store.message_cache;if(!n[e])throw new Error(`Message with key ${e} does not exists.`);delete n[e]}_process_message(e,t,n){if(t){if(!this._object_store[e])throw new Error(`session does not exist anymore: ${e}`);this._object_store[e].timer.reset()}const o=this._object_store.message_cache;if((0,r.assert)(!!n,"Context is required"),!o[e])throw new Error(`Message with key ${e} does not exists.`);var i,c,a,l;o[e]=(i=o[e],c=i.map(function(e){return e.byteLength}),a=c.reduce(function(e,t){return e+t},0),l=new Uint8Array(a),c.reduce(function(e,t,n){return l.set(new Uint8Array(i[n]),e),e+t},0),l.buffer);let _=(0,s.decodeMulti)(o[e]);const{done:d,value:h}=_.next(),u=h;if(Object.assign(u,{from:n.from,to:n.to,ws:n.ws,user:n.user}),u.ctx=JSON.parse(JSON.stringify(u)),Object.assign(u.ctx,this.default_context),!d){let e=_.next();Object.assign(u,e.value)}this._fire(u.type,u),delete o[e]}_on_message(e){if("string"==typeof e){const t=JSON.parse(e);t.ctx=Object.assign({},t,this.default_context),this._fire(t.type,t)}else if(e instanceof ArrayBuffer||ArrayBuffer.isView(e)){let t=(0,s.decodeMulti)(e);const{done:n,value:r}=t.next(),o=r;if(o.ctx=Object.assign({},o,this.default_context),!n){let e=t.next();Object.assign(o,e.value)}this._fire(o.type,o)}else{if("object"!=typeof e)throw new Error("Invalid message format");e.ctx=Object.assign({},e,this.default_context),this._fire(e.type,e)}}reset(){this._removeRejectionHandler(),this._event_handlers={},this._services={}}_removeRejectionHandler(){y._rejectionHandlerCount&&y._rejectionHandlerCount>0&&(y._rejectionHandlerCount--,0===y._rejectionHandlerCount&&("undefined"!=typeof window&&this._unhandledRejectionHandler?window.removeEventListener("unhandledrejection",this._unhandledRejectionHandler):"undefined"!=typeof process&&this._unhandledRejectionNodeHandler&&process.removeListener("unhandledRejection",this._unhandledRejectionNodeHandler))),this._unhandledRejectionHandler=null,this._unhandledRejectionNodeHandler=null}close(){if(this._cleanupOnDisconnect(),this._boundHandleMethod&&(this.off("method",this._boundHandleMethod),this._boundHandleMethod=null),this._boundHandleError&&(this.off("error",this._boundHandleError),this._boundHandleError=null),this._clientDisconnectedSubscription){try{"function"==typeof this._clientDisconnectedSubscription.unsubscribe&&this._clientDisconnectedSubscription.unsubscribe()}catch(e){console.debug(`Error unsubscribing client_disconnected: ${e}`)}this.off("client_disconnected"),this._clientDisconnectedSubscription=null}this._removeRejectionHandler(),this.off();try{for(const e of this._background_tasks)if(e&&"function"==typeof e.cancel)try{e.cancel()}catch(e){console.debug(`Error canceling background task: ${e}`)}this._background_tasks.clear()}catch(e){console.debug(`Error cleaning up background tasks: ${e}`)}this._sessionSweepInterval&&(clearInterval(this._sessionSweepInterval),this._sessionSweepInterval=null);try{this._connection=null,this._emit_message=function(){return console.debug("RPC connection closed, ignoring message"),Promise.reject(new Error("Connection is closed"))}}catch(e){console.debug(`Error during connection cleanup: ${e}`)}this._fire("disconnected")}async _handleClientDisconnected(e){try{console.debug(`Handling disconnection for client: ${e}`);const t=this._cleanupSessionsForClient(e);t>0&&console.debug(`Cleaned up ${t} sessions for disconnected client: ${e}`),this._fire("remote_client_disconnected",{client_id:e,sessions_cleaned:t})}catch(t){console.error(`Error handling client disconnection for ${e}: ${t}`)}}_removeFromTargetIdIndex(e){const t=e.split(".")[0],n=this._object_store[t];if(n&&"object"==typeof n){const e=n.target_id;e&&e in this._targetIdIndex&&(this._targetIdIndex[e].delete(t),0===this._targetIdIndex[e].size&&delete this._targetIdIndex[e])}}_cleanupSessionEntry(e,t=null){if(e&&"object"==typeof e){if(t&&e.reject&&"function"==typeof e.reject)try{e.reject(new Error(t))}catch(e){console.debug(`Error rejecting session: ${e}`)}if(e.heartbeat_task)try{clearInterval(e.heartbeat_task)}catch(e){}if(e.timer&&e.timer.started&&"function"==typeof e.timer.clear)try{e.timer.clear()}catch(e){}}}_cleanupSessionsForClient(e){let t=0;const n=this._targetIdIndex[e];if(!n)return 0;const r=`Client disconnected: ${e}`;for(const o of n){const n=this._object_store[o];n&&"object"==typeof n&&(n.target_id===e&&(this._cleanupSessionEntry(n,r),delete this._object_store[o],t++,console.debug(`Cleaned up session: ${o}`)))}return delete this._targetIdIndex[e],t}_rejectPendingCalls(e="Connection lost"){try{let t=0;for(const n of Object.keys(this._object_store)){if("services"===n||"message_cache"===n)continue;const r=this._object_store[n];"object"==typeof r&&null!==r&&(r.reject&&"function"==typeof r.reject&&t++,this._cleanupSessionEntry(r,e))}t>0&&console.warn(`Rejected ${t} pending RPC call(s) due to: ${e}`)}catch(e){console.error(`Error rejecting pending calls: ${e}`)}}_cleanupOnDisconnect(){try{console.debug("Cleaning up all sessions due to local RPC disconnection");const e=[];for(const t of Object.keys(this._object_store)){if("services"===t||"message_cache"===t)continue;const n=this._object_store[t];this._cleanupSessionEntry(n,"RPC connection closed"),e.push(t)}for(const t of e)delete this._object_store[t];this._targetIdIndex={}}catch(e){console.error(`Error during cleanup on disconnect: ${e}`)}}async disconnect(){const e=this._connection;if(this.close(),e)try{await e.disconnect()}catch(e){console.debug(`Error disconnecting underlying connection: ${e}`)}}async get_manager_service(e,t=20){e=e||{};let n=null;for(let r=0;r<t;r++){const o=Math.min(500*Math.pow(2,r),1e4);if(!this._connection.manager_id){if(r<t-1){console.warn(`Manager ID not set, retrying in ${o}ms (attempt ${r+1}/${t})`),await new Promise(e=>setTimeout(e,o));continue}throw new Error("Manager ID not set after maximum retries")}try{return await this.get_remote_service(`*/${this._connection.manager_id}:default`,e)}catch(e){n=e,console.warn(`Failed to get manager service (attempt ${r+1}/${t}): ${e.message}`),r<t-1&&await new Promise(e=>setTimeout(e,o))}}throw n}get_all_local_services(){return this._services}get_local_service(e,t){(0,r.assert)(e),(0,r.assert)(t,"Context is required");const[n,o]=t.to.split("/");(0,r.assert)(o===this._client_id,"Services can only be accessed locally");const s=this._services[e];if(!s)throw new Error("Service not found: "+e);if("public"==s.config.visibility||"unlisted"==s.config.visibility)return s;if(t.ws===n)return s;const i=s.config.authorized_workspaces;if(i&&i.includes(t.ws))return s;throw new Error(`Permission denied for getting protected service: ${e}, workspace mismatch: ${n} != ${t.ws}`)}async get_remote_service(e,t){let{timeout:n,case_conversion:o,kwargs_expansion:s}=t||{};n=void 0===n?this._method_timeout:n,!e&&this._connection.manager_id?e="*/"+this._connection.manager_id:e.includes(":")||(e=this._client_id+":"+e);const i=e.split(":")[0];let c=e.split(":")[1];if(c.includes("@")){c=c.split("@")[0];const t=e.split("@")[1];this._app_id&&"*"!==this._app_id&&(0,r.assert)(t===this._app_id,`Invalid app id: ${t} != ${this._app_id}`)}(0,r.assert)(i,`Invalid service uri: ${e}`);try{const t=this._generate_remote_method({_rserver:this._server_base_url,_rtarget:i,_rmethod:"services.built-in.get_service",_rpromise:!0,_rdoc:"Get a remote service"});let a=await(0,r.waitFor)(t(c),n,"Timeout Error: Failed to get remote service: "+e);return a.id=`${i}:${c}`,s&&(a=(0,r.expandKwargs)(a)),o?Object.assign(new g,(0,r.convertCase)(a,o)):Object.assign(new g,a)}catch(t){throw console.warn("Failed to get remote service: "+e,t),t}}_annotate_service_methods(e,t,n,r,o,s){if("function"==typeof e){let i=t.split(".")[1];this._method_annotations.set(e,{require_context:Array.isArray(n)?n.includes(i):!!n,run_in_executor:r,method_id:"services."+t,visibility:o,authorized_workspaces:s})}else if(e instanceof Array||e instanceof Object)for(let i of Object.keys(e)){let c=e[i];if("function"==typeof c&&c.__rpc_object__){let t=c.__rpc_object__._rtarget;if(t.includes("/")&&(t=t.split("/")[1]),this._client_id!==t)throw new Error(`Local method not found: ${c.__rpc_object__._rmethod}, client id mismatch ${this._client_id} != ${t}`);e instanceof Array&&(e=e.slice()),e[i]=p(this._object_store,c.__rpc_object__._rmethod),c=e[i]}this._annotate_service_methods(c,t+"."+i,n,r,o,s)}}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={},n=Object.getOwnPropertyNames(e).concat(Object.getOwnPropertyNames(Object.getPrototypeOf(e)));for(let r of n)"constructor"!==r&&("function"==typeof e[r]?t[r]=e[r].bind(e):t[r]=e[r]);e.id=e.id||"default",e=t}(0,r.assert)(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 n=!1,o=!1;e.config.require_context&&(n=e.config.require_context),e.config.run_in_executor&&(o=!0);const s=e.config.visibility||"protected";(0,r.assert)(["protected","public","unlisted"].includes(s));const i=e.config.authorized_workspaces;if(void 0!==i){if("protected"!==s)throw new Error(`authorized_workspaces can only be set when visibility is 'protected', got visibility='${s}'`);if(!Array.isArray(i))throw new Error("authorized_workspaces must be an array of workspace ids");for(const e of i)if("string"!=typeof e)throw new Error("Each workspace id in authorized_workspaces must be a string, got "+typeof e)}if(this._annotate_service_methods(e,e.id,n,o,s,i),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}_extract_service_info(e){const t=e.config||{};if(t.workspace=t.workspace||this._local_workspace||this._connection.workspace,!t.workspace)throw new Error("Workspace is not set. Please ensure the connection has a workspace or set local_workspace.");const n=t.require_context,r=["id","config","name","description","type","docs","app_id","service_schema"],o={};for(const t of Object.keys(e))r.includes(t)||(o[t]=e[t]);const s=f(o,null,n);return{config:t,id:`${t.workspace}/${this._client_id}:${e.id}`,name:e.name||e.id,description:e.description||"",type:e.type||"generic",docs:e.docs||null,app_id:this._app_id,service_schema:s}}async get_service_schema(e){return f(e,null,e.config.require_context)}async register_service(e,t){let n,{check_type:r,notify:s,overwrite:i}=t||{};if(s=void 0===s||s,r&&e.type)try{n=await this.get_manager_service({timeout:10,case_conversion:"camel"});e=function(e,t){function n(e,t,n="root"){for(let r in t)if(!e.hasOwnProperty(r))throw new Error(`Missing key '${r}' in service at path '${n}'`);for(let r in e)if("type"!==r&&!t.hasOwnProperty(r))throw new Error(`Unexpected key '${r}' in service at path '${n}'`)}return n(e,t.definition),function e(t,r,s="root"){if("object"!=typeof t||Array.isArray(t)){if(Array.isArray(t)){if(t.length!==r.length)throw new Error(`Length mismatch at path '${s}'`);t.forEach((n,i)=>{let c=`${s}[${i}]`;if("object"!=typeof n||Array.isArray(n)){if("function"==typeof n){if(!r.hasOwnProperty(i))throw new Error(`Missing schema for function at index ${i} in path '${c}'`);t[i]=(0,o.schemaFunction)(n,{name:r[i].name,description:r[i].description||"",parameters:r[i].parameters})}}else e(n,r[i],c)})}}else{n(t,r,s);for(let n in t){let i=t[n],c=`${s}.${n}`;if("object"!=typeof i||Array.isArray(i)){if("function"==typeof i){if(!r.hasOwnProperty(n))throw new Error(`Missing schema for function '${n}' at path '${c}'`);t[n]=(0,o.schemaFunction)(i,{name:r[n].name,description:r[n].description||"",parameters:r[n].parameters})}}else e(i,r[n],c)}}}(e,t.definition),e}(e,await n.get_service_type(e.type))}catch(t){throw new Error(`Failed to get service type ${e.type}, error: ${t}`)}const c=this.add_service(e,i),a=this._extract_service_info(c);if(s)try{n=n||await this.get_manager_service({timeout:10,case_conversion:"camel"}),await n.registerService(a)}catch(e){throw new Error(`Failed to notify workspace manager: ${e}`)}return a}async unregister_service(e,t){let n;if(t=void 0===t||t,n="string"==typeof e?e:e.id,(0,r.assert)(n&&"string"==typeof n,`Invalid service id: ${n}`),n.includes(":")&&(n=n.split(":")[1]),n.includes("@")&&(n=n.split("@")[0]),!this._services[n])throw new Error(`Service not found: ${n}`);if(n.startsWith("_rintf_")&&(t=!1),t){const e=await this.get_manager_service({timeout:10,case_conversion:"camel"});await e.unregisterService(n)}delete this._services[n]}_ndarray(e,t,n){const o=(0,r.typedArrayToDtype)(e);if(n&&n!==o)throw"dtype doesn't match the type of the array: "+o+" != "+n;return t=t||[e.length],{_rtype:"ndarray",_rvalue:e.buffer,_rshape:t,_rdtype:o}}_encode_callback(e,t,n,r,o,s,i){let c=`${n}.${e}`,a={_rtype:"method",_rtarget:s?`${s}/${this._client_id}`:this._client_id,_rmethod:c,_rpromise:!1};const l=this;let _=function(){try{t.apply(null,Array.prototype.slice.call(arguments))}catch(e){console.error(`Error in callback(${c}, ${i}): ${e}`)}finally{o&&o.started&&o.clear(),r&&l._object_store[n]&&("resolve"===e||"reject"===e?(l._removeFromTargetIdIndex(n),delete l._object_store[n]):l._cleanup_session_if_needed(n,e))}};return _.__name__=`callback(${c})`,[a,_]}_cleanup_session_if_needed(e,t){if(e)try{const n=this._get_session_store(e,!1);if(!n)return void console.debug(`Session ${e} not found for cleanup`);let r=!1;if(n._promise_manager)try{const o=n._promise_manager;o.should_cleanup_on_callback&&o.should_cleanup_on_callback(t)&&(o.settle&&o.settle(),r=!0,console.debug(`Promise session ${e} settled and marked for cleanup`))}catch(t){console.warn(`Error in promise manager cleanup for session ${e}:`,t)}else("resolve"===t||"reject"===t)&&n._callbacks&&Object.keys(n._callbacks).includes(t)&&(r=!0,console.debug(`Regular session ${e} marked for cleanup after ${t}`));r&&this._cleanup_session_completely(e)}catch(t){console.warn(`Error during session cleanup for ${e}:`,t)}else console.debug("Cannot cleanup session: session_id is empty")}_cleanup_session_completely(e){try{this._removeFromTargetIdIndex(e);const t=this._get_session_store(e,!1);if(!t)return void console.debug(`Session ${e} already cleaned up`);if(t.timer&&t.timer.started&&"function"==typeof t.timer.clear)try{t.timer.clear()}catch(t){console.warn(`Error clearing timer for session ${e}:`,t)}if(t.heartbeat_task&&"function"==typeof t.heartbeat_task.cancel)try{t.heartbeat_task.cancel()}catch(t){console.warn(`Error canceling heartbeat for session ${e}:`,t)}const n=e.split(".");let r=this._object_store;for(let t=0;t<n.length-1;t++){const o=n[t];if(!r[o])return void console.debug(`Session path ${e} not found at level ${o}`);r=r[o]}const o=n[n.length-1];r[o]&&(delete r[o],console.debug(`Cleaned up session ${e}`),this._cleanup_empty_containers(n.slice(0,-1)))}catch(t){console.warn(`Error in complete session cleanup for ${e}:`,t)}}_cleanup_empty_containers(e){try{for(let t=e.length-1;t>=0;t--){let n=this._object_store;for(let r=0;r<t;r++)if(n=n[e[r]],!n)return;const r=e[t],o=n[r];if(!o||"object"!=typeof o||0!==Object.keys(o).length)break;delete n[r],console.debug(`Cleaned up empty container at depth ${t}: ${e.slice(0,t+1).join(".")}`)}}catch(e){console.warn("Error cleaning up empty containers:",e)}}get_session_stats(){const e={total_sessions:0,promise_sessions:0,regular_sessions:0,sessions_with_timers:0,sessions_with_heartbeat:0,system_stores:{},session_ids:[],memory_usage:0};if(!this._object_store)return e;for(const t in this._object_store){const n=this._object_store[t];if(["services","message_cache"].includes(t))e.system_stores[t]={size:"object"==typeof n&&n?Object.keys(n).length:0};else if(n&&"object"==typeof n){Object.keys(n).length>0&&(e.total_sessions++,e.session_ids.push(t),n._promise_manager?e.promise_sessions++:e.regular_sessions++,(n._timer||n.timer)&&e.sessions_with_timers++,(n._heartbeat||n.heartbeat)&&e.sessions_with_heartbeat++,e.memory_usage+=JSON.stringify(n).length)}}return e}_force_cleanup_all_sessions(){if(!this._object_store)return void console.debug("Force cleaning up 0 sessions");let e=0;const t=[];for(const n in this._object_store)if(!["services","message_cache"].includes(n)){const r=this._object_store[n];r&&"object"==typeof r&&Object.keys(r).length>0&&(t.push(n),e++)}for(const e of t)delete this._object_store[e];this._targetIdIndex={},console.debug(`Force cleaning up ${e} sessions`)}_sweepStaleSessions(){const e=Date.now();let t=0;for(const n of Object.keys(this._object_store)){if("services"===n||"message_cache"===n)continue;const r=this._object_store[n],o=r&&(r._last_activity_at||r._created_at);if(r&&"object"==typeof r&&o&&e-o>this._sessionMaxAge&&(!r.timer||!r.timer.started)){if("function"==typeof r.resolve||"function"==typeof r.reject)continue;this._removeFromTargetIdIndex(n),r.heartbeat_task&&clearInterval(r.heartbeat_task),delete this._object_store[n],t++}}t>0&&console.debug(`Swept ${t} stale session(s)`)}_is_promise_method_call(e){const t=e.split(".")[0],n=this._get_session_store(t,!1);return n&&n._promise_manager}_create_promise_manager(){return{should_cleanup_on_callback:e=>["resolve","reject"].includes(e),settle:()=>{console.debug("Promise settled")}}}async _encode_promise(e,t,n,r,o,s,i){let c=this._get_session_store(n,!0);c||(console.warn(`Failed to create session store ${n}, session management may be impaired`),c={}),c._promise_manager=this._create_promise_manager();let a={};return o&&t&&this._method_timeout?([a.heartbeat,c.heartbeat]=this._encode_callback("heartbeat",o.reset.bind(o),n,!1,null,s),c.timer=o,a.interval=this._method_timeout/2):o=null,[a.resolve,c.resolve]=this._encode_callback("resolve",e,n,r,o,s,`resolve (${i})`),[a.reject,c.reject]=this._encode_callback("reject",t,n,r,o,s,`reject (${i})`),a}async _send_chunks(e,t,n){const o=await this.get_remote_service(`${t}:built-in`);if(!o.message_cache)throw new Error("Remote client does not support message caching for large messages.");const s=o.message_cache,i=n||(0,r.randId)(),c=e.length,a=Date.now(),l=Math.ceil(c/this._long_message_chunk_size);if(o.config.api_version>=3){await s.create(i,!!n);const t=new r.Semaphore(30),o=[];for(let r=0;r<l;r++){const c=r*this._long_message_chunk_size,a=e.slice(c,c+this._long_message_chunk_size),l=async()=>{await s.set(i,r,a,!!n)};o.push(t.run(l))}try{await Promise.all(o)}catch(e){try{await s.remove(i)}catch(e){console.error(`Failed to clean up message cache after error: ${e}`)}throw e}}else{await s.create(i,!!n);for(let t=0;t<l;t++){const r=t*this._long_message_chunk_size,o=e.slice(r,r+this._long_message_chunk_size);await s.append(i,o,!!n)}}await s.process(i,!!n),((Date.now()-a)/1e3).toFixed(2)}emit(e,t){if((0,r.assert)("object"==typeof e&&e.type,"Invalid message, must be an object with a `type` fields."),!e.to)return void this._fire(e.type,e);let n=(0,i.encode)(e);if(t){const e=(0,i.encode)(t),r=new Uint8Array(n.length+e.length);r.set(n),r.set(e,n.length),n=r}const o=n.length;return o>this._long_message_chunk_size+1024&&console.warn(`Sending large message (size=${o})`),this._emit_message(n)}_generate_remote_method(e,t,n,o,s){let c=e._rtarget;o&&!c.includes("/")&&(c.startsWith("*/")||(o!==c&&(c=o+"/"+c),e._rtarget=c));let a=e._rmethod,l=e._rpromise||!1;const _=`method: ${a}, docs: ${e._rdoc}`,d=this;function h(){return new Promise(async(e,o)=>{try{let u=(0,r.randId)();n&&(u=n+"."+u);let p=d._get_session_store(u,!0);if(!p)return void o(new Error(`Runtime Error: Failed to get session store ${u} (context: ${_})`));p.target_id=c;const f=u.split(".")[0];c in d._targetIdIndex||(d._targetIdIndex[c]=new Set),d._targetIdIndex[c].add(f);const g=await d._encode(Array.prototype.slice.call(arguments),u,s),y=g.length,w=y>0&&"object"==typeof g[y-1]&&null!==g[y-1]&&g[y-1]._rkwargs;let b;w&&delete g[y-1]._rkwargs,b=d._local_workspace?d._local_workspace+"/"+d._client_id:d._client_id;let v={type:"method",from:b,to:c,method:a},k={};g&&(k.args=g),w&&(k.with_kwargs=w),t&&(v.parent=t);let E=null;if(l){v.session=u;let t=`${c}:${a}`;const n=function(e){o(new Error(e)),d._object_store[u]&&(d._removeFromTargetIdIndex(u),delete d._object_store[u],console.debug(`Cleaned up session ${u} after timeout`))};E=new m(d._method_timeout,n,[`Method call timed out: ${t}, context: ${_}`],t);let r=!0;const i=await d._encode_promise(e,o,u,r,E,s,_);if(!0===l)k.promise=i;else{if("*"!==l)throw new Error(`Unsupported promise type: ${l}`);k.promise="*",k.t=d._method_timeout/2}}let S=(0,i.encode)(v);if(k){const e=(0,i.encode)(k),t=new Uint8Array(S.length+e.length);t.set(S),t.set(e,S.length),S=t}S.length<=d._long_message_chunk_size+1024||h.__no_chunk__?d._emit_message(S).then(function(){E&&E.start(),l||e(null)}).catch(function(e){const t=`Failed to send the request when calling method (${c}:${a}), error: ${e}`;o?o(new Error(t)):console.warn("Unhandled RPC method call error:",t),E&&E.started&&E.clear()}):d._send_chunks(S,c,t).then(function(){E&&E.start(),l||e(null)}).catch(function(e){const t=`Failed to send the request when calling method (${c}:${a}), error: ${e}`;o?o(new Error(t)):console.warn("Unhandled RPC method call error:",t),E&&E.started&&E.clear()})}catch(e){o(e)}})}h.__rpc_object__=e;const u=a.split(".");return h.__name__=e._rname||u[u.length-1],h.__name__.includes("#")&&(h.__name__=h.__name__.split("#")[1]),h.__doc__=e._rdoc||`Remote method: ${a}`,h.__schema__=e._rschema,h.__no_chunk__="services.built-in.message_cache.append"===e._rmethod,h}get_client_info(){const e=[];for(let t of Object.values(this._services))e.push(this._extract_service_info(t));return{id:this._client_id,services:e}}async _handle_method(e){let t=null,n=null,o=null;try{(0,r.assert)(e.method&&e.ctx&&e.from);const s=e.from+":"+e.method,i=e.from.split("/")[0],c=e.from.split("/")[1];let a;e.to=e.to.includes("/")?e.to:i+"/"+e.to,e.ctx.to=e.to,this._local_workspace?(this._local_workspace&&"*"!==this._local_workspace&&(0,r.assert)(e.to.split("/")[0]===this._local_workspace,"Workspace mismatch: "+e.to.split("/")[0]+" != "+this._local_workspace),a=this._local_workspace):a=e.to.split("/")[0];const l=e.parent;if(e.promise){const h=await this._decode("*"===e.promise?this._expand_promise(e):e.promise,e.session,l,i,a);if(t=h.resolve,n=h.reject,h.heartbeat&&h.interval){async function u(){try{await h.heartbeat()}catch(e){console.error(e)}}if(o=setInterval(u,1e3*h.interval),e.session){const f=this._get_session_store(e.session,!1);f&&(f.heartbeat_task=o)}}}let _,d;try{_=p(this._object_store,e.method);const m=e.method.split(".");if(m.length>1){const g=m[0];if("services"!==g&&"message_cache"!==g){const y=this._object_store[g];y&&"object"==typeof y&&(y._last_activity_at=Date.now())}}}catch(w){if(this._is_promise_method_call(e.method))return void console.debug(`Promise method ${e.method} not available (detected by session type), ignoring: ${s}`);const b=e.method.split(".");if(b.length>1){const k=b[0];return k in this._object_store?(console.debug(`Session ${k} exists but method ${e.method} not found, likely expired callback: ${s}`),void("function"==typeof n&&n(new Error(`Method expired or not found: ${s}`)))):(console.debug(`Session ${k} not found for method ${e.method}, likely cleaned up: ${s}`),void("function"==typeof n&&n(new Error(`Session not found: ${s}`))))}console.debug(`Failed to find method ${s} at ${this._client_id}`);const v=new Error(`Method not found: ${s} at ${this._client_id}`);return void("function"==typeof n?n(v):console.warn("Method not found and no reject callback:",v.message))}if((0,r.assert)(_&&"function"==typeof _,"Invalid method: "+s),this._method_annotations.has(_)){if("protected"===this._method_annotations.get(_).visibility)if(a===i);else if(this._method_annotations.get(_).authorized_workspaces&&this._method_annotations.get(_).authorized_workspaces.includes(i));else if("*"!==i||c!==this._connection.manager_id)throw new Error("Permission denied for invoking protected method "+s+", workspace mismatch: "+a+" != "+i)}else{let E=this._object_store[e.method.split(".")[0]].target_id;if(a===i&&E&&-1===E.indexOf("/")&&(E=a+"/"+E),E!==e.from)throw new Error("Access denied for method call ("+s+") from "+e.from+" to target "+E)}if(l&&!e.method.startsWith("services.")&&(0,r.assert)(null!==this._get_session_store(l,!0),"Parent session was closed: "+l),d=e.args?await this._decode(e.args,e.session,null,i,null):[],this._method_annotations.has(_)&&this._method_annotations.get(_).require_context){if(d.length+1<_.length)for(let S=d.length;S<_.length-1;S++)d.push(void 0);d.push(e.ctx)}if(e.promise){const x=_.apply(null,d);x instanceof Promise?x.then(e=>{t(e)}).catch(e=>{n(e)}).finally(()=>{clearInterval(o)}):(t(x),clearInterval(o))}else _.apply(null,d),clearInterval(o)}catch(T){n?n(T):console.error("Error during calling method: ",T),clearInterval(o)}}encode(e,t){return this._encode(e,t)}_get_session_store(e,t){if(!e)return null;let n=this._object_store;const r=e.split(".");if(t){const e=r.length-1;for(let t of r.slice(0,e))n[t]||(n[t]={}),n=n[t];if(!n[r[e]]){n[r[e]]={};const t=Date.now();n[r[e]]._created_at=t,n[r[e]]._last_activity_at=t}return n[r[e]]}for(let e of r){if(!n[e])return null;n=n[e]}return n}async _encode(e,t,n){const o=typeof e;if("number"===o||"string"===o||"boolean"===o||null==e||e instanceof Uint8Array)return e;if(e instanceof ArrayBuffer)return{_rtype:"memoryview",_rvalue:new Uint8Array(e)};if(e.__rpc_object__){if((e.__rpc_object__._rserver||this._server_base_url)===this._server_base_url)return e.__rpc_object__}let s;if(e.constructor instanceof Object&&e._rtype){const c=e._rtype;return delete e._rtype,s=await this._encode(e,t,n),s._rtype=c,s}if((0,r.isGenerator)(e)||(0,r.isAsyncGenerator)(e)||(0,r.isAsyncIterator)(e)||(0,r.isSyncIterator)(e)){(0,r.assert)(t&&"string"==typeof t,"Session ID is required for generator encoding");const l=(0,r.randId)(),h=l+":close",u=this._get_session_store(t,!0);(0,r.assert)(null!==u,`Failed to create session store ${t} due to invalid parent`);const p=(0,r.isAsyncGenerator)(e)||(0,r.isAsyncIterator)(e),f=async()=>{if(p){const t=await e.next();return t.done?(delete u[l],delete u[h],{_rtype:"stop_iteration"}):t.value}{const t=e.next();return t.done?(delete u[l],delete u[h],{_rtype:"stop_iteration"}):t.value}},m=async()=>{try{"function"==typeof e.return&&(p?await e.return():e.return())}catch(e){}finally{delete u[l],delete u[h]}return!0};return u[l]=f,u[h]=m,s={_rtype:"generator",_rserver:this._server_base_url,_rtarget:this._client_id,_rmethod:`${t}.${l}`,_rclose_method:`${t}.${h}`,_rpromise:"*",_rdoc:"Remote generator"},s}if("function"==typeof e){if(this._method_annotations.has(e)){let y=this._method_annotations.get(e);s={_rtype:"method",_rserver:this._server_base_url,_rtarget:this._client_id,_rmethod:y.method_id,_rpromise:"*",_rname:e.name}}else{let w;(0,r.assert)("string"==typeof t),w=e.__name__?`${(0,r.randId)()}#${e.__name__}`:(0,r.randId)(),s={_rtype:"method",_rserver:this._server_base_url,_rtarget:this._client_id,_rmethod:`${t}.${w}`,_rpromise:"*",_rname:e.name};let b=this._get_session_store(t,!0);(0,r.assert)(null!==b,`Failed to create session store ${t} due to invalid parent`),b[w]=e}if(s._rdoc=e.__doc__,!s._rdoc)try{const v=function(e){const t=e.toString(),n=t.match(/function\s*(\w*)/),r=n&&n[1]||"",o=t.match(/\(([^)]*)\)/);let s="";o&&(s=o[1].split(",").map(e=>e.replace(/\/\*.*?\*\//g,"").replace(/\/\/.*$/g,"")).filter(e=>e.trim().length>0).map(e=>e.trim()).join(", "));let i=t.match(/\)\s*\{\s*\/\*([\s\S]*?)\*\//);const c=i&&i[1].trim()||"";i=t.match(/\)\s*\{\s*(\/\/[\s\S]*?)\n\s*[^\s\/]/);const a=i&&i[1].split("\n").map(e=>e.replace(/^\/\/\s*/,"").trim()).join("\n")||"",l=c||a;return r&&s.length>0&&{name:r,sig:s,doc:l}}(e);v&&!s._rdoc&&(s._rdoc=`${v.doc}`)}catch(k){console.error("Failed to extract function docstring:",e)}return s._rschema=e.__schema__,s}const i=Array.isArray(e);for(let E of Object.keys(this._codecs)){const S=this._codecs[E];if(S.encoder&&e instanceof S.type){let x=await Promise.resolve(S.encoder(e));if(x&&!x._rtype&&(x._rtype=S.name),"object"==typeof x){const T=x._rtype;delete x._rtype,x=await this._encode(x,t,n),x._rtype=T}return s=x,s}}if("undefined"!=typeof tf&&tf.Tensor&&e instanceof tf.Tensor){const C=e.dataSync();s={_rtype:"ndarray",_rvalue:new Uint8Array(C.buffer),_rshape:e.shape,_rdtype:e.dtype}}else if("undefined"!=typeof nj&&nj.NdArray&&e instanceof nj.NdArray){if(!e.selection||!e.selection.data)throw new Error("Invalid NumJS array: missing selection or data");const j=(0,r.typedArrayToDtype)(e.selection.data);s={_rtype:"ndarray",_rvalue:new Uint8Array(e.selection.data.buffer),_rshape:e.shape,_rdtype:j}}else if(e instanceof Error)console.error(e),s={_rtype:"error",_rvalue:e.toString(),_rtrace:e.stack};else if(e!==Object(e)||e instanceof Boolean||e instanceof String||e instanceof Date||e instanceof RegExp||"undefined"!=typeof ImageData&&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 R=0;async function P(t){let n;n=t?e.slice(R,R+t):e.slice(R);const r=new Uint8Array(await n.arrayBuffer());return R+=r.byteLength,r}function I(e){R=e}s={_rtype:"iostream",_rnative:"js:blob",type:e.type,name:e.name,size:e.size,path:e._path||e.webkitRelativePath,read:await this._encode(P,t,n),seek:await this._encode(I,t,n)}}else if(e instanceof a){const D=(0,r.typedArrayToDtype)(e);s={_rtype:"typedarray",_rvalue:new Uint8Array(e.buffer),_rdtype:D}}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,n)};else if(e instanceof Map)s={_rtype:"orderedmap",_rvalue:await this._encode(Array.from(e),t,n)};else{if(!(e.constructor===Object||Array.isArray(e)||e instanceof g))throw`hypha-rpc: Unsupported data type: ${e}, you can register a custom codec to encode/decode the object.`;{if(!i&&!0===e._rintf&&Object.keys(e).some(t=>!t.startsWith("_")&&"function"==typeof e[t])){const O=`_rintf_${(0,r.randId)()}`,$={id:O};for(const U of Object.keys(e))U.startsWith("_")||"function"!=typeof e[U]||($[U]=e[U]);this.add_service($,!0),e._rintf_service_id=O,s={};for(const L of Object.keys(e))s[L]=await this._encode(e[L],t,n);return s._rintf_service_id=O,s}if(i){if(_(e))return e}else if(!("_rtype"in e||e instanceof g)&&d(e))return e;s=i?[]:{};const A=Object.keys(e);for(let M of A)s[M]=await this._encode(e[M],t,n)}}if(!s)throw new Error("Failed to encode object");return s}async decode(e){return await this._decode(e)}async _decode(e,t,n,o,s){if(!e)return e;let i;if(e._rtype)if(this._codecs[e._rtype]&&this._codecs[e._rtype].decoder){const c=e._rtype;delete e._rtype,(e=await this._decode(e,t,n,o,s))._rtype=c,i=await Promise.resolve(this._codecs[e._rtype].decoder(e))}else if("method"===e._rtype)i=this._generate_remote_method(e,t,n,o,s);else if("generator"===e._rtype){const a=this._generate_remote_method(e,t,n,o,s);let l=null;if(e._rclose_method){const p={_rtype:"method",_rserver:e._rserver,_rtarget:e._rtarget,_rmethod:e._rclose_method,_rpromise:"*"};l=this._generate_remote_method(p,t,n,o,s)}async function*u(){let e=!1;try{for(;;){const t=await a();if(t&&"stop_iteration"===t._rtype){e=!0;break}yield t}}catch(e){throw console.error("Error in generator:",e),e}finally{if(!e&&l)try{await l()}catch(e){}}}i=u()}else if("ndarray"===e._rtype)if("undefined"!=typeof nj&&nj.array)Array.isArray(e._rvalue)&&(e._rvalue=e._rvalue.reduce(h)),i=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(h));const f=r.dtypeToTypedArray[e._rdtype];i=tf.tensor(new f(e._rvalue),e._rshape,e._rdtype)}else i=e;else if("error"===e._rtype)i=new Error("RemoteError: "+e._rvalue+"\n"+(e._rtrace||""));else if("typedarray"===e._rtype){const m=r.dtypeToTypedArray[e._rdtype];if(!m)throw new Error("unsupported dtype: "+e._rdtype);i=new m(e._rvalue.buffer.slice(e._rvalue.byteOffset,e._rvalue.byteOffset+e._rvalue.byteLength))}else if("memoryview"===e._rtype)i=e._rvalue.buffer.slice(e._rvalue.byteOffset,e._rvalue.byteOffset+e._rvalue.byteLength);else if("iostream"===e._rtype){if("js:blob"===e._rnative){const g=await this._generate_remote_method(e.read,t,n,o,s),y=await g();i=new Blob([y],{type:e.type,name:e.name})}else{i={};for(let w of Object.keys(e))w.startsWith("_")||(i[w]=await this._decode(e[w],t,n,o,s))}i.__rpc_object__=e}else if("orderedmap"===e._rtype)i=new Map(await this._decode(e._rvalue,t,n,o,s));else if("set"===e._rtype)i=new Set(await this._decode(e._rvalue,t,n,o,s));else{const b=e._rtype;delete e._rtype,i=await this._decode(e,t,n,o,s),i._rtype=b}else if(e.constructor===Object||Array.isArray(e)){const v=Array.isArray(e);if(v){if(_(e))return e}else if(d(e))return e;i=v?[]:{};for(let k of Object.keys(e))if(v||e.hasOwnProperty(k)){const E=e[k];i[k]=await this._decode(E,t,n,o,s)}}else i=e;if(void 0===i)throw new Error("Failed to decode object");return i}_expand_promise(e){return{heartbeat:{_rtype:"method",_rtarget:e.from.split("/")[1],_rmethod:e.session+".heartbeat",_rdoc:`heartbeat callback for method: ${e.method}`},resolve:{_rtype:"method",_rtarget:e.from.split("/")[1],_rmethod:e.session+".resolve",_rdoc:`resolve callback for method: ${e.method}`},reject:{_rtype:"method",_rtarget:e.from.split("/")[1],_rmethod:e.session+".reject",_rdoc:`reject callback for method: ${e.method}`},interval:e.t}}}},"./src/utils/index.js":
7
+ \********************/(e,t,n)=>{n.r(t),n.d(t,{API_VERSION:()=>c,RPC:()=>y});var r=n(/*! ./utils/index.js */"./src/utils/index.js"),o=n(/*! ./utils/schema.js */"./src/utils/schema.js"),i=n(/*! @msgpack/msgpack */"./node_modules/@msgpack/msgpack/dist.es5+esm/decode.mjs"),s=n(/*! @msgpack/msgpack */"./node_modules/@msgpack/msgpack/dist.es5+esm/encode.mjs");const c=3,a=Object.getPrototypeOf(Object.getPrototypeOf(new Uint8Array)).constructor;function l(e){if(null==e)return!0;const t=typeof e;return"number"===t||"string"===t||"boolean"===t}function d(e){for(let t=0;t<e.length;t++){const n=e[t];if(!l(n)&&!(n instanceof Uint8Array))if(Array.isArray(n)){if(!d(n))return!1}else{if(!n||n.constructor!==Object)return!1;if("_rtype"in n)return!1;if(!h(n))return!1}}return!0}function h(e){const t=Object.values(e);for(let e=0;e<t.length;e++){const n=t[e];if(!l(n)&&!(n instanceof Uint8Array))if(Array.isArray(n)){if(!d(n))return!1}else{if(!n||n.constructor!==Object)return!1;if("_rtype"in n)return!1;if(!h(n))return!1}}return!0}function u(e,t){const n=new Uint8Array(e.byteLength+t.byteLength);return n.set(new Uint8Array(e),0),n.set(new Uint8Array(t),e.byteLength),n.buffer}function _(e,t,n="Operation timed out"){return new Promise((r,o)=>{const i=setTimeout(()=>{o(new Error(`TimeoutError: ${n}`))},t);e.then(e=>{clearTimeout(i),r(e)}).catch(e=>{clearTimeout(i),o(e)})})}function p(e,t){if(!t)throw new Error("undefined index");return"string"==typeof t?p(e,t.split(".")):0===t.length?e:p(e[t[0]],t.slice(1))}function f(e,t=null,n=!1){if(Array.isArray(e))return e.map((e,t)=>f(e,null,n));if("object"==typeof e&&null!==e){let t={};for(let r in e)t[r]=f(e[r],r,n);return t}if("function"==typeof e){if(e.__schema__){const r=JSON.parse(JSON.stringify(e.__schema__));if(t&&(r.name=t,e.__schema__.name=t),n&&(r.parameters&&r.parameters.properties&&delete r.parameters.properties.context,r.parameters&&r.parameters.required)){const e=r.parameters.required.indexOf("context");e>-1&&r.parameters.required.splice(e,1)}return{type:"function",function:r}}return{type:"function",function:{name:t||e.name||"function"}}}return"number"==typeof e?{type:"number"}:"string"==typeof e?{type:"string"}:"boolean"==typeof e?{type:"boolean"}:null===e?{type:"null"}:{}}class m{constructor(e,t,n,r){this._timeout=e,this._callback=t,this._args=n,this._label=r||"timer",this._task=null,this.started=!1}start(){this.started?this.reset():(this._task=setTimeout(()=>{this._callback.apply(this,this._args)},1e3*this._timeout),this.started=!0)}clear(){this._task&&this.started?(clearTimeout(this._task),this._task=null,this.started=!1):console.warn(`Clearing a timer (${this._label}) which is not started`)}reset(){this._task&&clearTimeout(this._task),this._task=setTimeout(()=>{this._callback.apply(this,this._args)},1e3*this._timeout),this.started=!0}}class g extends Object{}class y extends r.MessageEmitter{constructor(e,{client_id:t=null,default_context:n=null,name:o=null,codecs:i=null,method_timeout:s=null,max_message_buffer_size:a=0,debug:l=!1,workspace:d=null,silent:h=!1,app_id:u=null,server_base_url:p=null,long_message_chunk_size:f=null}){if(super(l),this._codecs=i||{},(0,r.assert)(t&&"string"==typeof t),(0,r.assert)(t,"client_id is required"),this._client_id=t,this._name=o,this._app_id=u||"*",this._local_workspace=d,this._silent=h,this.default_context=n||{},this._method_annotations=new WeakMap,this._max_message_buffer_size=a,this._chunk_store={},this._method_timeout=s||30,this._server_base_url=p,this._long_message_chunk_size=f||262144,this._services={},this._object_store={services:this._services},this._targetIdIndex={},this._background_tasks=new Set,this._sessionMaxAge=6e5,this._sessionSweepInterval=setInterval(()=>{this._sweepStaleSessions()},this._sessionMaxAge/2),this._unhandledRejectionHandler=e=>{const t=e.reason;if(t&&"object"==typeof t){const n=t.toString();if(n.includes("Method not found")||n.includes("Session not found")||n.includes("Method expired")||n.includes("Connection is closed")||n.includes("Client disconnected")||n.includes("RPC connection closed"))return console.debug("Ignoring expected disconnection/method error:",t),void e.preventDefault()}console.warn("Unhandled RPC promise rejection:",t)},this._unhandledRejectionNodeHandler=null,y._rejectionHandlerCount||(y._rejectionHandlerCount=0),y._rejectionHandlerCount++,1===y._rejectionHandlerCount&&("undefined"!=typeof window?window.addEventListener("unhandledrejection",this._unhandledRejectionHandler):"undefined"!=typeof process&&(this._unhandledRejectionNodeHandler=(e,t)=>{this._unhandledRejectionHandler({reason:e,promise:t,preventDefault:()=>{}})},process.on("unhandledRejection",this._unhandledRejectionNodeHandler))),e){this.add_service({id:"built-in",type:"built-in",name:`Built-in services for ${this._local_workspace}/${this._client_id}`,config:{require_context:!0,visibility:"public",api_version:c},ping:this._ping.bind(this),get_service:this.get_local_service.bind(this),message_cache:{create:this._create_message.bind(this),append:this._append_message.bind(this),set:this._set_message.bind(this),process:this._process_message.bind(this),remove:this._remove_message.bind(this)}}),this._boundHandleMethod=this._handle_method.bind(this),this._boundHandleError=console.error,this.on("method",this._boundHandleMethod),this.on("error",this._boundHandleError),(0,r.assert)(e.emit_message&&e.on_message),(0,r.assert)(void 0!==e.manager_id,"Connection must have manager_id"),this._emit_message=e.emit_message.bind(e),e.on_message(this._on_message.bind(this)),this._connection=e;const t=async e=>{if(!this._silent&&this._connection.manager_id){console.debug("Connection established, reporting services...");try{const e=await this.get_manager_service({timeout:20,case_conversion:"camel"}),t=Object.values(this._services),n=t.length;let r=0;const o=[],i=this._method_timeout||3e4;for(let n of t)try{const t=this._extract_service_info(n);await _(e.registerService(t),i,`Timeout registering service ${n.id||"unknown"}`),r++,console.debug(`Successfully registered service: ${n.id||"unknown"}`)}catch(e){o.push(n.id||"unknown"),e.message&&e.message.includes("TimeoutError")?console.error(`Timeout registering service ${n.id||"unknown"}`):console.error(`Failed to register service ${n.id||"unknown"}: ${e}`)}r===n?console.info(`Successfully registered all ${r} services with the server`):console.warn(`Only registered ${r} out of ${n} services with the server. Failed services: ${o.join(", ")}`),this._fire("services_registered",{total:n,registered:r,failed:o});try{if(e.subscribe&&"function"==typeof e.subscribe){console.debug("Subscribing to client_disconnected events");const t=async e=>{const t=e.data?.id||e.client,n=e.data?.workspace;if(t&&n){const e=`${n}/${t}`;console.debug(`Client ${e} disconnected, cleaning up sessions`),await this._handleClientDisconnected(e)}else t&&(console.debug(`Client ${t} disconnected, cleaning up sessions`),await this._handleClientDisconnected(t))};this._clientDisconnectedSubscription=await _(e.subscribe(["client_disconnected"]),i,"Timeout subscribing to client_disconnected events"),this.on("client_disconnected",t),console.debug("Successfully subscribed to client_disconnected events")}else console.debug("Manager does not support subscribe method, skipping client_disconnected handling"),this._clientDisconnectedSubscription=null}catch(e){console.debug(`Failed to subscribe to client_disconnected events: ${e}`),this._clientDisconnectedSubscription=null}}catch(e){console.error(`Failed to get manager service for registering services: ${e}`),this._fire("services_registration_failed",{error:e.toString(),total_services:Object.keys(this._services).length})}}e&&(e.public_base_url&&(this._server_base_url=e.public_base_url),this._fire("connected",e))};e.on_connected(t),"function"==typeof e.on_disconnected&&e.on_disconnected(t=>{e._enable_reconnect?console.info(`Connection lost (${t}), reconnection enabled - pending calls will be handled by timeout`):(console.warn(`Connection lost (${t}), rejecting all pending RPC calls`),this._rejectPendingCalls(`Connection lost: ${t||"unknown reason"}`))}),t()}else this._emit_message=function(){console.log("No connection to emit message")}}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(0,r.assert)("ping"==e),"pong"}async ping(e,t){let n=this._generate_remote_method({_rserver:this._server_base_url,_rtarget:e,_rmethod:"services.built-in.ping",_rpromise:!0,_rdoc:"Ping a remote client"});(0,r.assert)("pong"==await n("ping",t))}_create_message(e,t,n,r){if(t){if(!this._object_store[e])throw new Error(`session does not exist anymore: ${e}`);this._object_store[e].timer.reset()}this._object_store.message_cache||(this._object_store.message_cache={});const o=this._object_store.message_cache,i=Object.keys(o);if(i.length>=256){const e=Date.now();for(const t of i){const n=o[t];n&&n._cache_created_at&&e-n._cache_created_at>3e5&&delete o[t]}const t=Object.keys(o);t.length>=256&&t.sort((e,t)=>(o[e]._cache_created_at||0)-(o[t]._cache_created_at||0)).slice(0,t.length-256+1).forEach(e=>delete o[e])}if(!n&&o[e])throw new Error(`Message with the same key (${e}) already exists in the cache store, please use overwrite=true or remove it first.`);o[e]=[],o[e]._cache_created_at=Date.now()}_append_message(e,t,n,o){if(n){if(!this._object_store[e])throw new Error(`session does not exist anymore: ${e}`);this._object_store[e].timer.reset()}const i=this._object_store.message_cache;if(!i[e])throw new Error(`Message with key ${e} does not exists.`);(0,r.assert)(t instanceof a),i[e].push(t)}_set_message(e,t,n,o,i){if(o){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.`);(0,r.assert)(n instanceof a),s[e][t]=n}_remove_message(e,t){const n=this._object_store.message_cache;if(!n[e])throw new Error(`Message with key ${e} does not exists.`);delete n[e]}_process_message(e,t,n){if(t){if(!this._object_store[e])throw new Error(`session does not exist anymore: ${e}`);this._object_store[e].timer.reset()}const o=this._object_store.message_cache;if((0,r.assert)(!!n,"Context is required"),!o[e])throw new Error(`Message with key ${e} does not exists.`);var s,c,a,l;o[e]=(s=o[e],c=s.map(function(e){return e.byteLength}),a=c.reduce(function(e,t){return e+t},0),l=new Uint8Array(a),c.reduce(function(e,t,n){return l.set(new Uint8Array(s[n]),e),e+t},0),l.buffer);let d=(0,i.decodeMulti)(o[e]);const{done:h,value:u}=d.next(),_=u;if(Object.assign(_,{from:n.from,to:n.to,ws:n.ws,user:n.user}),_.ctx=JSON.parse(JSON.stringify(_)),Object.assign(_.ctx,this.default_context),!h){let e=d.next();Object.assign(_,e.value)}this._fire(_.type,_),delete o[e]}_on_message(e){if("string"==typeof e){const t=JSON.parse(e);t.ctx=Object.assign({},t,this.default_context),this._fire(t.type,t)}else if(e instanceof ArrayBuffer||ArrayBuffer.isView(e)){let t=(0,i.decodeMulti)(e);const{done:n,value:r}=t.next(),o=r;if(o.ctx=Object.assign({},o,this.default_context),!n){let e=t.next();Object.assign(o,e.value)}this._fire(o.type,o)}else{if("object"!=typeof e)throw new Error("Invalid message format");e.ctx=Object.assign({},e,this.default_context),this._fire(e.type,e)}}reset(){this._removeRejectionHandler(),this._event_handlers={},this._services={}}_removeRejectionHandler(){y._rejectionHandlerCount&&y._rejectionHandlerCount>0&&(y._rejectionHandlerCount--,0===y._rejectionHandlerCount&&("undefined"!=typeof window&&this._unhandledRejectionHandler?window.removeEventListener("unhandledrejection",this._unhandledRejectionHandler):"undefined"!=typeof process&&this._unhandledRejectionNodeHandler&&process.removeListener("unhandledRejection",this._unhandledRejectionNodeHandler))),this._unhandledRejectionHandler=null,this._unhandledRejectionNodeHandler=null}close(){if(this._cleanupOnDisconnect(),this._boundHandleMethod&&(this.off("method",this._boundHandleMethod),this._boundHandleMethod=null),this._boundHandleError&&(this.off("error",this._boundHandleError),this._boundHandleError=null),this._clientDisconnectedSubscription){try{"function"==typeof this._clientDisconnectedSubscription.unsubscribe&&this._clientDisconnectedSubscription.unsubscribe()}catch(e){console.debug(`Error unsubscribing client_disconnected: ${e}`)}this.off("client_disconnected"),this._clientDisconnectedSubscription=null}this._removeRejectionHandler(),this.off();try{for(const e of this._background_tasks)if(e&&"function"==typeof e.cancel)try{e.cancel()}catch(e){console.debug(`Error canceling background task: ${e}`)}this._background_tasks.clear()}catch(e){console.debug(`Error cleaning up background tasks: ${e}`)}this._sessionSweepInterval&&(clearInterval(this._sessionSweepInterval),this._sessionSweepInterval=null);try{this._connection=null,this._emit_message=function(){return console.debug("RPC connection closed, ignoring message"),Promise.reject(new Error("Connection is closed"))}}catch(e){console.debug(`Error during connection cleanup: ${e}`)}this._fire("disconnected")}async _handleClientDisconnected(e){try{console.debug(`Handling disconnection for client: ${e}`);const t=this._cleanupSessionsForClient(e);t>0&&console.debug(`Cleaned up ${t} sessions for disconnected client: ${e}`),this._fire("remote_client_disconnected",{client_id:e,sessions_cleaned:t})}catch(t){console.error(`Error handling client disconnection for ${e}: ${t}`)}}_removeFromTargetIdIndex(e){const t=e.split(".")[0],n=this._object_store[t];if(n&&"object"==typeof n){const e=n.target_id;e&&e in this._targetIdIndex&&(this._targetIdIndex[e].delete(t),0===this._targetIdIndex[e].size&&delete this._targetIdIndex[e])}}_cleanupSessionEntry(e,t=null){if(e&&"object"==typeof e){if(t&&e.reject&&"function"==typeof e.reject)try{e.reject(new Error(t))}catch(e){console.debug(`Error rejecting session: ${e}`)}if(e.heartbeat_task)try{clearInterval(e.heartbeat_task)}catch(e){}if(e.timer&&e.timer.started&&"function"==typeof e.timer.clear)try{e.timer.clear()}catch(e){}}}_cleanupSessionsForClient(e){let t=0;const n=this._targetIdIndex[e];if(!n)return 0;const r=`Client disconnected: ${e}`;for(const o of n){const n=this._object_store[o];n&&"object"==typeof n&&(n.target_id===e&&(this._cleanupSessionEntry(n,r),delete this._object_store[o],t++,console.debug(`Cleaned up session: ${o}`)))}return delete this._targetIdIndex[e],t}_rejectPendingCalls(e="Connection lost"){try{let t=0;for(const n of Object.keys(this._object_store)){if("services"===n||"message_cache"===n)continue;const r=this._object_store[n];"object"==typeof r&&null!==r&&(r.reject&&"function"==typeof r.reject&&t++,this._cleanupSessionEntry(r,e))}t>0&&console.warn(`Rejected ${t} pending RPC call(s) due to: ${e}`)}catch(e){console.error(`Error rejecting pending calls: ${e}`)}}_cleanupOnDisconnect(){try{console.debug("Cleaning up all sessions due to local RPC disconnection");const e=[];for(const t of Object.keys(this._object_store)){if("services"===t||"message_cache"===t)continue;const n=this._object_store[t];this._cleanupSessionEntry(n,"RPC connection closed"),e.push(t)}for(const t of e)delete this._object_store[t];this._targetIdIndex={}}catch(e){console.error(`Error during cleanup on disconnect: ${e}`)}}async disconnect(){const e=this._connection;if(this.close(),e)try{await e.disconnect()}catch(e){console.debug(`Error disconnecting underlying connection: ${e}`)}}async get_manager_service(e,t=20){e=e||{};let n=null;for(let r=0;r<t;r++){const o=Math.min(500*Math.pow(2,r),1e4);if(!this._connection.manager_id){if(r<t-1){console.warn(`Manager ID not set, retrying in ${o}ms (attempt ${r+1}/${t})`),await new Promise(e=>setTimeout(e,o));continue}throw new Error("Manager ID not set after maximum retries")}try{return await this.get_remote_service(`*/${this._connection.manager_id}:default`,e)}catch(e){n=e,console.warn(`Failed to get manager service (attempt ${r+1}/${t}): ${e.message}`),r<t-1&&await new Promise(e=>setTimeout(e,o))}}throw n}get_all_local_services(){return this._services}get_local_service(e,t){(0,r.assert)(e),(0,r.assert)(t,"Context is required");const[n,o]=t.to.split("/");(0,r.assert)(o===this._client_id,"Services can only be accessed locally");const i=this._services[e];if(!i)throw new Error("Service not found: "+e);if("public"==i.config.visibility||"unlisted"==i.config.visibility)return i;if(t.ws===n)return i;const s=i.config.authorized_workspaces;if(s&&s.includes(t.ws))return i;throw new Error(`Permission denied for getting protected service: ${e}, workspace mismatch: ${n} != ${t.ws}`)}async get_remote_service(e,t){let{timeout:n,case_conversion:o,kwargs_expansion:i}=t||{};n=void 0===n?this._method_timeout:n,!e&&this._connection.manager_id?e="*/"+this._connection.manager_id:e.includes(":")||(e=this._client_id+":"+e);const s=e.split(":")[0];let c=e.split(":")[1];if(c.includes("@")){c=c.split("@")[0];const t=e.split("@")[1];this._app_id&&"*"!==this._app_id&&(0,r.assert)(t===this._app_id,`Invalid app id: ${t} != ${this._app_id}`)}(0,r.assert)(s,`Invalid service uri: ${e}`);try{const t=this._generate_remote_method({_rserver:this._server_base_url,_rtarget:s,_rmethod:"services.built-in.get_service",_rpromise:!0,_rdoc:"Get a remote service"});let a=await(0,r.waitFor)(t(c),n,"Timeout Error: Failed to get remote service: "+e);return a.id=`${s}:${c}`,i&&(a=(0,r.expandKwargs)(a)),o?Object.assign(new g,(0,r.convertCase)(a,o)):Object.assign(new g,a)}catch(t){throw console.warn("Failed to get remote service: "+e,t),t}}_annotate_service_methods(e,t,n,r,o,i){if("function"==typeof e){let s=t.split(".")[1];this._method_annotations.set(e,{require_context:Array.isArray(n)?n.includes(s):!!n,run_in_executor:r,method_id:"services."+t,visibility:o,authorized_workspaces:i})}else if(e instanceof Array||e instanceof Object)for(let s of Object.keys(e)){let c=e[s];if("function"==typeof c&&c.__rpc_object__){let t=c.__rpc_object__._rtarget;if(t.includes("/")&&(t=t.split("/")[1]),this._client_id!==t)throw new Error(`Local method not found: ${c.__rpc_object__._rmethod}, client id mismatch ${this._client_id} != ${t}`);e instanceof Array&&(e=e.slice()),e[s]=p(this._object_store,c.__rpc_object__._rmethod),c=e[s]}this._annotate_service_methods(c,t+"."+s,n,r,o,i)}}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={},n=Object.getOwnPropertyNames(e).concat(Object.getOwnPropertyNames(Object.getPrototypeOf(e)));for(let r of n)"constructor"!==r&&("function"==typeof e[r]?t[r]=e[r].bind(e):t[r]=e[r]);e.id=e.id||"default",e=t}(0,r.assert)(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 n=!1,o=!1;e.config.require_context&&(n=e.config.require_context),e.config.run_in_executor&&(o=!0);const i=e.config.visibility||"protected";(0,r.assert)(["protected","public","unlisted"].includes(i));const s=e.config.authorized_workspaces;if(void 0!==s){if("protected"!==i)throw new Error(`authorized_workspaces can only be set when visibility is 'protected', got visibility='${i}'`);if(!Array.isArray(s))throw new Error("authorized_workspaces must be an array of workspace ids");for(const e of s)if("string"!=typeof e)throw new Error("Each workspace id in authorized_workspaces must be a string, got "+typeof e)}if(this._annotate_service_methods(e,e.id,n,o,i,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}_extract_service_info(e){const t=e.config||{};if(t.workspace=t.workspace||this._local_workspace||this._connection.workspace,!t.workspace)throw new Error("Workspace is not set. Please ensure the connection has a workspace or set local_workspace.");const n=t.require_context,r=["id","config","name","description","type","docs","app_id","service_schema"],o={};for(const t of Object.keys(e))r.includes(t)||(o[t]=e[t]);const i=f(o,null,n);return{config:t,id:`${t.workspace}/${this._client_id}:${e.id}`,name:e.name||e.id,description:e.description||"",type:e.type||"generic",docs:e.docs||null,app_id:this._app_id,service_schema:i}}async get_service_schema(e){return f(e,null,e.config.require_context)}async register_service(e,t){let n,{check_type:r,notify:i,overwrite:s}=t||{};if(i=void 0===i||i,r&&e.type)try{n=await this.get_manager_service({timeout:10,case_conversion:"camel"});e=function(e,t){function n(e,t,n="root"){for(let r in t)if(!e.hasOwnProperty(r))throw new Error(`Missing key '${r}' in service at path '${n}'`);for(let r in e)if("type"!==r&&!t.hasOwnProperty(r))throw new Error(`Unexpected key '${r}' in service at path '${n}'`)}return n(e,t.definition),function e(t,r,i="root"){if("object"!=typeof t||Array.isArray(t)){if(Array.isArray(t)){if(t.length!==r.length)throw new Error(`Length mismatch at path '${i}'`);t.forEach((n,s)=>{let c=`${i}[${s}]`;if("object"!=typeof n||Array.isArray(n)){if("function"==typeof n){if(!r.hasOwnProperty(s))throw new Error(`Missing schema for function at index ${s} in path '${c}'`);t[s]=(0,o.schemaFunction)(n,{name:r[s].name,description:r[s].description||"",parameters:r[s].parameters})}}else e(n,r[s],c)})}}else{n(t,r,i);for(let n in t){let s=t[n],c=`${i}.${n}`;if("object"!=typeof s||Array.isArray(s)){if("function"==typeof s){if(!r.hasOwnProperty(n))throw new Error(`Missing schema for function '${n}' at path '${c}'`);t[n]=(0,o.schemaFunction)(s,{name:r[n].name,description:r[n].description||"",parameters:r[n].parameters})}}else e(s,r[n],c)}}}(e,t.definition),e}(e,await n.get_service_type(e.type))}catch(t){throw new Error(`Failed to get service type ${e.type}, error: ${t}`)}const c=this.add_service(e,s),a=this._extract_service_info(c);if(i)try{n=n||await this.get_manager_service({timeout:10,case_conversion:"camel"}),await n.registerService(a)}catch(e){throw new Error(`Failed to notify workspace manager: ${e}`)}return a}async unregister_service(e,t){let n;if(t=void 0===t||t,n="string"==typeof e?e:e.id,(0,r.assert)(n&&"string"==typeof n,`Invalid service id: ${n}`),n.includes(":")&&(n=n.split(":")[1]),n.includes("@")&&(n=n.split("@")[0]),!this._services[n])throw new Error(`Service not found: ${n}`);if(n.startsWith("_rintf_")&&(t=!1),t){const e=await this.get_manager_service({timeout:10,case_conversion:"camel"});await e.unregisterService(n)}delete this._services[n]}_ndarray(e,t,n){const o=(0,r.typedArrayToDtype)(e);if(n&&n!==o)throw"dtype doesn't match the type of the array: "+o+" != "+n;return t=t||[e.length],{_rtype:"ndarray",_rvalue:e.buffer,_rshape:t,_rdtype:o}}_encode_callback(e,t,n,r,o,i,s){let c=`${n}.${e}`,a={_rtype:"method",_rtarget:i?`${i}/${this._client_id}`:this._client_id,_rmethod:c,_rpromise:!1};const l=this;let d=function(){try{t.apply(null,Array.prototype.slice.call(arguments))}catch(e){console.error(`Error in callback(${c}, ${s}): ${e}`)}finally{o&&o.started&&o.clear(),r&&l._object_store[n]&&("resolve"===e||"reject"===e?(l._removeFromTargetIdIndex(n),delete l._object_store[n]):l._cleanup_session_if_needed(n,e))}};return d.__name__=`callback(${c})`,[a,d]}_cleanup_session_if_needed(e,t){if(e)try{const n=this._get_session_store(e,!1);if(!n)return void console.debug(`Session ${e} not found for cleanup`);let r=!1;if(n._promise_manager)try{const o=n._promise_manager;o.should_cleanup_on_callback&&o.should_cleanup_on_callback(t)&&(o.settle&&o.settle(),r=!0,console.debug(`Promise session ${e} settled and marked for cleanup`))}catch(t){console.warn(`Error in promise manager cleanup for session ${e}:`,t)}else("resolve"===t||"reject"===t)&&n._callbacks&&Object.keys(n._callbacks).includes(t)&&(r=!0,console.debug(`Regular session ${e} marked for cleanup after ${t}`));r&&this._cleanup_session_completely(e)}catch(t){console.warn(`Error during session cleanup for ${e}:`,t)}else console.debug("Cannot cleanup session: session_id is empty")}_cleanup_session_completely(e){try{this._removeFromTargetIdIndex(e);const t=this._get_session_store(e,!1);if(!t)return void console.debug(`Session ${e} already cleaned up`);if(t.timer&&t.timer.started&&"function"==typeof t.timer.clear)try{t.timer.clear()}catch(t){console.warn(`Error clearing timer for session ${e}:`,t)}if(t.heartbeat_task&&"function"==typeof t.heartbeat_task.cancel)try{t.heartbeat_task.cancel()}catch(t){console.warn(`Error canceling heartbeat for session ${e}:`,t)}const n=e.split(".");let r=this._object_store;for(let t=0;t<n.length-1;t++){const o=n[t];if(!r[o])return void console.debug(`Session path ${e} not found at level ${o}`);r=r[o]}const o=n[n.length-1];r[o]&&(delete r[o],console.debug(`Cleaned up session ${e}`),this._cleanup_empty_containers(n.slice(0,-1)))}catch(t){console.warn(`Error in complete session cleanup for ${e}:`,t)}}_cleanup_empty_containers(e){try{for(let t=e.length-1;t>=0;t--){let n=this._object_store;for(let r=0;r<t;r++)if(n=n[e[r]],!n)return;const r=e[t],o=n[r];if(!o||"object"!=typeof o||0!==Object.keys(o).length)break;delete n[r],console.debug(`Cleaned up empty container at depth ${t}: ${e.slice(0,t+1).join(".")}`)}}catch(e){console.warn("Error cleaning up empty containers:",e)}}get_session_stats(){const e={total_sessions:0,promise_sessions:0,regular_sessions:0,sessions_with_timers:0,sessions_with_heartbeat:0,system_stores:{},session_ids:[],memory_usage:0};if(!this._object_store)return e;for(const t in this._object_store){const n=this._object_store[t];if(["services","message_cache"].includes(t))e.system_stores[t]={size:"object"==typeof n&&n?Object.keys(n).length:0};else if(n&&"object"==typeof n){Object.keys(n).length>0&&(e.total_sessions++,e.session_ids.push(t),n._promise_manager?e.promise_sessions++:e.regular_sessions++,(n._timer||n.timer)&&e.sessions_with_timers++,(n._heartbeat||n.heartbeat)&&e.sessions_with_heartbeat++,e.memory_usage+=JSON.stringify(n).length)}}return e}_force_cleanup_all_sessions(){if(!this._object_store)return void console.debug("Force cleaning up 0 sessions");let e=0;const t=[];for(const n in this._object_store)if(!["services","message_cache"].includes(n)){const r=this._object_store[n];r&&"object"==typeof r&&Object.keys(r).length>0&&(t.push(n),e++)}for(const e of t)delete this._object_store[e];this._targetIdIndex={},console.debug(`Force cleaning up ${e} sessions`)}_sweepStaleSessions(){const e=Date.now();let t=0;for(const n of Object.keys(this._object_store)){if("services"===n||"message_cache"===n)continue;const r=this._object_store[n],o=r&&(r._last_activity_at||r._created_at);if(r&&"object"==typeof r&&o&&e-o>this._sessionMaxAge&&(!r.timer||!r.timer.started)){if("function"==typeof r.resolve||"function"==typeof r.reject)continue;this._removeFromTargetIdIndex(n),r.heartbeat_task&&clearInterval(r.heartbeat_task),delete this._object_store[n],t++}}t>0&&console.debug(`Swept ${t} stale session(s)`)}_is_promise_method_call(e){const t=e.split(".")[0],n=this._get_session_store(t,!1);return n&&n._promise_manager}_create_promise_manager(){return{should_cleanup_on_callback:e=>["resolve","reject"].includes(e),settle:()=>{console.debug("Promise settled")}}}async _encode_promise(e,t,n,r,o,i,s){let c=this._get_session_store(n,!0);c||(console.warn(`Failed to create session store ${n}, session management may be impaired`),c={}),c._promise_manager=this._create_promise_manager();let a={};return o&&t&&this._method_timeout?([a.heartbeat,c.heartbeat]=this._encode_callback("heartbeat",o.reset.bind(o),n,!1,null,i),c.timer=o,a.interval=this._method_timeout/2):o=null,[a.resolve,c.resolve]=this._encode_callback("resolve",e,n,r,o,i,`resolve (${s})`),[a.reject,c.reject]=this._encode_callback("reject",t,n,r,o,i,`reject (${s})`),a}async _send_chunks(e,t,n){const o=await this.get_remote_service(`${t}:built-in`);if(!o.message_cache)throw new Error("Remote client does not support message caching for large messages.");const i=o.message_cache,s=n||(0,r.randId)(),c=e.length,a=Date.now(),l=Math.ceil(c/this._long_message_chunk_size);if(o.config.api_version>=3){await i.create(s,!!n);const t=new r.Semaphore(30),o=[];for(let r=0;r<l;r++){const c=r*this._long_message_chunk_size,a=e.slice(c,c+this._long_message_chunk_size),l=async()=>{await i.set(s,r,a,!!n)};o.push(t.run(l))}try{await Promise.all(o)}catch(e){try{await i.remove(s)}catch(e){console.error(`Failed to clean up message cache after error: ${e}`)}throw e}}else{await i.create(s,!!n);for(let t=0;t<l;t++){const r=t*this._long_message_chunk_size,o=e.slice(r,r+this._long_message_chunk_size);await i.append(s,o,!!n)}}await i.process(s,!!n),((Date.now()-a)/1e3).toFixed(2)}emit(e,t){if((0,r.assert)("object"==typeof e&&e.type,"Invalid message, must be an object with a `type` fields."),!e.to)return void this._fire(e.type,e);let n=(0,s.encode)(e);if(t){const e=(0,s.encode)(t),r=new Uint8Array(n.length+e.length);r.set(n),r.set(e,n.length),n=r}const o=n.length;return o>this._long_message_chunk_size+1024&&console.warn(`Sending large message (size=${o})`),this._emit_message(n)}_generate_remote_method(e,t,n,o,i){let c=e._rtarget;o&&!c.includes("/")&&(c.startsWith("*/")||(o!==c&&(c=o+"/"+c),e._rtarget=c));let a=e._rmethod,l=e._rpromise||!1;const d=`method: ${a}, docs: ${e._rdoc}`,h=this;function u(){return new Promise(async(e,o)=>{try{let _=(0,r.randId)();n&&(_=n+"."+_);let p=h._get_session_store(_,!0);if(!p)return void o(new Error(`Runtime Error: Failed to get session store ${_} (context: ${d})`));p.target_id=c;const f=_.split(".")[0];c in h._targetIdIndex||(h._targetIdIndex[c]=new Set),h._targetIdIndex[c].add(f);const g=await h._encode(Array.prototype.slice.call(arguments),_,i),y=g.length,w=y>0&&"object"==typeof g[y-1]&&null!==g[y-1]&&g[y-1]._rkwargs;let b;w&&delete g[y-1]._rkwargs,b=h._local_workspace?h._local_workspace+"/"+h._client_id:h._client_id;let v={type:"method",from:b,to:c,method:a},E={};g&&(E.args=g),w&&(E.with_kwargs=w),t&&(v.parent=t);let k=null;if(l){v.session=_;let t=`${c}:${a}`;const n=function(e){o(new Error(e)),h._object_store[_]&&(h._removeFromTargetIdIndex(_),delete h._object_store[_],console.debug(`Cleaned up session ${_} after timeout`))};k=new m(h._method_timeout,n,[`Method call timed out: ${t}, context: ${d}`],t);let r=!0;const s=await h._encode_promise(e,o,_,r,k,i,d);if(!0===l)E.promise=s;else{if("*"!==l)throw new Error(`Unsupported promise type: ${l}`);E.promise="*",E.t=h._method_timeout/2}}let x=(0,s.encode)(v);if(E){const e=(0,s.encode)(E),t=new Uint8Array(x.length+e.length);t.set(x),t.set(e,x.length),x=t}x.length<=h._long_message_chunk_size+1024||u.__no_chunk__?h._emit_message(x).then(function(){k&&k.start(),l||e(null)}).catch(function(e){const t=`Failed to send the request when calling method (${c}:${a}), error: ${e}`;o?o(new Error(t)):console.warn("Unhandled RPC method call error:",t),k&&k.started&&k.clear()}):h._send_chunks(x,c,t).then(function(){k&&k.start(),l||e(null)}).catch(function(e){const t=`Failed to send the request when calling method (${c}:${a}), error: ${e}`;o?o(new Error(t)):console.warn("Unhandled RPC method call error:",t),k&&k.started&&k.clear()})}catch(e){o(e)}})}u.__rpc_object__=e;const _=a.split(".");return u.__name__=e._rname||_[_.length-1],u.__name__.includes("#")&&(u.__name__=u.__name__.split("#")[1]),u.__doc__=e._rdoc||`Remote method: ${a}`,u.__schema__=e._rschema,u.__no_chunk__="services.built-in.message_cache.append"===e._rmethod,u}get_client_info(){const e=[];for(let t of Object.values(this._services))e.push(this._extract_service_info(t));return{id:this._client_id,services:e}}async _handle_method(e){let t=null,n=null,o=null;try{(0,r.assert)(e.method&&e.ctx&&e.from);const i=e.from+":"+e.method,s=e.from.split("/")[0],c=e.from.split("/")[1];let a;e.to=e.to.includes("/")?e.to:s+"/"+e.to,e.ctx.to=e.to,this._local_workspace?(this._local_workspace&&"*"!==this._local_workspace&&(0,r.assert)(e.to.split("/")[0]===this._local_workspace,"Workspace mismatch: "+e.to.split("/")[0]+" != "+this._local_workspace),a=this._local_workspace):a=e.to.split("/")[0];const l=e.parent;if(e.promise){const u=await this._decode("*"===e.promise?this._expand_promise(e):e.promise,e.session,l,s,a);if(t=u.resolve,n=u.reject,u.heartbeat&&u.interval){async function _(){try{await u.heartbeat()}catch(e){console.error(e)}}if(o=setInterval(_,1e3*u.interval),e.session){const f=this._get_session_store(e.session,!1);f&&(f.heartbeat_task=o)}}}let d,h;try{d=p(this._object_store,e.method);const m=e.method.split(".");if(m.length>1){const g=m[0];if("services"!==g&&"message_cache"!==g){const y=this._object_store[g];y&&"object"==typeof y&&(y._last_activity_at=Date.now())}}}catch(w){if(this._is_promise_method_call(e.method))return void console.debug(`Promise method ${e.method} not available (detected by session type), ignoring: ${i}`);const b=e.method.split(".");if(b.length>1){const E=b[0];return E in this._object_store?(console.debug(`Session ${E} exists but method ${e.method} not found, likely expired callback: ${i}`),void("function"==typeof n&&n(new Error(`Method expired or not found: ${i}`)))):(console.debug(`Session ${E} not found for method ${e.method}, likely cleaned up: ${i}`),void("function"==typeof n&&n(new Error(`Session not found: ${i}`))))}console.debug(`Failed to find method ${i} at ${this._client_id}`);const v=new Error(`Method not found: ${i} at ${this._client_id}`);return void("function"==typeof n?n(v):console.warn("Method not found and no reject callback:",v.message))}if((0,r.assert)(d&&"function"==typeof d,"Invalid method: "+i),this._method_annotations.has(d)){if("protected"===this._method_annotations.get(d).visibility)if(a===s);else if(this._method_annotations.get(d).authorized_workspaces&&this._method_annotations.get(d).authorized_workspaces.includes(s));else if("*"!==s||c!==this._connection.manager_id)throw new Error("Permission denied for invoking protected method "+i+", workspace mismatch: "+a+" != "+s)}else{let k=this._object_store[e.method.split(".")[0]].target_id;if(a===s&&k&&-1===k.indexOf("/")&&(k=a+"/"+k),k!==e.from)throw new Error("Access denied for method call ("+i+") from "+e.from+" to target "+k)}if(l&&!e.method.startsWith("services.")&&(0,r.assert)(null!==this._get_session_store(l,!0),"Parent session was closed: "+l),h=e.args?await this._decode(e.args,e.session,null,s,null):[],this._method_annotations.has(d)&&this._method_annotations.get(d).require_context){if(h.length+1<d.length)for(let x=h.length;x<d.length-1;x++)h.push(void 0);h.push(e.ctx)}if(e.promise){const S=d.apply(null,h);S instanceof Promise?S.then(e=>{t(e)}).catch(e=>{n(e)}).finally(()=>{clearInterval(o)}):(t(S),clearInterval(o))}else d.apply(null,h),clearInterval(o)}catch(T){n?n(T):console.error("Error during calling method: ",T),clearInterval(o)}}encode(e,t){return this._encode(e,t)}_get_session_store(e,t){if(!e)return null;let n=this._object_store;const r=e.split(".");if(t){const e=r.length-1;for(let t of r.slice(0,e))n[t]||(n[t]={}),n=n[t];if(!n[r[e]]){n[r[e]]={};const t=Date.now();n[r[e]]._created_at=t,n[r[e]]._last_activity_at=t}return n[r[e]]}for(let e of r){if(!n[e])return null;n=n[e]}return n}async _encode(e,t,n){const o=typeof e;if("number"===o||"string"===o||"boolean"===o||null==e||e instanceof Uint8Array)return e;if(e instanceof ArrayBuffer)return{_rtype:"memoryview",_rvalue:new Uint8Array(e)};if(e.__rpc_object__){if((e.__rpc_object__._rserver||this._server_base_url)===this._server_base_url)return e.__rpc_object__}let i;if(e.constructor instanceof Object&&e._rtype){const c=e._rtype;return delete e._rtype,i=await this._encode(e,t,n),i._rtype=c,i}if((0,r.isGenerator)(e)||(0,r.isAsyncGenerator)(e)||(0,r.isAsyncIterator)(e)||(0,r.isSyncIterator)(e)){(0,r.assert)(t&&"string"==typeof t,"Session ID is required for generator encoding");const l=(0,r.randId)(),u=l+":close",_=this._get_session_store(t,!0);(0,r.assert)(null!==_,`Failed to create session store ${t} due to invalid parent`);const p=(0,r.isAsyncGenerator)(e)||(0,r.isAsyncIterator)(e),f=async()=>{if(p){const t=await e.next();return t.done?(delete _[l],delete _[u],{_rtype:"stop_iteration"}):t.value}{const t=e.next();return t.done?(delete _[l],delete _[u],{_rtype:"stop_iteration"}):t.value}},m=async()=>{try{"function"==typeof e.return&&(p?await e.return():e.return())}catch(e){}finally{delete _[l],delete _[u]}return!0};return _[l]=f,_[u]=m,i={_rtype:"generator",_rserver:this._server_base_url,_rtarget:this._client_id,_rmethod:`${t}.${l}`,_rclose_method:`${t}.${u}`,_rpromise:"*",_rdoc:"Remote generator"},i}if("function"==typeof e){if(this._method_annotations.has(e)){let y=this._method_annotations.get(e);i={_rtype:"method",_rserver:this._server_base_url,_rtarget:this._client_id,_rmethod:y.method_id,_rpromise:"*",_rname:e.name}}else{let w;(0,r.assert)("string"==typeof t),w=e.__name__?`${(0,r.randId)()}#${e.__name__}`:(0,r.randId)(),i={_rtype:"method",_rserver:this._server_base_url,_rtarget:this._client_id,_rmethod:`${t}.${w}`,_rpromise:"*",_rname:e.name};let b=this._get_session_store(t,!0);(0,r.assert)(null!==b,`Failed to create session store ${t} due to invalid parent`),b[w]=e}if(i._rdoc=e.__doc__,!i._rdoc)try{const v=function(e){const t=e.toString(),n=t.match(/function\s*(\w*)/),r=n&&n[1]||"",o=t.match(/\(([^)]*)\)/);let i="";o&&(i=o[1].split(",").map(e=>e.replace(/\/\*.*?\*\//g,"").replace(/\/\/.*$/g,"")).filter(e=>e.trim().length>0).map(e=>e.trim()).join(", "));let s=t.match(/\)\s*\{\s*\/\*([\s\S]*?)\*\//);const c=s&&s[1].trim()||"";s=t.match(/\)\s*\{\s*(\/\/[\s\S]*?)\n\s*[^\s\/]/);const a=s&&s[1].split("\n").map(e=>e.replace(/^\/\/\s*/,"").trim()).join("\n")||"",l=c||a;return r&&i.length>0&&{name:r,sig:i,doc:l}}(e);v&&!i._rdoc&&(i._rdoc=`${v.doc}`)}catch(E){console.error("Failed to extract function docstring:",e)}return i._rschema=e.__schema__,i}const s=Array.isArray(e);for(let k of Object.keys(this._codecs)){const x=this._codecs[k];if(x.encoder&&e instanceof x.type){let S=await Promise.resolve(x.encoder(e));if(S&&!S._rtype&&(S._rtype=x.name),"object"==typeof S){const T=S._rtype;delete S._rtype,S=await this._encode(S,t,n),S._rtype=T}return i=S,i}}if("undefined"!=typeof tf&&tf.Tensor&&e instanceof tf.Tensor){const C=e.dataSync();i={_rtype:"ndarray",_rvalue:new Uint8Array(C.buffer),_rshape:e.shape,_rdtype:e.dtype}}else if("undefined"!=typeof nj&&nj.NdArray&&e instanceof nj.NdArray){if(!e.selection||!e.selection.data)throw new Error("Invalid NumJS array: missing selection or data");const R=(0,r.typedArrayToDtype)(e.selection.data);i={_rtype:"ndarray",_rvalue:new Uint8Array(e.selection.data.buffer),_rshape:e.shape,_rdtype:R}}else if(e instanceof Error)console.error(e),i={_rtype:"error",_rvalue:e.toString(),_rtrace:e.stack};else if(e!==Object(e)||e instanceof Boolean||e instanceof String||e instanceof Date||e instanceof RegExp||"undefined"!=typeof ImageData&&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)i=e;else if(e instanceof Blob){let I=0;async function A(t){let n;n=t?e.slice(I,I+t):e.slice(I);const r=new Uint8Array(await n.arrayBuffer());return I+=r.byteLength,r}function $(e){I=e}i={_rtype:"iostream",_rnative:"js:blob",type:e.type,name:e.name,size:e.size,path:e._path||e.webkitRelativePath,read:await this._encode(A,t,n),seek:await this._encode($,t,n)}}else if(e instanceof a){const j=(0,r.typedArrayToDtype)(e);i={_rtype:"typedarray",_rvalue:new Uint8Array(e.buffer),_rdtype:j}}else if(e instanceof DataView)i={_rtype:"memoryview",_rvalue:new Uint8Array(e.buffer)};else if(e instanceof Set)i={_rtype:"set",_rvalue:await this._encode(Array.from(e),t,n)};else if(e instanceof Map)i={_rtype:"orderedmap",_rvalue:await this._encode(Array.from(e),t,n)};else{if(!(e.constructor===Object||Array.isArray(e)||e instanceof g))throw`hypha-rpc: Unsupported data type: ${e}, you can register a custom codec to encode/decode the object.`;{if(!s&&!0===e._rintf&&Object.keys(e).some(t=>!t.startsWith("_")&&"function"==typeof e[t])){const D=`_rintf_${(0,r.randId)()}`,O={id:D};for(const L of Object.keys(e))L.startsWith("_")||"function"!=typeof e[L]||(O[L]=e[L]);this.add_service(O,!0),e._rintf_service_id=D,i={};for(const M of Object.keys(e))i[M]=await this._encode(e[M],t,n);return i._rintf_service_id=D,i}if(s){if(d(e))return e}else if(!("_rtype"in e||e instanceof g)&&h(e))return e;i=s?[]:{};const P=Object.keys(e);for(let U of P)i[U]=await this._encode(e[U],t,n)}}if(!i)throw new Error("Failed to encode object");return i}async decode(e){return await this._decode(e)}async _decode(e,t,n,o,i){if(!e)return e;let s;if(e._rtype)if(this._codecs[e._rtype]&&this._codecs[e._rtype].decoder){const c=e._rtype;delete e._rtype,(e=await this._decode(e,t,n,o,i))._rtype=c,s=await Promise.resolve(this._codecs[e._rtype].decoder(e))}else if("method"===e._rtype)s=this._generate_remote_method(e,t,n,o,i);else if("generator"===e._rtype){const a=this._generate_remote_method(e,t,n,o,i);let l=null;if(e._rclose_method){const p={_rtype:"method",_rserver:e._rserver,_rtarget:e._rtarget,_rmethod:e._rclose_method,_rpromise:"*"};l=this._generate_remote_method(p,t,n,o,i)}async function*_(){let e=!1;try{for(;;){const t=await a();if(t&&"stop_iteration"===t._rtype){e=!0;break}yield t}}catch(e){throw console.error("Error in generator:",e),e}finally{if(!e&&l)try{await l()}catch(e){}}}s=_()}else if("ndarray"===e._rtype)if("undefined"!=typeof nj&&nj.array)Array.isArray(e._rvalue)&&(e._rvalue=e._rvalue.reduce(u)),s=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(u));const f=r.dtypeToTypedArray[e._rdtype];s=tf.tensor(new f(e._rvalue),e._rshape,e._rdtype)}else s=e;else if("error"===e._rtype)s=new Error("RemoteError: "+e._rvalue+"\n"+(e._rtrace||""));else if("typedarray"===e._rtype){const m=r.dtypeToTypedArray[e._rdtype];if(!m)throw new Error("unsupported dtype: "+e._rdtype);s=new m(e._rvalue.buffer.slice(e._rvalue.byteOffset,e._rvalue.byteOffset+e._rvalue.byteLength))}else if("memoryview"===e._rtype)s=e._rvalue.buffer.slice(e._rvalue.byteOffset,e._rvalue.byteOffset+e._rvalue.byteLength);else if("iostream"===e._rtype){if("js:blob"===e._rnative){const g=await this._generate_remote_method(e.read,t,n,o,i),y=await g();s=new Blob([y],{type:e.type,name:e.name})}else{s={};for(let w of Object.keys(e))w.startsWith("_")||(s[w]=await this._decode(e[w],t,n,o,i))}s.__rpc_object__=e}else if("orderedmap"===e._rtype)s=new Map(await this._decode(e._rvalue,t,n,o,i));else if("set"===e._rtype)s=new Set(await this._decode(e._rvalue,t,n,o,i));else{const b=e._rtype;delete e._rtype,s=await this._decode(e,t,n,o,i),s._rtype=b}else if(e.constructor===Object||Array.isArray(e)){const v=Array.isArray(e);if(v){if(d(e))return e}else if(h(e))return e;s=v?[]:{};for(let E of Object.keys(e))if(v||e.hasOwnProperty(E)){const k=e[E];s[E]=await this._decode(k,t,n,o,i)}}else s=e;if(void 0===s)throw new Error("Failed to decode object");return s}_expand_promise(e){return{heartbeat:{_rtype:"method",_rtarget:e.from.split("/")[1],_rmethod:e.session+".heartbeat",_rdoc:`heartbeat callback for method: ${e.method}`},resolve:{_rtype:"method",_rtarget:e.from.split("/")[1],_rmethod:e.session+".resolve",_rdoc:`resolve callback for method: ${e.method}`},reject:{_rtype:"method",_rtarget:e.from.split("/")[1],_rmethod:e.session+".reject",_rdoc:`reject callback for method: ${e.method}`},interval:e.t}}}},"./src/utils/index.js":
8
8
  /*!****************************!*\
9
9
  !*** ./src/utils/index.js ***!
10
- \****************************/(__unused_webpack_module,__webpack_exports__,__webpack_require__)=>{function randId(){return Math.random().toString(36).substr(2,10)+(new Date).getTime()}function toCamelCase(e){return e.includes("_")?e.replace(/_./g,e=>e[1].toUpperCase()):e}function toSnakeCase(e){return e.replace(/([A-Z])/g,"_$1").toLowerCase()}function expandKwargs(e){if("object"!=typeof e||null===e)return e;const t=Array.isArray(e)?[]:{};for(const n in e)if(e.hasOwnProperty(n)){const r=e[n];"function"==typeof r?(t[n]=(...e)=>{if(0===e.length)throw new Error(`Function "${n}" expects at least one argument.`);const t=e[e.length-1];let o={};return"object"!=typeof t||null===t||Array.isArray(t)||(o={...t,_rkwarg:!0},e=e.slice(0,-1)),r(...e,o)},t[n].__name__=n,r.__schema__&&(t[n].__schema__={...r.__schema__},t[n].__schema__.name=n)):t[n]=expandKwargs(r)}return t}function convertCase(e,t){if("object"!=typeof e||null===e||!t)return e;const n=Array.isArray(e)?[]:{};for(const r in e)if(e.hasOwnProperty(r)){const o=e[r],s=toCamelCase(r),i=toSnakeCase(r);"camel"===t?(n[s]=convertCase(o,t),"function"==typeof o&&(n[s].__name__=s,o.__schema__&&(n[s].__schema__={...o.__schema__},n[s].__schema__.name=s))):"snake"===t?(n[i]=convertCase(o,t),"function"==typeof o&&(n[i].__name__=i,o.__schema__&&(n[i].__schema__={...o.__schema__},n[i].__schema__.name=i))):(t.includes("camel")&&(n[s]=convertCase(o,"camel")),t.includes("snake")&&(n[i]=convertCase(o,"snake")))}return n}function parseServiceUrl(e){e=e.replace(/\/$/,"");const t=new RegExp("^(https?:\\/\\/[^/]+)\\/([a-z0-9_-]+)\\/services\\/(?:(?<clientId>[a-zA-Z0-9_-]+):)?(?<serviceId>[a-zA-Z0-9_-]+)(?:@(?<appId>[a-zA-Z0-9_-]+))?"),n=e.match(t);if(!n)throw new Error("URL does not match the expected pattern");const r=n[1],o=n[2],s=n.groups?.clientId||"*",i=n.groups?.serviceId;return{serverUrl:r,workspace:o,clientId:s,serviceId:i,appId:n.groups?.appId||"*"}}__webpack_require__.r(__webpack_exports__),__webpack_require__.d(__webpack_exports__,{MessageEmitter:()=>MessageEmitter,Semaphore:()=>Semaphore,assert:()=>assert,cacheRequirements:()=>cacheRequirements,convertCase:()=>convertCase,dtypeToTypedArray:()=>dtypeToTypedArray,expandKwargs:()=>expandKwargs,isAsyncGenerator:()=>isAsyncGenerator,isAsyncIterator:()=>isAsyncIterator,isGenerator:()=>isGenerator,isSyncIterator:()=>isSyncIterator,loadRequirements:()=>loadRequirements,loadRequirementsInWebworker:()=>loadRequirementsInWebworker,loadRequirementsInWindow:()=>loadRequirementsInWindow,normalizeConfig:()=>normalizeConfig,parseServiceUrl:()=>parseServiceUrl,randId:()=>randId,toCamelCase:()=>toCamelCase,toSnakeCase:()=>toSnakeCase,typedArrayToDtype:()=>typedArrayToDtype,typedArrayToDtypeMapping:()=>typedArrayToDtypeMapping,urlJoin:()=>urlJoin,waitFor:()=>waitFor});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,n)=>{var r=document.createElement("script");r.src=e,r.type="text/javascript",r.onload=t,r.onreadystatechange=function(){"loaded"!==this.readyState&&"complete"!==this.readyState||t()},r.onerror=n,document.head.appendChild(r)})}async function n(){for(var e=Array.prototype.slice.call(arguments),n=e.length,r=0;r<n;r++)await t(e[r])}if(e&&(Array.isArray(e)||"string"==typeof e))try{var r;if(e="string"==typeof e?[e]:e,!Array.isArray(e))throw"unsupported requirements definition";for(var o=0;o<e.length;o++)e[o].toLowerCase().endsWith(".css")||e[o].startsWith("css:")?(e[o].startsWith("css:")&&(e[o]=e[o].slice(4)),(r=document.createElement("link")).rel="stylesheet",r.href=e[o],document.head.appendChild(r)):e[o].toLowerCase().endsWith(".mjs")||e[o].startsWith("mjs:")?(e[o].startsWith("mjs:")&&(e[o]=e[o].slice(4)),await new Function("url","return import(url)")(e[o])):e[o].toLowerCase().endsWith(".js")||e[o].startsWith("js:")?(e[o].startsWith("js:")&&(e[o]=e[o].slice(3)),await n(e[o])):e[o].startsWith("http")?await n(e[o]):e[o].startsWith("cache:")||console.log("Unprocessed requirements url: "+e[o])}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,n)=>("function"!=typeof e[n]&&(t[n]=e[n]),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 n=Object.getPrototypeOf(e);for(const e of typedArrayToDtypeKeys)if(n instanceof e){t=typedArrayToDtypeMapping[e.name];break}}return t}function cacheUrlInServiceWorker(e){return new Promise(function(t,n){const r={command:"add",url:e};if(!navigator.serviceWorker||!navigator.serviceWorker.register)return void n("Service worker is not supported.");const o=new MessageChannel;o.port1.onmessage=function(e){e.data&&e.data.error?n(e.data.error):t(e.data&&e.data.result)},navigator.serviceWorker&&navigator.serviceWorker.controller?navigator.serviceWorker.controller.postMessage(r,[o.port2]):n("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 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,n){let r;return Promise.race([e,new Promise((e,o)=>r=setTimeout(()=>{o(n||"Timeout Error")},1e3*t))]).finally(()=>clearTimeout(r))}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 n=this._event_handlers[e].indexOf(t);n>=0&&this._event_handlers[e].splice(n,1)}}else this._event_handlers={}}_fire(e,t){if(this._event_handlers[e])for(var n=this._event_handlers[e].length;n--;){const r=this._event_handlers[e][n];try{r(t)}catch(e){console.error(e)}finally{r.___event_run_once&&this._event_handlers[e].splice(n,1)}}else this._debug&&console.warn("unhandled event",e,t)}waitFor(e,t){return new Promise((n,r)=>{const o=e=>{clearTimeout(s),n(e)};this.once(e,o);const s=setTimeout(()=>{this.off(e,o),r(new Error("Timeout"))},1e3*t)})}}class Semaphore{constructor(e){this.max=e,this.queue=[],this.current=0}async run(e){this.current>=this.max&&await new Promise(e=>this.queue.push(e)),this.current++;try{return await e()}finally{this.current--,this.queue.length>0&&this.queue.shift()()}}}function isGenerator(e){return!!e&&("object"==typeof e&&"function"==typeof e.next&&"function"==typeof e.throw&&"function"==typeof e.return)}function isAsyncGenerator(e){return!!e&&("object"==typeof e&&"function"==typeof e.next&&"function"==typeof e.throw&&"function"==typeof e.return&&Symbol.asyncIterator in Object(e)&&"AsyncGenerator"===e[Symbol.toStringTag])}function isAsyncIterator(e){return!(!e||isAsyncGenerator(e))&&("object"==typeof e&&Symbol.asyncIterator in Object(e)&&"function"==typeof e.next)}function isSyncIterator(e){return!(!e||isGenerator(e))&&("object"==typeof e&&Symbol.iterator in Object(e)&&"function"==typeof e.next&&!Array.isArray(e)&&"string"!=typeof e)}},"./src/utils/schema.js":
10
+ \****************************/(__unused_webpack_module,__webpack_exports__,__webpack_require__)=>{function randId(){return Math.random().toString(36).substr(2,10)+(new Date).getTime()}function toCamelCase(e){return e.includes("_")?e.replace(/_./g,e=>e[1].toUpperCase()):e}function toSnakeCase(e){return e.replace(/([A-Z])/g,"_$1").toLowerCase()}function expandKwargs(e){if("object"!=typeof e||null===e)return e;const t=Array.isArray(e)?[]:{};for(const n in e)if(e.hasOwnProperty(n)){const r=e[n];"function"==typeof r?(t[n]=(...e)=>{if(0===e.length)throw new Error(`Function "${n}" expects at least one argument.`);const t=e[e.length-1];let o={};return"object"!=typeof t||null===t||Array.isArray(t)||(o={...t,_rkwarg:!0},e=e.slice(0,-1)),r(...e,o)},t[n].__name__=n,r.__schema__&&(t[n].__schema__={...r.__schema__},t[n].__schema__.name=n)):t[n]=expandKwargs(r)}return t}function convertCase(e,t){if("object"!=typeof e||null===e||!t)return e;const n=Array.isArray(e)?[]:{};for(const r in e)if(e.hasOwnProperty(r)){const o=e[r],i=toCamelCase(r),s=toSnakeCase(r);"camel"===t?(n[i]=convertCase(o,t),"function"==typeof o&&(n[i].__name__=i,o.__schema__&&(n[i].__schema__={...o.__schema__},n[i].__schema__.name=i))):"snake"===t?(n[s]=convertCase(o,t),"function"==typeof o&&(n[s].__name__=s,o.__schema__&&(n[s].__schema__={...o.__schema__},n[s].__schema__.name=s))):(t.includes("camel")&&(n[i]=convertCase(o,"camel")),t.includes("snake")&&(n[s]=convertCase(o,"snake")))}return n}function parseServiceUrl(e){e=e.replace(/\/$/,"");const t=new RegExp("^(https?:\\/\\/[^/]+)\\/([a-z0-9_-]+)\\/services\\/(?:(?<clientId>[a-zA-Z0-9_-]+):)?(?<serviceId>[a-zA-Z0-9_-]+)(?:@(?<appId>[a-zA-Z0-9_-]+))?"),n=e.match(t);if(!n)throw new Error("URL does not match the expected pattern");const r=n[1],o=n[2],i=n.groups?.clientId||"*",s=n.groups?.serviceId;return{serverUrl:r,workspace:o,clientId:i,serviceId:s,appId:n.groups?.appId||"*"}}__webpack_require__.r(__webpack_exports__),__webpack_require__.d(__webpack_exports__,{MessageEmitter:()=>MessageEmitter,Semaphore:()=>Semaphore,assert:()=>assert,cacheRequirements:()=>cacheRequirements,convertCase:()=>convertCase,dtypeToTypedArray:()=>dtypeToTypedArray,expandKwargs:()=>expandKwargs,isAsyncGenerator:()=>isAsyncGenerator,isAsyncIterator:()=>isAsyncIterator,isGenerator:()=>isGenerator,isSyncIterator:()=>isSyncIterator,loadRequirements:()=>loadRequirements,loadRequirementsInWebworker:()=>loadRequirementsInWebworker,loadRequirementsInWindow:()=>loadRequirementsInWindow,normalizeConfig:()=>normalizeConfig,parseServiceUrl:()=>parseServiceUrl,randId:()=>randId,toCamelCase:()=>toCamelCase,toSnakeCase:()=>toSnakeCase,typedArrayToDtype:()=>typedArrayToDtype,typedArrayToDtypeMapping:()=>typedArrayToDtypeMapping,urlJoin:()=>urlJoin,waitFor:()=>waitFor});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,n)=>{var r=document.createElement("script");r.src=e,r.type="text/javascript",r.onload=t,r.onreadystatechange=function(){"loaded"!==this.readyState&&"complete"!==this.readyState||t()},r.onerror=n,document.head.appendChild(r)})}async function n(){for(var e=Array.prototype.slice.call(arguments),n=e.length,r=0;r<n;r++)await t(e[r])}if(e&&(Array.isArray(e)||"string"==typeof e))try{var r;if(e="string"==typeof e?[e]:e,!Array.isArray(e))throw"unsupported requirements definition";for(var o=0;o<e.length;o++)e[o].toLowerCase().endsWith(".css")||e[o].startsWith("css:")?(e[o].startsWith("css:")&&(e[o]=e[o].slice(4)),(r=document.createElement("link")).rel="stylesheet",r.href=e[o],document.head.appendChild(r)):e[o].toLowerCase().endsWith(".mjs")||e[o].startsWith("mjs:")?(e[o].startsWith("mjs:")&&(e[o]=e[o].slice(4)),await new Function("url","return import(url)")(e[o])):e[o].toLowerCase().endsWith(".js")||e[o].startsWith("js:")?(e[o].startsWith("js:")&&(e[o]=e[o].slice(3)),await n(e[o])):e[o].startsWith("http")?await n(e[o]):e[o].startsWith("cache:")||console.log("Unprocessed requirements url: "+e[o])}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,n)=>("function"!=typeof e[n]&&(t[n]=e[n]),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 n=Object.getPrototypeOf(e);for(const e of typedArrayToDtypeKeys)if(n instanceof e){t=typedArrayToDtypeMapping[e.name];break}}return t}function cacheUrlInServiceWorker(e){return new Promise(function(t,n){const r={command:"add",url:e};if(!navigator.serviceWorker||!navigator.serviceWorker.register)return void n("Service worker is not supported.");const o=new MessageChannel;o.port1.onmessage=function(e){e.data&&e.data.error?n(e.data.error):t(e.data&&e.data.result)},navigator.serviceWorker&&navigator.serviceWorker.controller?navigator.serviceWorker.controller.postMessage(r,[o.port2]):n("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 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,n){let r;return Promise.race([e,new Promise((e,o)=>r=setTimeout(()=>{o(n||"Timeout Error")},1e3*t))]).finally(()=>clearTimeout(r))}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 n=this._event_handlers[e].indexOf(t);n>=0&&this._event_handlers[e].splice(n,1)}}else this._event_handlers={}}_fire(e,t){if(this._event_handlers[e])for(var n=this._event_handlers[e].length;n--;){const r=this._event_handlers[e][n];try{r(t)}catch(e){console.error(e)}finally{r.___event_run_once&&this._event_handlers[e].splice(n,1)}}else this._debug&&console.warn("unhandled event",e,t)}waitFor(e,t){return new Promise((n,r)=>{const o=e=>{clearTimeout(i),n(e)};this.once(e,o);const i=setTimeout(()=>{this.off(e,o),r(new Error("Timeout"))},1e3*t)})}}class Semaphore{constructor(e){this.max=e,this.queue=[],this.current=0}async run(e){this.current>=this.max&&await new Promise(e=>this.queue.push(e)),this.current++;try{return await e()}finally{this.current--,this.queue.length>0&&this.queue.shift()()}}}function isGenerator(e){return!!e&&("object"==typeof e&&"function"==typeof e.next&&"function"==typeof e.throw&&"function"==typeof e.return)}function isAsyncGenerator(e){return!!e&&("object"==typeof e&&"function"==typeof e.next&&"function"==typeof e.throw&&"function"==typeof e.return&&Symbol.asyncIterator in Object(e)&&"AsyncGenerator"===e[Symbol.toStringTag])}function isAsyncIterator(e){return!(!e||isAsyncGenerator(e))&&("object"==typeof e&&Symbol.asyncIterator in Object(e)&&"function"==typeof e.next)}function isSyncIterator(e){return!(!e||isGenerator(e))&&("object"==typeof e&&Symbol.iterator in Object(e)&&"function"==typeof e.next&&!Array.isArray(e)&&"string"!=typeof e)}},"./src/utils/schema.js":
11
11
  /*!*****************************!*\
12
12
  !*** ./src/utils/schema.js ***!
13
- \*****************************/(e,t,n)=>{n.r(t),n.d(t,{schemaFunction:()=>s,z:()=>o});var r=n(/*! ./index.js */"./src/utils/index.js");const o={object:e=>({type:"object",properties:e,required:Object.keys(e).filter(t=>!e[t]._optional)}),string:()=>({type:"string",_optional:!1}),number:()=>({type:"number",_optional:!1}),integer:()=>({type:"integer",_optional:!1}),boolean:()=>({type:"boolean",_optional:!1}),array:e=>({type:"array",items:e,_optional:!1}),optional:e=>({...e,_optional:!0})};function s(e,{schema_type:t="auto",name:n=null,description:o=null,parameters:s=null}){if(!e||"function"!=typeof e)throw Error("func should be a function");(0,r.assert)("auto"===t,"schema_type should be auto");const i=n||e.name;(0,r.assert)(i,"name should not be null");let c=s;if(s&&"object"==typeof s&&"object"===s.type){c={type:"object",properties:s.properties||{},required:s.required||[]};for(const[e,t]of Object.entries(c.properties))void 0!==t._optional&&delete t._optional}return(0,r.assert)(c&&"object"===c.type,"parameters should be an object schema"),e.__schema__={name:i,description:o||"",parameters:c},e}["string","number","integer","boolean","array"].forEach(e=>{o[e]=()=>{const t={type:"integer"===e?"integer":e,_optional:!1,describe:e=>({...t,description:e})};return t}})},"./src/webrtc-client.js":
13
+ \*****************************/(e,t,n)=>{n.r(t),n.d(t,{schemaFunction:()=>i,z:()=>o});var r=n(/*! ./index.js */"./src/utils/index.js");const o={object:e=>({type:"object",properties:e,required:Object.keys(e).filter(t=>!e[t]._optional)}),string:()=>({type:"string",_optional:!1}),number:()=>({type:"number",_optional:!1}),integer:()=>({type:"integer",_optional:!1}),boolean:()=>({type:"boolean",_optional:!1}),array:e=>({type:"array",items:e,_optional:!1}),optional:e=>({...e,_optional:!0})};function i(e,{schema_type:t="auto",name:n=null,description:o=null,parameters:i=null}){if(!e||"function"!=typeof e)throw Error("func should be a function");(0,r.assert)("auto"===t,"schema_type should be auto");const s=n||e.name;(0,r.assert)(s,"name should not be null");let c=i;if(i&&"object"==typeof i&&"object"===i.type){c={type:"object",properties:i.properties||{},required:i.required||[]};for(const[e,t]of Object.entries(c.properties))void 0!==t._optional&&delete t._optional}return(0,r.assert)(c&&"object"===c.type,"parameters should be an object schema"),e.__schema__={name:s,description:o||"",parameters:c},e}["string","number","integer","boolean","array"].forEach(e=>{o[e]=()=>{const t={type:"integer"===e?"integer":e,_optional:!1,describe:e=>({...t,description:e})};return t}})},"./src/webrtc-client.js":
14
14
  /*!******************************!*\
15
15
  !*** ./src/webrtc-client.js ***!
16
- \******************************/(e,t,n)=>{n.r(t),n.d(t,{getRTCService:()=>a,registerRTCService:()=>l});var r=n(/*! ./rpc.js */"./src/rpc.js"),o=n(/*! ./utils/index.js */"./src/utils/index.js"),s=n(/*! ./utils/schema.js */"./src/utils/schema.js");class i{constructor(e){this._data_channel=e,this._handle_message=null,this._reconnection_token=null,this._handle_disconnected=null,this._handle_connected=()=>{},this.manager_id=null,this._data_channel.onopen=async()=>{this._handle_connected&&this._handle_connected({channel:this._data_channel})},this._data_channel.onmessage=async e=>{let t=e.data;t instanceof Blob&&(t=await t.arrayBuffer()),this._handle_message&&this._handle_message(t)},this._data_channel.onclose=()=>{this._handle_disconnected&&this._handle_disconnected("closed"),console.log("data channel closed"),this._data_channel=null}}on_disconnected(e){this._handle_disconnected=e}on_connected(e){this._handle_connected=e}on_message(e){(0,o.assert)(e,"handler is required"),this._handle_message=e}async emit_message(e){(0,o.assert)(this._handle_message,"No handler for message");try{this._data_channel.send(e)}catch(e){throw console.error(`Failed to send data, error: ${e}`),e}}async disconnect(e){this._data_channel=null,console.info(`data channel connection disconnected (${e})`)}}async function c(e){(0,o.assert)(e.channel,"No channel provided"),(0,o.assert)(e.workspace,"No workspace provided");const t=e.channel,n=e.client_id||(0,o.randId)(),s=new i(t);e.context=e.context||{},e.context.connection_type="webrtc",e.context.ws=e.workspace;return new r.RPC(s,{client_id:n,default_context:e.context,name:e.name,method_timeout:e.method_timeout||10,workspace:e.workspace,app_id:e.app_id,long_message_chunk_size:e.long_message_chunk_size})}async function a(e,t,n){(n=n||{}).peer_id=n.peer_id||(0,o.randId)();const r=new RTCPeerConnection({iceServers:n.ice_servers||[{urls:["stun:stun.l.google.com:19302"]}],sdpSemantics:"unified-plan"});return new Promise(async(i,a)=>{let l=!1;const _=setTimeout(()=>{l||(l=!0,r.close(),a(new Error("WebRTC Connection timeout")))},3e4);try{r.addEventListener("connectionstatechange",()=>{console.log("WebRTC Connection state: ",r.connectionState),"failed"===r.connectionState?l||(l=!0,clearTimeout(_),r.close(),a(new Error("WebRTC Connection failed"))):"closed"===r.connectionState?l||(l=!0,clearTimeout(_),a(new Error("WebRTC Connection closed"))):"connected"===r.connectionState&&console.log("WebRTC Connection established successfully")},!1),r.addEventListener("iceconnectionstatechange",()=>{console.log("ICE Connection state: ",r.iceConnectionState),"failed"===r.iceConnectionState&&(l||(l=!0,clearTimeout(_),r.close(),a(new Error("ICE Connection failed"))))}),n.on_init&&(await n.on_init(r),delete n.on_init);let d=r.createDataChannel(n.peer_id,{ordered:!0});d.binaryType="arraybuffer";const h=await r.createOffer();await r.setLocalDescription(h),await new Promise(e=>{"complete"===r.iceGatheringState?e():(r.addEventListener("icegatheringstatechange",()=>{"complete"===r.iceGatheringState&&e()}),setTimeout(e,5e3))});const u=await e.getService(t),p=await u.offer({sdp:r.localDescription.sdp,type:r.localDescription.type});d.onopen=()=>{n.channel=d,n.workspace=p.workspace,setTimeout(async()=>{if(!l)try{const e=await c(n);async function t(t,...r){return(0,o.assert)(!t.includes(":"),"WebRTC service name should not contain ':'"),(0,o.assert)(!t.includes("/"),"WebRTC service name should not contain '/'"),await e.get_remote_service(n.workspace+"/"+n.peer_id+":"+t,...r)}async function d(){await e.disconnect(),r.close()}r.rpc=e,r.getService=(0,s.schemaFunction)(t,{name:"getService",description:"Get a remote service via webrtc",parameters:{type:"object",properties:{service_id:{type:"string",description:"Service ID. This should be a service id in the format: 'workspace/service_id', 'workspace/client_id:service_id' or 'workspace/client_id:service_id@app_id'"},config:{type:"object",description:"Options for the service"}},required:["id"]}}),r.disconnect=(0,s.schemaFunction)(d,{name:"disconnect",description:"Disconnect from the webrtc connection via webrtc",parameters:{type:"object",properties:{}}}),r.registerCodec=(0,s.schemaFunction)(e.register_codec,{name:"registerCodec",description:"Register a codec for the webrtc connection",parameters:{type:"object",properties:{codec:{type:"object",description:"Codec to register",properties:{name:{type:"string"},type:{},encoder:{type:"function"},decoder:{type:"function"}}}}}}),l=!0,clearTimeout(_),i(r)}catch(h){l||(l=!0,clearTimeout(_),a(h))}},1e3)},d.onclose=()=>{l||(l=!0,clearTimeout(_),a(new Error("Data channel closed")))},d.onerror=e=>{l||(l=!0,clearTimeout(_),a(new Error(`Data channel error: ${e}`)))},await r.setRemoteDescription(new RTCSessionDescription({sdp:p.sdp,type:p.type}))}catch(e){l||(l=!0,clearTimeout(_),a(e))}})}async function l(e,t,n){const r=(n=n||{visibility:"protected",require_context:!0}).on_init;return delete n.on_init,await e.registerService({id:t,config:n,offer:(t,o)=>async function(e,t,n,r,o){n=n||{};let s=new RTCSessionDescription({sdp:e.sdp,type:e.type}),i=new RTCPeerConnection({iceServers:n.ice_servers||[{urls:["stun:stun.l.google.com:19302"]}],sdpSemantics:"unified-plan"});t&&i.addEventListener("datachannel",async e=>{const n=e.channel;let r=null;o&&o.user&&(r={user:o.user,ws:o.ws}),(await c({channel:n,client_id:n.label,workspace:t.config.workspace,context:r}))._services=t.rpc._services}),r&&await r(i),await i.setRemoteDescription(s);let a=await i.createAnswer();return await i.setLocalDescription(a),await new Promise(e=>{"complete"===i.iceGatheringState?e():(i.addEventListener("icegatheringstatechange",()=>{"complete"===i.iceGatheringState&&e()}),setTimeout(e,5e3))}),{sdp:i.localDescription.sdp,type:i.localDescription.type,workspace:t.config.workspace}}(t,e,n,r,o)})}},"./node_modules/@msgpack/msgpack/dist.es5+esm/CachedKeyDecoder.mjs":
16
+ \******************************/(e,t,n)=>{n.r(t),n.d(t,{getRTCService:()=>a,registerRTCService:()=>l});var r=n(/*! ./rpc.js */"./src/rpc.js"),o=n(/*! ./utils/index.js */"./src/utils/index.js"),i=n(/*! ./utils/schema.js */"./src/utils/schema.js");class s{constructor(e){this._data_channel=e,this._handle_message=null,this._reconnection_token=null,this._handle_disconnected=null,this._handle_connected=()=>{},this.manager_id=null,this._data_channel.onopen=async()=>{this._handle_connected&&this._handle_connected({channel:this._data_channel})},this._data_channel.onmessage=async e=>{let t=e.data;t instanceof Blob&&(t=await t.arrayBuffer()),this._handle_message&&this._handle_message(t)},this._data_channel.onclose=()=>{this._handle_disconnected&&this._handle_disconnected("closed"),console.log("data channel closed"),this._data_channel=null}}on_disconnected(e){this._handle_disconnected=e}on_connected(e){this._handle_connected=e}on_message(e){(0,o.assert)(e,"handler is required"),this._handle_message=e}async emit_message(e){(0,o.assert)(this._handle_message,"No handler for message");try{this._data_channel.send(e)}catch(e){throw console.error(`Failed to send data, error: ${e}`),e}}async disconnect(e){this._data_channel=null,console.info(`data channel connection disconnected (${e})`)}}async function c(e){(0,o.assert)(e.channel,"No channel provided"),(0,o.assert)(e.workspace,"No workspace provided");const t=e.channel,n=e.client_id||(0,o.randId)(),i=new s(t);e.context=e.context||{},e.context.connection_type="webrtc",e.context.ws=e.workspace;return new r.RPC(i,{client_id:n,default_context:e.context,name:e.name,method_timeout:e.method_timeout||10,workspace:e.workspace,app_id:e.app_id,long_message_chunk_size:e.long_message_chunk_size})}async function a(e,t,n){(n=n||{}).peer_id=n.peer_id||(0,o.randId)();const r=new RTCPeerConnection({iceServers:n.ice_servers||[{urls:["stun:stun.l.google.com:19302"]}],sdpSemantics:"unified-plan"});return new Promise(async(s,a)=>{let l=!1;const d=setTimeout(()=>{l||(l=!0,r.close(),a(new Error("WebRTC Connection timeout")))},3e4);try{r.addEventListener("connectionstatechange",()=>{console.log("WebRTC Connection state: ",r.connectionState),"failed"===r.connectionState?l||(l=!0,clearTimeout(d),r.close(),a(new Error("WebRTC Connection failed"))):"closed"===r.connectionState?l||(l=!0,clearTimeout(d),a(new Error("WebRTC Connection closed"))):"connected"===r.connectionState&&console.log("WebRTC Connection established successfully")},!1),r.addEventListener("iceconnectionstatechange",()=>{console.log("ICE Connection state: ",r.iceConnectionState),"failed"===r.iceConnectionState&&(l||(l=!0,clearTimeout(d),r.close(),a(new Error("ICE Connection failed"))))}),n.on_init&&(await n.on_init(r),delete n.on_init);let h=r.createDataChannel(n.peer_id,{ordered:!0});h.binaryType="arraybuffer";const u=await r.createOffer();await r.setLocalDescription(u),await new Promise(e=>{"complete"===r.iceGatheringState?e():(r.addEventListener("icegatheringstatechange",()=>{"complete"===r.iceGatheringState&&e()}),setTimeout(e,5e3))});const _=await e.getService(t),p=await _.offer({sdp:r.localDescription.sdp,type:r.localDescription.type});h.onopen=()=>{n.channel=h,n.workspace=p.workspace,setTimeout(async()=>{if(!l)try{const e=await c(n);async function t(t,...r){return(0,o.assert)(!t.includes(":"),"WebRTC service name should not contain ':'"),(0,o.assert)(!t.includes("/"),"WebRTC service name should not contain '/'"),await e.get_remote_service(n.workspace+"/"+n.peer_id+":"+t,...r)}async function h(){await e.disconnect(),r.close()}r.rpc=e,r.getService=(0,i.schemaFunction)(t,{name:"getService",description:"Get a remote service via webrtc",parameters:{type:"object",properties:{service_id:{type:"string",description:"Service ID. This should be a service id in the format: 'workspace/service_id', 'workspace/client_id:service_id' or 'workspace/client_id:service_id@app_id'"},config:{type:"object",description:"Options for the service"}},required:["id"]}}),r.disconnect=(0,i.schemaFunction)(h,{name:"disconnect",description:"Disconnect from the webrtc connection via webrtc",parameters:{type:"object",properties:{}}}),r.registerCodec=(0,i.schemaFunction)(e.register_codec,{name:"registerCodec",description:"Register a codec for the webrtc connection",parameters:{type:"object",properties:{codec:{type:"object",description:"Codec to register",properties:{name:{type:"string"},type:{},encoder:{type:"function"},decoder:{type:"function"}}}}}}),l=!0,clearTimeout(d),s(r)}catch(u){l||(l=!0,clearTimeout(d),a(u))}},1e3)},h.onclose=()=>{l||(l=!0,clearTimeout(d),a(new Error("Data channel closed")))},h.onerror=e=>{l||(l=!0,clearTimeout(d),a(new Error(`Data channel error: ${e}`)))},await r.setRemoteDescription(new RTCSessionDescription({sdp:p.sdp,type:p.type}))}catch(e){l||(l=!0,clearTimeout(d),a(e))}})}async function l(e,t,n){const r=(n=n||{visibility:"protected",require_context:!0}).on_init;return delete n.on_init,await e.registerService({id:t,config:n,offer:(t,o)=>async function(e,t,n,r,o){n=n||{};let i=new RTCSessionDescription({sdp:e.sdp,type:e.type}),s=new RTCPeerConnection({iceServers:n.ice_servers||[{urls:["stun:stun.l.google.com:19302"]}],sdpSemantics:"unified-plan"});t&&s.addEventListener("datachannel",async e=>{const n=e.channel;let r=null;o&&o.user&&(r={user:o.user,ws:o.ws}),(await c({channel:n,client_id:n.label,workspace:t.config.workspace,context:r}))._services=t.rpc._services}),r&&await r(s),await s.setRemoteDescription(i);let a=await s.createAnswer();return await s.setLocalDescription(a),await new Promise(e=>{"complete"===s.iceGatheringState?e():(s.addEventListener("icegatheringstatechange",()=>{"complete"===s.iceGatheringState&&e()}),setTimeout(e,5e3))}),{sdp:s.localDescription.sdp,type:s.localDescription.type,workspace:t.config.workspace}}(t,e,n,r,o)})}},"./node_modules/@msgpack/msgpack/dist.es5+esm/CachedKeyDecoder.mjs":
17
17
  /*!*************************************************************************!*\
18
18
  !*** ./node_modules/@msgpack/msgpack/dist.es5+esm/CachedKeyDecoder.mjs ***!
19
- \*************************************************************************/(e,t,n)=>{n.r(t),n.d(t,{CachedKeyDecoder:()=>o});var r=n(/*! ./utils/utf8.mjs */"./node_modules/@msgpack/msgpack/dist.es5+esm/utils/utf8.mjs"),o=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 n=0;n<this.maxKeyLength;n++)this.caches.push([])}return e.prototype.canBeCached=function(e){return e>0&&e<=this.maxKeyLength},e.prototype.find=function(e,t,n){e:for(var r=0,o=this.caches[n-1];r<o.length;r++){for(var s=o[r],i=s.bytes,c=0;c<n;c++)if(i[c]!==e[t+c])continue e;return s.str}return null},e.prototype.store=function(e,t){var n=this.caches[e.length-1],r={bytes:e,str:t};n.length>=this.maxLengthPerKey?n[Math.random()*n.length|0]=r:n.push(r)},e.prototype.decode=function(e,t,n){var o=this.find(e,t,n);if(null!=o)return this.hit++,o;this.miss++;var s=(0,r.utf8DecodeJs)(e,t,n),i=Uint8Array.prototype.slice.call(e,t,t+n);return this.store(i,s),s},e}()},"./node_modules/@msgpack/msgpack/dist.es5+esm/DecodeError.mjs":
19
+ \*************************************************************************/(e,t,n)=>{n.r(t),n.d(t,{CachedKeyDecoder:()=>o});var r=n(/*! ./utils/utf8.mjs */"./node_modules/@msgpack/msgpack/dist.es5+esm/utils/utf8.mjs"),o=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 n=0;n<this.maxKeyLength;n++)this.caches.push([])}return e.prototype.canBeCached=function(e){return e>0&&e<=this.maxKeyLength},e.prototype.find=function(e,t,n){e:for(var r=0,o=this.caches[n-1];r<o.length;r++){for(var i=o[r],s=i.bytes,c=0;c<n;c++)if(s[c]!==e[t+c])continue e;return i.str}return null},e.prototype.store=function(e,t){var n=this.caches[e.length-1],r={bytes:e,str:t};n.length>=this.maxLengthPerKey?n[Math.random()*n.length|0]=r:n.push(r)},e.prototype.decode=function(e,t,n){var o=this.find(e,t,n);if(null!=o)return this.hit++,o;this.miss++;var i=(0,r.utf8DecodeJs)(e,t,n),s=Uint8Array.prototype.slice.call(e,t,t+n);return this.store(s,i),i},e}()},"./node_modules/@msgpack/msgpack/dist.es5+esm/DecodeError.mjs":
20
20
  /*!********************************************************************!*\
21
21
  !*** ./node_modules/@msgpack/msgpack/dist.es5+esm/DecodeError.mjs ***!
22
- \********************************************************************/(e,t,n)=>{n.r(t),n.d(t,{DecodeError:()=>s});var r,o=(r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},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 n(){this.constructor=e}r(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),s=function(e){function t(n){var r=e.call(this,n)||this,o=Object.create(t.prototype);return Object.setPrototypeOf(r,o),Object.defineProperty(r,"name",{configurable:!0,enumerable:!1,value:t.name}),r}return o(t,e),t}(Error)},"./node_modules/@msgpack/msgpack/dist.es5+esm/Decoder.mjs":
22
+ \********************************************************************/(e,t,n)=>{n.r(t),n.d(t,{DecodeError:()=>i});var r,o=(r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},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 n(){this.constructor=e}r(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),i=function(e){function t(n){var r=e.call(this,n)||this,o=Object.create(t.prototype);return Object.setPrototypeOf(r,o),Object.defineProperty(r,"name",{configurable:!0,enumerable:!1,value:t.name}),r}return o(t,e),t}(Error)},"./node_modules/@msgpack/msgpack/dist.es5+esm/Decoder.mjs":
23
23
  /*!****************************************************************!*\
24
24
  !*** ./node_modules/@msgpack/msgpack/dist.es5+esm/Decoder.mjs ***!
25
- \****************************************************************/(e,t,n)=>{n.r(t),n.d(t,{DataViewIndexOutOfBoundsError:()=>y,Decoder:()=>v});var r=n(/*! ./utils/prettyByte.mjs */"./node_modules/@msgpack/msgpack/dist.es5+esm/utils/prettyByte.mjs"),o=n(/*! ./ExtensionCodec.mjs */"./node_modules/@msgpack/msgpack/dist.es5+esm/ExtensionCodec.mjs"),s=n(/*! ./utils/int.mjs */"./node_modules/@msgpack/msgpack/dist.es5+esm/utils/int.mjs"),i=n(/*! ./utils/utf8.mjs */"./node_modules/@msgpack/msgpack/dist.es5+esm/utils/utf8.mjs"),c=n(/*! ./utils/typedArrays.mjs */"./node_modules/@msgpack/msgpack/dist.es5+esm/utils/typedArrays.mjs"),a=n(/*! ./CachedKeyDecoder.mjs */"./node_modules/@msgpack/msgpack/dist.es5+esm/CachedKeyDecoder.mjs"),l=n(/*! ./DecodeError.mjs */"./node_modules/@msgpack/msgpack/dist.es5+esm/DecodeError.mjs"),_=function(e,t,n,r){return new(n||(n=Promise))(function(o,s){function i(e){try{a(r.next(e))}catch(e){s(e)}}function c(e){try{a(r.throw(e))}catch(e){s(e)}}function a(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(i,c)}a((r=r.apply(e,t||[])).next())})},d=function(e,t){var n,r,o,s,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return s={next:c(0),throw:c(1),return:c(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function c(s){return function(c){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;i;)try{if(n=1,r&&(o=2&s[0]?r.return:s[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,s[1])).done)return o;switch(r=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return i.label++,{value:s[1],done:!1};case 5:i.label++,r=s[1],s=[0];continue;case 7:s=i.ops.pop(),i.trys.pop();continue;default:if(!(o=i.trys,(o=o.length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]<o[3])){i.label=s[1];break}if(6===s[0]&&i.label<o[1]){i.label=o[1],o=s;break}if(o&&i.label<o[2]){i.label=o[2],i.ops.push(s);break}o[2]&&i.ops.pop(),i.trys.pop();continue}s=t.call(e,i)}catch(e){s=[6,e],r=0}finally{n=o=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,c])}}},h=function(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,n=e[Symbol.asyncIterator];return n?n.call(e):(e="function"==typeof __values?__values(e):e[Symbol.iterator](),t={},r("next"),r("throw"),r("return"),t[Symbol.asyncIterator]=function(){return this},t);function r(n){t[n]=e[n]&&function(t){return new Promise(function(r,o){(function(e,t,n,r){Promise.resolve(r).then(function(t){e({value:t,done:n})},t)})(r,o,(t=e[n](t)).done,t.value)})}}},u=function(e){return this instanceof u?(this.v=e,this):new u(e)},p=function(e,t,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r,o=n.apply(e,t||[]),s=[];return r={},i("next"),i("throw"),i("return"),r[Symbol.asyncIterator]=function(){return this},r;function i(e){o[e]&&(r[e]=function(t){return new Promise(function(n,r){s.push([e,t,n,r])>1||c(e,t)})})}function c(e,t){try{(n=o[e](t)).value instanceof u?Promise.resolve(n.value.v).then(a,l):_(s[0][2],n)}catch(e){_(s[0][3],e)}var n}function a(e){c("next",e)}function l(e){c("throw",e)}function _(e,t){e(t),s.shift(),s.length&&c(s[0][0],s[0][1])}},f=function(e){var t=typeof e;return"string"===t||"number"===t},m=new DataView(new ArrayBuffer(0)),g=new Uint8Array(m.buffer),y=function(){try{m.getInt8(0)}catch(e){return e.constructor}throw new Error("never reached")}(),w=new y("Insufficient data"),b=new a.CachedKeyDecoder,v=function(){function e(e,t,n,r,i,c,a,l){void 0===e&&(e=o.ExtensionCodec.defaultCodec),void 0===t&&(t=void 0),void 0===n&&(n=s.UINT32_MAX),void 0===r&&(r=s.UINT32_MAX),void 0===i&&(i=s.UINT32_MAX),void 0===c&&(c=s.UINT32_MAX),void 0===a&&(a=s.UINT32_MAX),void 0===l&&(l=b),this.extensionCodec=e,this.context=t,this.maxStrLength=n,this.maxBinLength=r,this.maxArrayLength=i,this.maxMapLength=c,this.maxExtLength=a,this.keyDecoder=l,this.totalPos=0,this.pos=0,this.view=m,this.bytes=g,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=(0,c.ensureUint8Array)(e),this.view=(0,c.createDataView)(this.bytes),this.pos=0},e.prototype.appendBuffer=function(e){if(-1!==this.headByte||this.hasRemaining(1)){var t=this.bytes.subarray(this.pos),n=(0,c.ensureUint8Array)(e),r=new Uint8Array(t.length+n.length);r.set(t),r.set(n,t.length),this.setBuffer(r)}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,n=this.pos;return new RangeError("Extra ".concat(t.byteLength-n," of ").concat(t.byteLength," byte(s) found at buffer[").concat(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 d(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,n,o,s;return _(this,void 0,void 0,function(){var i,c,a,l,_,u,p,f;return d(this,function(d){switch(d.label){case 0:i=!1,d.label=1;case 1:d.trys.push([1,6,7,12]),t=h(e),d.label=2;case 2:return[4,t.next()];case 3:if((n=d.sent()).done)return[3,5];if(a=n.value,i)throw this.createExtraByteError(this.totalPos);this.appendBuffer(a);try{c=this.doDecodeSync(),i=!0}catch(e){if(!(e instanceof y))throw e}this.totalPos+=this.pos,d.label=4;case 4:return[3,2];case 5:return[3,12];case 6:return l=d.sent(),o={error:l},[3,12];case 7:return d.trys.push([7,,10,11]),n&&!n.done&&(s=t.return)?[4,s.call(t)]:[3,9];case 8:d.sent(),d.label=9;case 9:return[3,11];case 10:if(o)throw o.error;return[7];case 11:return[7];case 12:if(i){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return[2,c]}throw u=(_=this).headByte,p=_.pos,f=_.totalPos,new RangeError("Insufficient data in parsing ".concat((0,r.prettyByte)(u)," at ").concat(f," (").concat(p," 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 p(this,arguments,function(){var n,r,o,s,i,c,a,l,_;return d(this,function(d){switch(d.label){case 0:n=t,r=-1,d.label=1;case 1:d.trys.push([1,13,14,19]),o=h(e),d.label=2;case 2:return[4,u(o.next())];case 3:if((s=d.sent()).done)return[3,12];if(i=s.value,t&&0===r)throw this.createExtraByteError(this.totalPos);this.appendBuffer(i),n&&(r=this.readArraySize(),n=!1,this.complete()),d.label=4;case 4:d.trys.push([4,9,,10]),d.label=5;case 5:return[4,u(this.doDecodeSync())];case 6:return[4,d.sent()];case 7:return d.sent(),0===--r?[3,8]:[3,5];case 8:return[3,10];case 9:if(!((c=d.sent())instanceof y))throw c;return[3,10];case 10:this.totalPos+=this.pos,d.label=11;case 11:return[3,2];case 12:return[3,19];case 13:return a=d.sent(),l={error:a},[3,19];case 14:return d.trys.push([14,,17,18]),s&&!s.done&&(_=o.return)?[4,u(_.call(o))]:[3,16];case 15:d.sent(),d.label=16;case 16:return[3,18];case 17:if(l)throw l.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!==(o=e-128)){this.pushMapState(o),this.complete();continue e}t={}}else if(e<160){if(0!==(o=e-144)){this.pushArrayState(o),this.complete();continue e}t=[]}else{var n=e-160;t=this.decodeUtf8String(n,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){n=this.lookU8();t=this.decodeUtf8String(n,1)}else if(218===e){n=this.lookU16();t=this.decodeUtf8String(n,2)}else if(219===e){n=this.lookU32();t=this.decodeUtf8String(n,4)}else if(220===e){if(0!==(o=this.readU16())){this.pushArrayState(o),this.complete();continue e}t=[]}else if(221===e){if(0!==(o=this.readU32())){this.pushArrayState(o),this.complete();continue e}t=[]}else if(222===e){if(0!==(o=this.readU16())){this.pushMapState(o),this.complete();continue e}t={}}else if(223===e){if(0!==(o=this.readU32())){this.pushMapState(o),this.complete();continue e}t={}}else if(196===e){var o=this.lookU8();t=this.decodeBinary(o,1)}else if(197===e){o=this.lookU16();t=this.decodeBinary(o,2)}else if(198===e){o=this.lookU32();t=this.decodeBinary(o,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){o=this.lookU8();t=this.decodeExtension(o,1)}else if(200===e){o=this.lookU16();t=this.decodeExtension(o,2)}else{if(201!==e)throw new l.DecodeError("Unrecognized type byte: ".concat((0,r.prettyByte)(e)));o=this.lookU32();t=this.decodeExtension(o,4)}this.complete();for(var s=this.stack;s.length>0;){var i=s[s.length-1];if(0===i.type){if(i.array[i.position]=t,i.position++,i.position!==i.size)continue e;s.pop(),t=i.array}else{if(1===i.type){if(!f(t))throw new l.DecodeError("The type of key must be string or number but "+typeof t);if("__proto__"===t)throw new l.DecodeError("The key __proto__ is not allowed");i.key=t,i.type=2;continue e}if(i.map[i.key]=t,i.readCount++,i.readCount!==i.size){i.key=null,i.type=1;continue e}s.pop(),t=i.map}}return t}},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 l.DecodeError("Unrecognized array type byte: ".concat((0,r.prettyByte)(e)))}},e.prototype.pushMapState=function(e){if(e>this.maxMapLength)throw new l.DecodeError("Max length exceeded: map length (".concat(e,") > maxMapLengthLength (").concat(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 l.DecodeError("Max length exceeded: array length (".concat(e,") > maxArrayLength (").concat(this.maxArrayLength,")"));this.stack.push({type:0,size:e,array:new Array(e),position:0})},e.prototype.decodeUtf8String=function(e,t){var n;if(e>this.maxStrLength)throw new l.DecodeError("Max length exceeded: UTF-8 byte length (".concat(e,") > maxStrLength (").concat(this.maxStrLength,")"));if(this.bytes.byteLength<this.pos+t+e)throw w;var r,o=this.pos+t;return r=this.stateIsMapKey()&&(null===(n=this.keyDecoder)||void 0===n?void 0:n.canBeCached(e))?this.keyDecoder.decode(this.bytes,o,e):e>i.TEXT_DECODER_THRESHOLD?(0,i.utf8DecodeTD)(this.bytes,o,e):(0,i.utf8DecodeJs)(this.bytes,o,e),this.pos+=t+e,r},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 l.DecodeError("Max length exceeded: bin length (".concat(e,") > maxBinLength (").concat(this.maxBinLength,")"));if(!this.hasRemaining(e+t))throw w;var n=this.pos+t,r=this.bytes.subarray(n,n+e);return this.pos+=t+e,r},e.prototype.decodeExtension=function(e,t){if(e>this.maxExtLength)throw new l.DecodeError("Max length exceeded: ext length (".concat(e,") > maxExtLength (").concat(this.maxExtLength,")"));var n=this.view.getInt8(this.pos+t),r=this.decodeBinary(e,t+1);return this.extensionCodec.decode(r,n,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=(0,s.getUint64)(this.view,this.pos);return this.pos+=8,e},e.prototype.readI64=function(){var e=(0,s.getInt64)(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}()},"./node_modules/@msgpack/msgpack/dist.es5+esm/Encoder.mjs":
25
+ \****************************************************************/(e,t,n)=>{n.r(t),n.d(t,{DataViewIndexOutOfBoundsError:()=>y,Decoder:()=>v});var r=n(/*! ./utils/prettyByte.mjs */"./node_modules/@msgpack/msgpack/dist.es5+esm/utils/prettyByte.mjs"),o=n(/*! ./ExtensionCodec.mjs */"./node_modules/@msgpack/msgpack/dist.es5+esm/ExtensionCodec.mjs"),i=n(/*! ./utils/int.mjs */"./node_modules/@msgpack/msgpack/dist.es5+esm/utils/int.mjs"),s=n(/*! ./utils/utf8.mjs */"./node_modules/@msgpack/msgpack/dist.es5+esm/utils/utf8.mjs"),c=n(/*! ./utils/typedArrays.mjs */"./node_modules/@msgpack/msgpack/dist.es5+esm/utils/typedArrays.mjs"),a=n(/*! ./CachedKeyDecoder.mjs */"./node_modules/@msgpack/msgpack/dist.es5+esm/CachedKeyDecoder.mjs"),l=n(/*! ./DecodeError.mjs */"./node_modules/@msgpack/msgpack/dist.es5+esm/DecodeError.mjs"),d=function(e,t,n,r){return new(n||(n=Promise))(function(o,i){function s(e){try{a(r.next(e))}catch(e){i(e)}}function c(e){try{a(r.throw(e))}catch(e){i(e)}}function a(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(s,c)}a((r=r.apply(e,t||[])).next())})},h=function(e,t){var n,r,o,i,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:c(0),throw:c(1),return:c(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function c(i){return function(c){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return s.label++,{value:i[1],done:!1};case 5:s.label++,r=i[1],i=[0];continue;case 7:i=s.ops.pop(),s.trys.pop();continue;default:if(!(o=s.trys,(o=o.length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){s=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]<o[3])){s.label=i[1];break}if(6===i[0]&&s.label<o[1]){s.label=o[1],o=i;break}if(o&&s.label<o[2]){s.label=o[2],s.ops.push(i);break}o[2]&&s.ops.pop(),s.trys.pop();continue}i=t.call(e,s)}catch(e){i=[6,e],r=0}finally{n=o=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,c])}}},u=function(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,n=e[Symbol.asyncIterator];return n?n.call(e):(e="function"==typeof __values?__values(e):e[Symbol.iterator](),t={},r("next"),r("throw"),r("return"),t[Symbol.asyncIterator]=function(){return this},t);function r(n){t[n]=e[n]&&function(t){return new Promise(function(r,o){(function(e,t,n,r){Promise.resolve(r).then(function(t){e({value:t,done:n})},t)})(r,o,(t=e[n](t)).done,t.value)})}}},_=function(e){return this instanceof _?(this.v=e,this):new _(e)},p=function(e,t,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r,o=n.apply(e,t||[]),i=[];return r={},s("next"),s("throw"),s("return"),r[Symbol.asyncIterator]=function(){return this},r;function s(e){o[e]&&(r[e]=function(t){return new Promise(function(n,r){i.push([e,t,n,r])>1||c(e,t)})})}function c(e,t){try{(n=o[e](t)).value instanceof _?Promise.resolve(n.value.v).then(a,l):d(i[0][2],n)}catch(e){d(i[0][3],e)}var n}function a(e){c("next",e)}function l(e){c("throw",e)}function d(e,t){e(t),i.shift(),i.length&&c(i[0][0],i[0][1])}},f=function(e){var t=typeof e;return"string"===t||"number"===t},m=new DataView(new ArrayBuffer(0)),g=new Uint8Array(m.buffer),y=function(){try{m.getInt8(0)}catch(e){return e.constructor}throw new Error("never reached")}(),w=new y("Insufficient data"),b=new a.CachedKeyDecoder,v=function(){function e(e,t,n,r,s,c,a,l){void 0===e&&(e=o.ExtensionCodec.defaultCodec),void 0===t&&(t=void 0),void 0===n&&(n=i.UINT32_MAX),void 0===r&&(r=i.UINT32_MAX),void 0===s&&(s=i.UINT32_MAX),void 0===c&&(c=i.UINT32_MAX),void 0===a&&(a=i.UINT32_MAX),void 0===l&&(l=b),this.extensionCodec=e,this.context=t,this.maxStrLength=n,this.maxBinLength=r,this.maxArrayLength=s,this.maxMapLength=c,this.maxExtLength=a,this.keyDecoder=l,this.totalPos=0,this.pos=0,this.view=m,this.bytes=g,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=(0,c.ensureUint8Array)(e),this.view=(0,c.createDataView)(this.bytes),this.pos=0},e.prototype.appendBuffer=function(e){if(-1!==this.headByte||this.hasRemaining(1)){var t=this.bytes.subarray(this.pos),n=(0,c.ensureUint8Array)(e),r=new Uint8Array(t.length+n.length);r.set(t),r.set(n,t.length),this.setBuffer(r)}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,n=this.pos;return new RangeError("Extra ".concat(t.byteLength-n," of ").concat(t.byteLength," byte(s) found at buffer[").concat(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 h(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,n,o,i;return d(this,void 0,void 0,function(){var s,c,a,l,d,_,p,f;return h(this,function(h){switch(h.label){case 0:s=!1,h.label=1;case 1:h.trys.push([1,6,7,12]),t=u(e),h.label=2;case 2:return[4,t.next()];case 3:if((n=h.sent()).done)return[3,5];if(a=n.value,s)throw this.createExtraByteError(this.totalPos);this.appendBuffer(a);try{c=this.doDecodeSync(),s=!0}catch(e){if(!(e instanceof y))throw e}this.totalPos+=this.pos,h.label=4;case 4:return[3,2];case 5:return[3,12];case 6:return l=h.sent(),o={error:l},[3,12];case 7:return h.trys.push([7,,10,11]),n&&!n.done&&(i=t.return)?[4,i.call(t)]:[3,9];case 8:h.sent(),h.label=9;case 9:return[3,11];case 10:if(o)throw o.error;return[7];case 11:return[7];case 12:if(s){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return[2,c]}throw _=(d=this).headByte,p=d.pos,f=d.totalPos,new RangeError("Insufficient data in parsing ".concat((0,r.prettyByte)(_)," at ").concat(f," (").concat(p," 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 p(this,arguments,function(){var n,r,o,i,s,c,a,l,d;return h(this,function(h){switch(h.label){case 0:n=t,r=-1,h.label=1;case 1:h.trys.push([1,13,14,19]),o=u(e),h.label=2;case 2:return[4,_(o.next())];case 3:if((i=h.sent()).done)return[3,12];if(s=i.value,t&&0===r)throw this.createExtraByteError(this.totalPos);this.appendBuffer(s),n&&(r=this.readArraySize(),n=!1,this.complete()),h.label=4;case 4:h.trys.push([4,9,,10]),h.label=5;case 5:return[4,_(this.doDecodeSync())];case 6:return[4,h.sent()];case 7:return h.sent(),0===--r?[3,8]:[3,5];case 8:return[3,10];case 9:if(!((c=h.sent())instanceof y))throw c;return[3,10];case 10:this.totalPos+=this.pos,h.label=11;case 11:return[3,2];case 12:return[3,19];case 13:return a=h.sent(),l={error:a},[3,19];case 14:return h.trys.push([14,,17,18]),i&&!i.done&&(d=o.return)?[4,_(d.call(o))]:[3,16];case 15:h.sent(),h.label=16;case 16:return[3,18];case 17:if(l)throw l.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!==(o=e-128)){this.pushMapState(o),this.complete();continue e}t={}}else if(e<160){if(0!==(o=e-144)){this.pushArrayState(o),this.complete();continue e}t=[]}else{var n=e-160;t=this.decodeUtf8String(n,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){n=this.lookU8();t=this.decodeUtf8String(n,1)}else if(218===e){n=this.lookU16();t=this.decodeUtf8String(n,2)}else if(219===e){n=this.lookU32();t=this.decodeUtf8String(n,4)}else if(220===e){if(0!==(o=this.readU16())){this.pushArrayState(o),this.complete();continue e}t=[]}else if(221===e){if(0!==(o=this.readU32())){this.pushArrayState(o),this.complete();continue e}t=[]}else if(222===e){if(0!==(o=this.readU16())){this.pushMapState(o),this.complete();continue e}t={}}else if(223===e){if(0!==(o=this.readU32())){this.pushMapState(o),this.complete();continue e}t={}}else if(196===e){var o=this.lookU8();t=this.decodeBinary(o,1)}else if(197===e){o=this.lookU16();t=this.decodeBinary(o,2)}else if(198===e){o=this.lookU32();t=this.decodeBinary(o,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){o=this.lookU8();t=this.decodeExtension(o,1)}else if(200===e){o=this.lookU16();t=this.decodeExtension(o,2)}else{if(201!==e)throw new l.DecodeError("Unrecognized type byte: ".concat((0,r.prettyByte)(e)));o=this.lookU32();t=this.decodeExtension(o,4)}this.complete();for(var i=this.stack;i.length>0;){var s=i[i.length-1];if(0===s.type){if(s.array[s.position]=t,s.position++,s.position!==s.size)continue e;i.pop(),t=s.array}else{if(1===s.type){if(!f(t))throw new l.DecodeError("The type of key must be string or number but "+typeof t);if("__proto__"===t)throw new l.DecodeError("The key __proto__ is not allowed");s.key=t,s.type=2;continue e}if(s.map[s.key]=t,s.readCount++,s.readCount!==s.size){s.key=null,s.type=1;continue e}i.pop(),t=s.map}}return t}},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 l.DecodeError("Unrecognized array type byte: ".concat((0,r.prettyByte)(e)))}},e.prototype.pushMapState=function(e){if(e>this.maxMapLength)throw new l.DecodeError("Max length exceeded: map length (".concat(e,") > maxMapLengthLength (").concat(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 l.DecodeError("Max length exceeded: array length (".concat(e,") > maxArrayLength (").concat(this.maxArrayLength,")"));this.stack.push({type:0,size:e,array:new Array(e),position:0})},e.prototype.decodeUtf8String=function(e,t){var n;if(e>this.maxStrLength)throw new l.DecodeError("Max length exceeded: UTF-8 byte length (".concat(e,") > maxStrLength (").concat(this.maxStrLength,")"));if(this.bytes.byteLength<this.pos+t+e)throw w;var r,o=this.pos+t;return r=this.stateIsMapKey()&&(null===(n=this.keyDecoder)||void 0===n?void 0:n.canBeCached(e))?this.keyDecoder.decode(this.bytes,o,e):e>s.TEXT_DECODER_THRESHOLD?(0,s.utf8DecodeTD)(this.bytes,o,e):(0,s.utf8DecodeJs)(this.bytes,o,e),this.pos+=t+e,r},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 l.DecodeError("Max length exceeded: bin length (".concat(e,") > maxBinLength (").concat(this.maxBinLength,")"));if(!this.hasRemaining(e+t))throw w;var n=this.pos+t,r=this.bytes.subarray(n,n+e);return this.pos+=t+e,r},e.prototype.decodeExtension=function(e,t){if(e>this.maxExtLength)throw new l.DecodeError("Max length exceeded: ext length (".concat(e,") > maxExtLength (").concat(this.maxExtLength,")"));var n=this.view.getInt8(this.pos+t),r=this.decodeBinary(e,t+1);return this.extensionCodec.decode(r,n,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=(0,i.getUint64)(this.view,this.pos);return this.pos+=8,e},e.prototype.readI64=function(){var e=(0,i.getInt64)(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}()},"./node_modules/@msgpack/msgpack/dist.es5+esm/Encoder.mjs":
26
26
  /*!****************************************************************!*\
27
27
  !*** ./node_modules/@msgpack/msgpack/dist.es5+esm/Encoder.mjs ***!
28
- \****************************************************************/(e,t,n)=>{n.r(t),n.d(t,{DEFAULT_INITIAL_BUFFER_SIZE:()=>a,DEFAULT_MAX_DEPTH:()=>c,Encoder:()=>l});var r=n(/*! ./utils/utf8.mjs */"./node_modules/@msgpack/msgpack/dist.es5+esm/utils/utf8.mjs"),o=n(/*! ./ExtensionCodec.mjs */"./node_modules/@msgpack/msgpack/dist.es5+esm/ExtensionCodec.mjs"),s=n(/*! ./utils/int.mjs */"./node_modules/@msgpack/msgpack/dist.es5+esm/utils/int.mjs"),i=n(/*! ./utils/typedArrays.mjs */"./node_modules/@msgpack/msgpack/dist.es5+esm/utils/typedArrays.mjs"),c=100,a=2048,l=function(){function e(e,t,n,r,s,i,l,_){void 0===e&&(e=o.ExtensionCodec.defaultCodec),void 0===t&&(t=void 0),void 0===n&&(n=c),void 0===r&&(r=a),void 0===s&&(s=!1),void 0===i&&(i=!1),void 0===l&&(l=!1),void 0===_&&(_=!1),this.extensionCodec=e,this.context=t,this.maxDepth=n,this.initialBufferSize=r,this.sortKeys=s,this.forceFloat32=i,this.ignoreUndefined=l,this.forceIntegerToFloat=_,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}return e.prototype.reinitializeState=function(){this.pos=0},e.prototype.encodeSharedRef=function(e){return this.reinitializeState(),this.doEncode(e,1),this.bytes.subarray(0,this.pos)},e.prototype.encode=function(e){return this.reinitializeState(),this.doEncode(e,1),this.bytes.slice(0,this.pos)},e.prototype.doEncode=function(e,t){if(t>this.maxDepth)throw new Error("Too deep objects in depth ".concat(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),n=new Uint8Array(t),r=new DataView(t);n.set(this.bytes),this.view=r,this.bytes=n},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: ".concat(e," bytes in UTF-8"));this.writeU8(219),this.writeU32(e)}},e.prototype.encodeString=function(e){if(e.length>r.TEXT_ENCODER_THRESHOLD){var t=(0,r.utf8Count)(e);this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),(0,r.utf8EncodeTE)(e,this.bytes,this.pos),this.pos+=t}else{t=(0,r.utf8Count)(e);this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),(0,r.utf8EncodeJs)(e,this.bytes,this.pos),this.pos+=t}},e.prototype.encodeObject=function(e,t){var n=this.extensionCodec.tryToEncode(e,this.context);if(null!=n)this.encodeExtension(n);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: ".concat(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: ".concat(t));this.writeU8(198),this.writeU32(t)}var n=(0,i.ensureUint8Array)(e);this.writeU8a(n)},e.prototype.encodeArray=function(e,t){var n=e.length;if(n<16)this.writeU8(144+n);else if(n<65536)this.writeU8(220),this.writeU16(n);else{if(!(n<4294967296))throw new Error("Too large array: ".concat(n));this.writeU8(221),this.writeU32(n)}for(var r=0,o=e;r<o.length;r++){var s=o[r];this.doEncode(s,t+1)}},e.prototype.countWithoutUndefined=function(e,t){for(var n=0,r=0,o=t;r<o.length;r++){void 0!==e[o[r]]&&n++}return n},e.prototype.encodeMap=function(e,t){var n=Object.keys(e);this.sortKeys&&n.sort();var r=this.ignoreUndefined?this.countWithoutUndefined(e,n):n.length;if(r<16)this.writeU8(128+r);else if(r<65536)this.writeU8(222),this.writeU16(r);else{if(!(r<4294967296))throw new Error("Too large map object: ".concat(r));this.writeU8(223),this.writeU32(r)}for(var o=0,s=n;o<s.length;o++){var i=s[o],c=e[i];this.ignoreUndefined&&void 0===c||(this.encodeString(i),this.doEncode(c,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: ".concat(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),(0,s.setUint64)(this.view,this.pos,e),this.pos+=8},e.prototype.writeI64=function(e){this.ensureBufferSizeToWrite(8),(0,s.setInt64)(this.view,this.pos,e),this.pos+=8},e}()},"./node_modules/@msgpack/msgpack/dist.es5+esm/ExtData.mjs":
28
+ \****************************************************************/(e,t,n)=>{n.r(t),n.d(t,{DEFAULT_INITIAL_BUFFER_SIZE:()=>a,DEFAULT_MAX_DEPTH:()=>c,Encoder:()=>l});var r=n(/*! ./utils/utf8.mjs */"./node_modules/@msgpack/msgpack/dist.es5+esm/utils/utf8.mjs"),o=n(/*! ./ExtensionCodec.mjs */"./node_modules/@msgpack/msgpack/dist.es5+esm/ExtensionCodec.mjs"),i=n(/*! ./utils/int.mjs */"./node_modules/@msgpack/msgpack/dist.es5+esm/utils/int.mjs"),s=n(/*! ./utils/typedArrays.mjs */"./node_modules/@msgpack/msgpack/dist.es5+esm/utils/typedArrays.mjs"),c=100,a=2048,l=function(){function e(e,t,n,r,i,s,l,d){void 0===e&&(e=o.ExtensionCodec.defaultCodec),void 0===t&&(t=void 0),void 0===n&&(n=c),void 0===r&&(r=a),void 0===i&&(i=!1),void 0===s&&(s=!1),void 0===l&&(l=!1),void 0===d&&(d=!1),this.extensionCodec=e,this.context=t,this.maxDepth=n,this.initialBufferSize=r,this.sortKeys=i,this.forceFloat32=s,this.ignoreUndefined=l,this.forceIntegerToFloat=d,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}return e.prototype.reinitializeState=function(){this.pos=0},e.prototype.encodeSharedRef=function(e){return this.reinitializeState(),this.doEncode(e,1),this.bytes.subarray(0,this.pos)},e.prototype.encode=function(e){return this.reinitializeState(),this.doEncode(e,1),this.bytes.slice(0,this.pos)},e.prototype.doEncode=function(e,t){if(t>this.maxDepth)throw new Error("Too deep objects in depth ".concat(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),n=new Uint8Array(t),r=new DataView(t);n.set(this.bytes),this.view=r,this.bytes=n},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: ".concat(e," bytes in UTF-8"));this.writeU8(219),this.writeU32(e)}},e.prototype.encodeString=function(e){if(e.length>r.TEXT_ENCODER_THRESHOLD){var t=(0,r.utf8Count)(e);this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),(0,r.utf8EncodeTE)(e,this.bytes,this.pos),this.pos+=t}else{t=(0,r.utf8Count)(e);this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),(0,r.utf8EncodeJs)(e,this.bytes,this.pos),this.pos+=t}},e.prototype.encodeObject=function(e,t){var n=this.extensionCodec.tryToEncode(e,this.context);if(null!=n)this.encodeExtension(n);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: ".concat(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: ".concat(t));this.writeU8(198),this.writeU32(t)}var n=(0,s.ensureUint8Array)(e);this.writeU8a(n)},e.prototype.encodeArray=function(e,t){var n=e.length;if(n<16)this.writeU8(144+n);else if(n<65536)this.writeU8(220),this.writeU16(n);else{if(!(n<4294967296))throw new Error("Too large array: ".concat(n));this.writeU8(221),this.writeU32(n)}for(var r=0,o=e;r<o.length;r++){var i=o[r];this.doEncode(i,t+1)}},e.prototype.countWithoutUndefined=function(e,t){for(var n=0,r=0,o=t;r<o.length;r++){void 0!==e[o[r]]&&n++}return n},e.prototype.encodeMap=function(e,t){var n=Object.keys(e);this.sortKeys&&n.sort();var r=this.ignoreUndefined?this.countWithoutUndefined(e,n):n.length;if(r<16)this.writeU8(128+r);else if(r<65536)this.writeU8(222),this.writeU16(r);else{if(!(r<4294967296))throw new Error("Too large map object: ".concat(r));this.writeU8(223),this.writeU32(r)}for(var o=0,i=n;o<i.length;o++){var s=i[o],c=e[s];this.ignoreUndefined&&void 0===c||(this.encodeString(s),this.doEncode(c,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: ".concat(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),(0,i.setUint64)(this.view,this.pos,e),this.pos+=8},e.prototype.writeI64=function(e){this.ensureBufferSizeToWrite(8),(0,i.setInt64)(this.view,this.pos,e),this.pos+=8},e}()},"./node_modules/@msgpack/msgpack/dist.es5+esm/ExtData.mjs":
29
29
  /*!****************************************************************!*\
30
30
  !*** ./node_modules/@msgpack/msgpack/dist.es5+esm/ExtData.mjs ***!
31
31
  \****************************************************************/(e,t,n)=>{n.r(t),n.d(t,{ExtData:()=>r});var r=function(e,t){this.type=e,this.data=t}},"./node_modules/@msgpack/msgpack/dist.es5+esm/ExtensionCodec.mjs":
32
32
  /*!***********************************************************************!*\
33
33
  !*** ./node_modules/@msgpack/msgpack/dist.es5+esm/ExtensionCodec.mjs ***!
34
- \***********************************************************************/(e,t,n)=>{n.r(t),n.d(t,{ExtensionCodec:()=>s});var r=n(/*! ./ExtData.mjs */"./node_modules/@msgpack/msgpack/dist.es5+esm/ExtData.mjs"),o=n(/*! ./timestamp.mjs */"./node_modules/@msgpack/msgpack/dist.es5+esm/timestamp.mjs"),s=function(){function e(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(o.timestampExtension)}return e.prototype.register=function(e){var t=e.type,n=e.encode,r=e.decode;if(t>=0)this.encoders[t]=n,this.decoders[t]=r;else{var o=1+t;this.builtInEncoders[o]=n,this.builtInDecoders[o]=r}},e.prototype.tryToEncode=function(e,t){for(var n=0;n<this.builtInEncoders.length;n++){if(null!=(s=this.builtInEncoders[n]))if(null!=(i=s(e,t))){var o=-1-n;return new r.ExtData(o,i)}}for(n=0;n<this.encoders.length;n++){var s,i;if(null!=(s=this.encoders[n]))if(null!=(i=s(e,t))){o=n;return new r.ExtData(o,i)}}return e instanceof r.ExtData?e:null},e.prototype.decode=function(e,t,n){var o=t<0?this.builtInDecoders[-1-t]:this.decoders[t];return o?o(e,t,n):new r.ExtData(t,e)},e.defaultCodec=new e,e}()},"./node_modules/@msgpack/msgpack/dist.es5+esm/decode.mjs":
34
+ \***********************************************************************/(e,t,n)=>{n.r(t),n.d(t,{ExtensionCodec:()=>i});var r=n(/*! ./ExtData.mjs */"./node_modules/@msgpack/msgpack/dist.es5+esm/ExtData.mjs"),o=n(/*! ./timestamp.mjs */"./node_modules/@msgpack/msgpack/dist.es5+esm/timestamp.mjs"),i=function(){function e(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(o.timestampExtension)}return e.prototype.register=function(e){var t=e.type,n=e.encode,r=e.decode;if(t>=0)this.encoders[t]=n,this.decoders[t]=r;else{var o=1+t;this.builtInEncoders[o]=n,this.builtInDecoders[o]=r}},e.prototype.tryToEncode=function(e,t){for(var n=0;n<this.builtInEncoders.length;n++){if(null!=(i=this.builtInEncoders[n]))if(null!=(s=i(e,t))){var o=-1-n;return new r.ExtData(o,s)}}for(n=0;n<this.encoders.length;n++){var i,s;if(null!=(i=this.encoders[n]))if(null!=(s=i(e,t))){o=n;return new r.ExtData(o,s)}}return e instanceof r.ExtData?e:null},e.prototype.decode=function(e,t,n){var o=t<0?this.builtInDecoders[-1-t]:this.decoders[t];return o?o(e,t,n):new r.ExtData(t,e)},e.defaultCodec=new e,e}()},"./node_modules/@msgpack/msgpack/dist.es5+esm/decode.mjs":
35
35
  /*!***************************************************************!*\
36
36
  !*** ./node_modules/@msgpack/msgpack/dist.es5+esm/decode.mjs ***!
37
- \***************************************************************/(e,t,n)=>{n.r(t),n.d(t,{decode:()=>s,decodeMulti:()=>i,defaultDecodeOptions:()=>o});var r=n(/*! ./Decoder.mjs */"./node_modules/@msgpack/msgpack/dist.es5+esm/Decoder.mjs"),o={};function s(e,t){return void 0===t&&(t=o),new r.Decoder(t.extensionCodec,t.context,t.maxStrLength,t.maxBinLength,t.maxArrayLength,t.maxMapLength,t.maxExtLength).decode(e)}function i(e,t){return void 0===t&&(t=o),new r.Decoder(t.extensionCodec,t.context,t.maxStrLength,t.maxBinLength,t.maxArrayLength,t.maxMapLength,t.maxExtLength).decodeMulti(e)}},"./node_modules/@msgpack/msgpack/dist.es5+esm/encode.mjs":
37
+ \***************************************************************/(e,t,n)=>{n.r(t),n.d(t,{decode:()=>i,decodeMulti:()=>s,defaultDecodeOptions:()=>o});var r=n(/*! ./Decoder.mjs */"./node_modules/@msgpack/msgpack/dist.es5+esm/Decoder.mjs"),o={};function i(e,t){return void 0===t&&(t=o),new r.Decoder(t.extensionCodec,t.context,t.maxStrLength,t.maxBinLength,t.maxArrayLength,t.maxMapLength,t.maxExtLength).decode(e)}function s(e,t){return void 0===t&&(t=o),new r.Decoder(t.extensionCodec,t.context,t.maxStrLength,t.maxBinLength,t.maxArrayLength,t.maxMapLength,t.maxExtLength).decodeMulti(e)}},"./node_modules/@msgpack/msgpack/dist.es5+esm/encode.mjs":
38
38
  /*!***************************************************************!*\
39
39
  !*** ./node_modules/@msgpack/msgpack/dist.es5+esm/encode.mjs ***!
40
- \***************************************************************/(e,t,n)=>{n.r(t),n.d(t,{encode:()=>s});var r=n(/*! ./Encoder.mjs */"./node_modules/@msgpack/msgpack/dist.es5+esm/Encoder.mjs"),o={};function s(e,t){return void 0===t&&(t=o),new r.Encoder(t.extensionCodec,t.context,t.maxDepth,t.initialBufferSize,t.sortKeys,t.forceFloat32,t.ignoreUndefined,t.forceIntegerToFloat).encodeSharedRef(e)}},"./node_modules/@msgpack/msgpack/dist.es5+esm/timestamp.mjs":
40
+ \***************************************************************/(e,t,n)=>{n.r(t),n.d(t,{encode:()=>i});var r=n(/*! ./Encoder.mjs */"./node_modules/@msgpack/msgpack/dist.es5+esm/Encoder.mjs"),o={};function i(e,t){return void 0===t&&(t=o),new r.Encoder(t.extensionCodec,t.context,t.maxDepth,t.initialBufferSize,t.sortKeys,t.forceFloat32,t.ignoreUndefined,t.forceIntegerToFloat).encodeSharedRef(e)}},"./node_modules/@msgpack/msgpack/dist.es5+esm/timestamp.mjs":
41
41
  /*!******************************************************************!*\
42
42
  !*** ./node_modules/@msgpack/msgpack/dist.es5+esm/timestamp.mjs ***!
43
- \******************************************************************/(e,t,n)=>{n.r(t),n.d(t,{EXT_TIMESTAMP:()=>s,decodeTimestampExtension:()=>h,decodeTimestampToTimeSpec:()=>d,encodeDateToTimeSpec:()=>l,encodeTimeSpecToTimestamp:()=>a,encodeTimestampExtension:()=>_,timestampExtension:()=>u});var r=n(/*! ./DecodeError.mjs */"./node_modules/@msgpack/msgpack/dist.es5+esm/DecodeError.mjs"),o=n(/*! ./utils/int.mjs */"./node_modules/@msgpack/msgpack/dist.es5+esm/utils/int.mjs"),s=-1,i=4294967295,c=17179869183;function a(e){var t=e.sec,n=e.nsec;if(t>=0&&n>=0&&t<=c){if(0===n&&t<=i){var r=new Uint8Array(4);return(l=new DataView(r.buffer)).setUint32(0,t),r}var s=t/4294967296,a=4294967295&t;r=new Uint8Array(8);return(l=new DataView(r.buffer)).setUint32(0,n<<2|3&s),l.setUint32(4,a),r}var l;r=new Uint8Array(12);return(l=new DataView(r.buffer)).setUint32(0,n),(0,o.setInt64)(l,4,t),r}function l(e){var t=e.getTime(),n=Math.floor(t/1e3),r=1e6*(t-1e3*n),o=Math.floor(r/1e9);return{sec:n+o,nsec:r-1e9*o}}function _(e){return e instanceof Date?a(l(e)):null}function d(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 n=t.getUint32(0);return{sec:4294967296*(3&n)+t.getUint32(4),nsec:n>>>2};case 12:return{sec:(0,o.getInt64)(t,4),nsec:t.getUint32(0)};default:throw new r.DecodeError("Unrecognized data size for timestamp (expected 4, 8, or 12): ".concat(e.length))}}function h(e){var t=d(e);return new Date(1e3*t.sec+t.nsec/1e6)}var u={type:s,encode:_,decode:h}},"./node_modules/@msgpack/msgpack/dist.es5+esm/utils/int.mjs":
43
+ \******************************************************************/(e,t,n)=>{n.r(t),n.d(t,{EXT_TIMESTAMP:()=>i,decodeTimestampExtension:()=>u,decodeTimestampToTimeSpec:()=>h,encodeDateToTimeSpec:()=>l,encodeTimeSpecToTimestamp:()=>a,encodeTimestampExtension:()=>d,timestampExtension:()=>_});var r=n(/*! ./DecodeError.mjs */"./node_modules/@msgpack/msgpack/dist.es5+esm/DecodeError.mjs"),o=n(/*! ./utils/int.mjs */"./node_modules/@msgpack/msgpack/dist.es5+esm/utils/int.mjs"),i=-1,s=4294967295,c=17179869183;function a(e){var t=e.sec,n=e.nsec;if(t>=0&&n>=0&&t<=c){if(0===n&&t<=s){var r=new Uint8Array(4);return(l=new DataView(r.buffer)).setUint32(0,t),r}var i=t/4294967296,a=4294967295&t;r=new Uint8Array(8);return(l=new DataView(r.buffer)).setUint32(0,n<<2|3&i),l.setUint32(4,a),r}var l;r=new Uint8Array(12);return(l=new DataView(r.buffer)).setUint32(0,n),(0,o.setInt64)(l,4,t),r}function l(e){var t=e.getTime(),n=Math.floor(t/1e3),r=1e6*(t-1e3*n),o=Math.floor(r/1e9);return{sec:n+o,nsec:r-1e9*o}}function d(e){return e instanceof Date?a(l(e)):null}function h(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 n=t.getUint32(0);return{sec:4294967296*(3&n)+t.getUint32(4),nsec:n>>>2};case 12:return{sec:(0,o.getInt64)(t,4),nsec:t.getUint32(0)};default:throw new r.DecodeError("Unrecognized data size for timestamp (expected 4, 8, or 12): ".concat(e.length))}}function u(e){var t=h(e);return new Date(1e3*t.sec+t.nsec/1e6)}var _={type:i,encode:d,decode:u}},"./node_modules/@msgpack/msgpack/dist.es5+esm/utils/int.mjs":
44
44
  /*!******************************************************************!*\
45
45
  !*** ./node_modules/@msgpack/msgpack/dist.es5+esm/utils/int.mjs ***!
46
- \******************************************************************/(e,t,n)=>{n.r(t),n.d(t,{UINT32_MAX:()=>r,getInt64:()=>i,getUint64:()=>c,setInt64:()=>s,setUint64:()=>o});var r=4294967295;function o(e,t,n){var r=n/4294967296,o=n;e.setUint32(t,r),e.setUint32(t+4,o)}function s(e,t,n){var r=Math.floor(n/4294967296),o=n;e.setUint32(t,r),e.setUint32(t+4,o)}function i(e,t){return 4294967296*e.getInt32(t)+e.getUint32(t+4)}function c(e,t){return 4294967296*e.getUint32(t)+e.getUint32(t+4)}},"./node_modules/@msgpack/msgpack/dist.es5+esm/utils/prettyByte.mjs":
46
+ \******************************************************************/(e,t,n)=>{n.r(t),n.d(t,{UINT32_MAX:()=>r,getInt64:()=>s,getUint64:()=>c,setInt64:()=>i,setUint64:()=>o});var r=4294967295;function o(e,t,n){var r=n/4294967296,o=n;e.setUint32(t,r),e.setUint32(t+4,o)}function i(e,t,n){var r=Math.floor(n/4294967296),o=n;e.setUint32(t,r),e.setUint32(t+4,o)}function s(e,t){return 4294967296*e.getInt32(t)+e.getUint32(t+4)}function c(e,t){return 4294967296*e.getUint32(t)+e.getUint32(t+4)}},"./node_modules/@msgpack/msgpack/dist.es5+esm/utils/prettyByte.mjs":
47
47
  /*!*************************************************************************!*\
48
48
  !*** ./node_modules/@msgpack/msgpack/dist.es5+esm/utils/prettyByte.mjs ***!
49
49
  \*************************************************************************/(e,t,n)=>{function r(e){return"".concat(e<0?"-":"","0x").concat(Math.abs(e).toString(16).padStart(2,"0"))}n.r(t),n.d(t,{prettyByte:()=>r})},"./node_modules/@msgpack/msgpack/dist.es5+esm/utils/typedArrays.mjs":
@@ -52,8 +52,8 @@
52
52
  \**************************************************************************/(e,t,n)=>{function r(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)}function o(e){if(e instanceof ArrayBuffer)return new DataView(e);var t=r(e);return new DataView(t.buffer,t.byteOffset,t.byteLength)}n.r(t),n.d(t,{createDataView:()=>o,ensureUint8Array:()=>r})},"./node_modules/@msgpack/msgpack/dist.es5+esm/utils/utf8.mjs":
53
53
  /*!*******************************************************************!*\
54
54
  !*** ./node_modules/@msgpack/msgpack/dist.es5+esm/utils/utf8.mjs ***!
55
- \*******************************************************************/(e,t,n)=>{n.r(t),n.d(t,{TEXT_DECODER_THRESHOLD:()=>m,TEXT_ENCODER_THRESHOLD:()=>d,utf8Count:()=>a,utf8DecodeJs:()=>p,utf8DecodeTD:()=>g,utf8EncodeJs:()=>l,utf8EncodeTE:()=>h});var r,o,s,i=n(/*! ./int.mjs */"./node_modules/@msgpack/msgpack/dist.es5+esm/utils/int.mjs"),c=("undefined"==typeof process||"never"!==(null===(r=null===process||void 0===process?void 0:process.env)||void 0===r?void 0:r.TEXT_ENCODING))&&"undefined"!=typeof TextEncoder&&"undefined"!=typeof TextDecoder;function a(e){for(var t=e.length,n=0,r=0;r<t;){var o=e.charCodeAt(r++);if(4294967168&o)if(4294965248&o){if(o>=55296&&o<=56319&&r<t){var s=e.charCodeAt(r);56320==(64512&s)&&(++r,o=((1023&o)<<10)+(1023&s)+65536)}n+=4294901760&o?4:3}else n+=2;else n++}return n}function l(e,t,n){for(var r=e.length,o=n,s=0;s<r;){var i=e.charCodeAt(s++);if(4294967168&i){if(4294965248&i){if(i>=55296&&i<=56319&&s<r){var c=e.charCodeAt(s);56320==(64512&c)&&(++s,i=((1023&i)<<10)+(1023&c)+65536)}4294901760&i?(t[o++]=i>>18&7|240,t[o++]=i>>12&63|128,t[o++]=i>>6&63|128):(t[o++]=i>>12&15|224,t[o++]=i>>6&63|128)}else t[o++]=i>>6&31|192;t[o++]=63&i|128}else t[o++]=i}}var _=c?new TextEncoder:void 0,d=c?"undefined"!=typeof process&&"force"!==(null===(o=null===process||void 0===process?void 0:process.env)||void 0===o?void 0:o.TEXT_ENCODING)?200:0:i.UINT32_MAX;var h=(null==_?void 0:_.encodeInto)?function(e,t,n){_.encodeInto(e,t.subarray(n))}:function(e,t,n){t.set(_.encode(e),n)},u=4096;function p(e,t,n){for(var r=t,o=r+n,s=[],i="";r<o;){var c=e[r++];if(128&c)if(192==(224&c)){var a=63&e[r++];s.push((31&c)<<6|a)}else if(224==(240&c)){a=63&e[r++];var l=63&e[r++];s.push((31&c)<<12|a<<6|l)}else if(240==(248&c)){var _=(7&c)<<18|(a=63&e[r++])<<12|(l=63&e[r++])<<6|63&e[r++];_>65535&&(_-=65536,s.push(_>>>10&1023|55296),_=56320|1023&_),s.push(_)}else s.push(c);else s.push(c);s.length>=u&&(i+=String.fromCharCode.apply(String,s),s.length=0)}return s.length>0&&(i+=String.fromCharCode.apply(String,s)),i}var f=c?new TextDecoder:null,m=c?"undefined"!=typeof process&&"force"!==(null===(s=null===process||void 0===process?void 0:process.env)||void 0===s?void 0:s.TEXT_DECODER)?200:0:i.UINT32_MAX;function g(e,t,n){var r=e.subarray(t,t+n);return f.decode(r)}}},__webpack_module_cache__={};function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var n=__webpack_module_cache__[e]={exports:{}};return __webpack_modules__[e](n,n.exports,__webpack_require__),n.exports}__webpack_require__.d=(e,t)=>{for(var n in t)__webpack_require__.o(t,n)&&!__webpack_require__.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},__webpack_require__.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),__webpack_require__.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var __webpack_exports__={};
55
+ \*******************************************************************/(e,t,n)=>{n.r(t),n.d(t,{TEXT_DECODER_THRESHOLD:()=>m,TEXT_ENCODER_THRESHOLD:()=>h,utf8Count:()=>a,utf8DecodeJs:()=>p,utf8DecodeTD:()=>g,utf8EncodeJs:()=>l,utf8EncodeTE:()=>u});var r,o,i,s=n(/*! ./int.mjs */"./node_modules/@msgpack/msgpack/dist.es5+esm/utils/int.mjs"),c=("undefined"==typeof process||"never"!==(null===(r=null===process||void 0===process?void 0:process.env)||void 0===r?void 0:r.TEXT_ENCODING))&&"undefined"!=typeof TextEncoder&&"undefined"!=typeof TextDecoder;function a(e){for(var t=e.length,n=0,r=0;r<t;){var o=e.charCodeAt(r++);if(4294967168&o)if(4294965248&o){if(o>=55296&&o<=56319&&r<t){var i=e.charCodeAt(r);56320==(64512&i)&&(++r,o=((1023&o)<<10)+(1023&i)+65536)}n+=4294901760&o?4:3}else n+=2;else n++}return n}function l(e,t,n){for(var r=e.length,o=n,i=0;i<r;){var s=e.charCodeAt(i++);if(4294967168&s){if(4294965248&s){if(s>=55296&&s<=56319&&i<r){var c=e.charCodeAt(i);56320==(64512&c)&&(++i,s=((1023&s)<<10)+(1023&c)+65536)}4294901760&s?(t[o++]=s>>18&7|240,t[o++]=s>>12&63|128,t[o++]=s>>6&63|128):(t[o++]=s>>12&15|224,t[o++]=s>>6&63|128)}else t[o++]=s>>6&31|192;t[o++]=63&s|128}else t[o++]=s}}var d=c?new TextEncoder:void 0,h=c?"undefined"!=typeof process&&"force"!==(null===(o=null===process||void 0===process?void 0:process.env)||void 0===o?void 0:o.TEXT_ENCODING)?200:0:s.UINT32_MAX;var u=(null==d?void 0:d.encodeInto)?function(e,t,n){d.encodeInto(e,t.subarray(n))}:function(e,t,n){t.set(d.encode(e),n)},_=4096;function p(e,t,n){for(var r=t,o=r+n,i=[],s="";r<o;){var c=e[r++];if(128&c)if(192==(224&c)){var a=63&e[r++];i.push((31&c)<<6|a)}else if(224==(240&c)){a=63&e[r++];var l=63&e[r++];i.push((31&c)<<12|a<<6|l)}else if(240==(248&c)){var d=(7&c)<<18|(a=63&e[r++])<<12|(l=63&e[r++])<<6|63&e[r++];d>65535&&(d-=65536,i.push(d>>>10&1023|55296),d=56320|1023&d),i.push(d)}else i.push(c);else i.push(c);i.length>=_&&(s+=String.fromCharCode.apply(String,i),i.length=0)}return i.length>0&&(s+=String.fromCharCode.apply(String,i)),s}var f=c?new TextDecoder:null,m=c?"undefined"!=typeof process&&"force"!==(null===(i=null===process||void 0===process?void 0:process.env)||void 0===i?void 0:i.TEXT_DECODER)?200:0:s.UINT32_MAX;function g(e,t,n){var r=e.subarray(t,t+n);return f.decode(r)}}},__webpack_module_cache__={};function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var n=__webpack_module_cache__[e]={exports:{}};return __webpack_modules__[e](n,n.exports,__webpack_require__),n.exports}__webpack_require__.d=(e,t)=>{for(var n in t)__webpack_require__.o(t,n)&&!__webpack_require__.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},__webpack_require__.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),__webpack_require__.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var __webpack_exports__={};
56
56
  /*!*********************************!*\
57
57
  !*** ./src/websocket-client.js ***!
58
- \*********************************/__webpack_require__.r(__webpack_exports__),__webpack_require__.d(__webpack_exports__,{API_VERSION:()=>_rpc_js__WEBPACK_IMPORTED_MODULE_0__.API_VERSION,HTTPStreamingRPCConnection:()=>_http_client_js__WEBPACK_IMPORTED_MODULE_4__.HTTPStreamingRPCConnection,LocalWebSocket:()=>LocalWebSocket,RPC:()=>_rpc_js__WEBPACK_IMPORTED_MODULE_0__.RPC,connectToServer:()=>connectToServer,connectToServerHTTP:()=>_http_client_js__WEBPACK_IMPORTED_MODULE_4__.connectToServerHTTP,getRTCService:()=>_webrtc_client_js__WEBPACK_IMPORTED_MODULE_3__.getRTCService,getRemoteService:()=>getRemoteService,getRemoteServiceHTTP:()=>_http_client_js__WEBPACK_IMPORTED_MODULE_4__.getRemoteServiceHTTP,hyphaWebsocketClient:()=>hyphaWebsocketClient,loadRequirements:()=>_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.loadRequirements,login:()=>login,logout:()=>logout,normalizeServerUrlHTTP:()=>_http_client_js__WEBPACK_IMPORTED_MODULE_4__.normalizeServerUrl,registerRTCService:()=>_webrtc_client_js__WEBPACK_IMPORTED_MODULE_3__.registerRTCService,schemaFunction:()=>_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction,setupLocalClient:()=>setupLocalClient});var _rpc_js__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__(/*! ./rpc.js */"./src/rpc.js"),_utils_index_js__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__(/*! ./utils/index.js */"./src/utils/index.js"),_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__=__webpack_require__(/*! ./utils/schema.js */"./src/utils/schema.js"),_webrtc_client_js__WEBPACK_IMPORTED_MODULE_3__=__webpack_require__(/*! ./webrtc-client.js */"./src/webrtc-client.js"),_http_client_js__WEBPACK_IMPORTED_MODULE_4__=__webpack_require__(/*! ./http-client.js */"./src/http-client.js");const MAX_RETRY=1e6;class WebsocketRPCConnection{constructor(e,t,n,r,o=null,s=60,i=null,c=7200,a=null){(0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.assert)(e&&t,"server_url and client_id are required"),this._server_url=e,this._client_id=t,this._workspace=n,this._token=r,this._reconnection_token=o,this._websocket=null,this._handle_message=null,this._handle_connected=null,this._handle_disconnected=null,this._timeout=s,this._WebSocketClass=i||WebSocket,this._closed=!1,this._legacy_auth=null,this.connection_info=null,this._enable_reconnect=!1,this._token_refresh_interval=c,this.manager_id=null,this._refresh_token_task=null,this._reconnect_timeouts=new Set,this._additional_headers=a,this._reconnecting=!1,this._disconnectedNotified=!1}_cleanup(){this._refresh_token_delay&&(clearTimeout(this._refresh_token_delay),this._refresh_token_delay=null),this._refresh_token_task&&(clearInterval(this._refresh_token_task),this._refresh_token_task=null);for(const e of this._reconnect_timeouts)clearTimeout(e);this._reconnect_timeouts.clear()}on_message(e){(0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.assert)(e,"handler is required"),this._handle_message=e}on_connected(e){this._handle_connected=e}on_disconnected(e){this._handle_disconnected=e}async _attempt_connection(e,t=!0){return new Promise((n,r)=>{this._legacy_auth=!1;const o=new this._WebSocketClass(e);o.binaryType="arraybuffer",o.onopen=()=>{console.info("WebSocket connection established"),n(o)},o.onerror=e=>{console.error("WebSocket connection error:",e),r(new Error(`WebSocket connection error: ${e}`))},o.onclose=o=>{1003===o.code&&t?(console.info("Received 1003 error, attempting connection with query parameters."),this._legacy_auth=!0,this._attempt_connection_with_query_params(e).then(n).catch(r)):this._notifyDisconnected(o.reason)}})}async _attempt_connection_with_query_params(e){const t=[];this._client_id&&t.push(`client_id=${encodeURIComponent(this._client_id)}`),this._workspace&&t.push(`workspace=${encodeURIComponent(this._workspace)}`),this._token&&t.push(`token=${encodeURIComponent(this._token)}`),this._reconnection_token&&t.push(`reconnection_token=${encodeURIComponent(this._reconnection_token)}`);const n=e+(t.length>0?`?${t.join("&")}`:"");return await this._attempt_connection(n,!1)}_establish_connection(){return new Promise((e,t)=>{this._websocket.onmessage=n=>{const r=n.data,o=JSON.parse(r);if("connection_info"!=o.type){if("error"==o.type){const e="ConnectionAbortedError: "+o.message;return console.error("Failed to connect, "+e),void t(new Error(e))}return console.error("ConnectionAbortedError: Unexpected message received from the server:",r),void t(new Error("ConnectionAbortedError: Unexpected message received from the server"))}this.connection_info=o,this._workspace&&(0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.assert)(this.connection_info.workspace===this._workspace,`Connected to the wrong workspace: ${this.connection_info.workspace}, expected: ${this._workspace}`),this.connection_info.reconnection_token&&(this._reconnection_token=this.connection_info.reconnection_token),this.connection_info.reconnection_token_life_time&&this._token_refresh_interval>this.connection_info.reconnection_token_life_time/1.5&&(console.warn(`Token refresh interval is too long (${this._token_refresh_interval}), setting it to 1.5 times of the token life time(${this.connection_info.reconnection_token_life_time}).`),this._token_refresh_interval=this.connection_info.reconnection_token_life_time/1.5),this.manager_id=this.connection_info.manager_id||null,console.log(`Successfully connected to the server, workspace: ${this.connection_info.workspace}, manager_id: ${this.manager_id}`),this.connection_info.announcement&&console.log(`${this.connection_info.announcement}`),e(this.connection_info)}})}async open(){console.log("Creating a new websocket connection to",this._server_url.split("?")[0]);try{if(this._websocket=await this._attempt_connection(this._server_url),this._legacy_auth)throw new Error("NotImplementedError: Legacy authentication is not supported");const e=JSON.stringify({client_id:this._client_id,workspace:this._workspace,token:this._token,reconnection_token:this._reconnection_token});return this._websocket.send(e),await(0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.waitFor)(this._establish_connection(),this._timeout,"Failed to receive the first message from the server"),this._token_refresh_interval>0&&(this._refresh_token_delay=setTimeout(()=>{this._refresh_token_delay=null,this._closed||(this._send_refresh_token(),this._refresh_token_task=setInterval(()=>{this._send_refresh_token()},1e3*this._token_refresh_interval))},2e3)),this._enable_reconnect=!0,this._closed=!1,this._disconnectedNotified=!1,this._websocket.onmessage=e=>{if("string"==typeof e.data){const t=JSON.parse(e.data);"reconnection_token"===t.type?this._reconnection_token=t.reconnection_token:console.log("Received message from the server:",t)}else this._handle_message(e.data)},this._websocket.onerror=e=>{console.error("WebSocket connection error:",e),this._cleanup()},this._websocket.onclose=this._handle_close.bind(this),this._handle_connected&&this._handle_connected(this.connection_info),this.connection_info}catch(e){throw this._cleanup(),console.error("Failed to connect to",this._server_url.split("?")[0],e),e}}_send_refresh_token(){if(this._websocket&&this._websocket.readyState===WebSocket.OPEN){const e=JSON.stringify({type:"refresh_token"});this._websocket.send(e)}}_notifyDisconnected(e){this._disconnectedNotified||(this._disconnectedNotified=!0,this._handle_disconnected&&this._handle_disconnected(e))}_handle_close(e){if(!this._closed&&this._websocket&&this._websocket.readyState===WebSocket.CLOSED){if(this._cleanup(),this._disconnectedNotified=!1,this._enable_reconnect){if([1e3,1001].includes(e.code)?console.warn(`Websocket connection closed gracefully by server (code: ${e.code}): ${e.reason} - attempting reconnect`):console.warn("Websocket connection closed unexpectedly (code: %s): %s",e.code,e.reason),this._notifyDisconnected(e.reason),this._reconnecting)return void console.debug("Reconnection already in progress, skipping");this._reconnecting=!0;let t=0;const n=1e3,r=6e4,o=.1,s=async()=>{if(this._closed)return console.info("Connection was closed, stopping reconnection"),void(this._reconnecting=!1);try{console.warn(`Reconnecting to ${this._server_url.split("?")[0]} (attempt #${t})`),await this.open(),await new Promise(e=>setTimeout(e,500)),console.warn(`Successfully reconnected to server ${this._server_url} (services re-registered)`),this._reconnecting=!1}catch(e){if(`${e}`.includes("ConnectionAbortedError:"))return console.warn("Server refused to reconnect:",e),this._closed=!0,this._reconnecting=!1,void this._notifyDisconnected(`Server refused reconnection: ${e}`);if(`${e}`.includes("NotImplementedError:"))return console.error(`${e}\nIt appears that you are trying to connect to a hypha server that is older than 0.20.0, please upgrade the hypha server or use the websocket client in imjoy-rpc(https://www.npmjs.com/package/imjoy-rpc) instead`),this._closed=!0,this._reconnecting=!1,void this._notifyDisconnected(`Server too old: ${e}`);"NetworkError"===e.name||e.message.includes("network")?console.error(`Network error during reconnection: ${e.message}`):"TimeoutError"===e.name||e.message.includes("timeout")?console.error(`Connection timeout during reconnection: ${e.message}`):console.error(`Unexpected error during reconnection: ${e.message}`);const i=Math.min(n*Math.pow(2,t),r),c=(2*Math.random()-1)*o*i,a=Math.max(100,i+c);console.debug(`Waiting ${(a/1e3).toFixed(2)}s before next reconnection attempt`);const l=setTimeout(async()=>(this._reconnect_timeouts.delete(l),this._websocket&&this._websocket.readyState===WebSocket.OPEN?(console.info("Connection restored externally"),void(this._reconnecting=!1)):this._closed?(console.info("Connection was closed, stopping reconnection"),void(this._reconnecting=!1)):(t+=1,void(t<MAX_RETRY?await s():(console.error(`Failed to reconnect after ${MAX_RETRY} attempts, giving up.`),this._closed=!0,this._reconnecting=!1,this._notifyDisconnected("Max reconnection attempts exceeded"))))),a);this._reconnect_timeouts.add(l)}};s()}}else this._cleanup(),this._notifyDisconnected(e.reason)}async emit_message(e){if(this._closed)throw new Error("Connection is closed");this._websocket&&this._websocket.readyState===WebSocket.OPEN||await this.open();try{this._websocket.send(e)}catch(e){throw console.error(`Failed to send data, error: ${e}`),e}}disconnect(e){this._closed=!0,this._reconnecting=!1,this._websocket&&this._websocket.readyState!==WebSocket.CLOSED&&this._websocket.readyState!==WebSocket.CLOSING&&this._websocket.close(1e3,e),this._cleanup(),console.info(`WebSocket connection disconnected (${e})`)}}function normalizeServerUrl(e){if(!e)throw new Error("server_url is required");return e.startsWith("http://")?e=e.replace("http://","ws://").replace(/\/$/,"")+"/ws":e.startsWith("https://")&&(e=e.replace("https://","wss://").replace(/\/$/,"")+"/ws"),e}async function login(e){const t=e.login_service_id||"public/hypha-login",n=e.workspace,r=e.expires_in,o=e.login_timeout||60,s=e.login_callback,i=e.profile,c=e.additional_headers,a=e.transport||"websocket",l=await connectToServer({name:"initial login client",server_url:e.server_url,additional_headers:c,transport:a});try{const e=await l.getService(t);let c;return(0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.assert)(e,`Failed to get the login service: ${t}`),c=n?await e.start({workspace:n,expires_in:r,_rkwargs:!0}):await e.start(),s?await s(c):console.log(`Please open your browser and login at ${c.login_url}`),await e.check(c.key,{timeout:o,profile:i,_rkwargs:!0})}catch(e){throw e}finally{await l.disconnect()}}async function logout(e){const t=e.login_service_id||"public/hypha-login",n=e.logout_callback,r=e.additional_headers,o=e.transport||"websocket",s=await connectToServer({name:"initial logout client",server_url:e.server_url,additional_headers:r,transport:o});try{const e=await s.getService(t);if((0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.assert)(e,`Failed to get the login service: ${t}`),!e.logout)throw new Error("Logout is not supported by this server. Please upgrade the Hypha server to a version that supports logout.");const r=await e.logout({});return n?await n(r):console.log(`Please open your browser to logout at ${r.logout_url}`),r}catch(e){throw e}finally{await s.disconnect()}}async function webrtcGetService(e,t,n){const r=void 0!==(n=n||{}).webrtc?n.webrtc:"auto",o=n.webrtc_config;void 0!==n.webrtc&&delete n.webrtc,void 0!==n.webrtc_config&&delete n.webrtc_config,(0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.assert)([void 0,!0,!1,"auto"].includes(r),"webrtc must be true, false or 'auto'");const s=await e.getService(t,n);if(!0===r||"auto"===r){if(s.id.includes(":")&&s.id.includes("/"))try{const t=s.id.split(":")[0].split("/"),r=t[t.length-1],i=`${t.slice(0,-1).join("/")}/${r}-rtc`,c=await(0,_webrtc_client_js__WEBPACK_IMPORTED_MODULE_3__.getRTCService)(e,i,o),a=await c.getService(s.id.split(":")[1],n);return a._webrtc=!0,a._peer=c,a._service=s,a}catch(e){console.warn("Failed to get webrtc service, using websocket connection",e)}if(!0===r)throw new Error("Failed to get the service via webrtc")}return s}async function connectToServer(e){if("http"===(e.transport||"websocket"))return await(0,_http_client_js__WEBPACK_IMPORTED_MODULE_4__.connectToServerHTTP)(e);e.server&&(e.server_url=e.server_url||e.server.url,e.WebSocketClass=e.WebSocketClass||e.server.WebSocketClass);let t=e.client_id;t||(t=(0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.randId)(),e.client_id=t),0===Object.keys(e).length&&("undefined"!=typeof process&&process.env?(e.server_url=process.env.HYPHA_SERVER_URL,e.token=process.env.HYPHA_TOKEN,e.client_id=process.env.HYPHA_CLIENT_ID,e.workspace=process.env.HYPHA_WORKSPACE):"undefined"!=typeof self&&self.env?(e.server_url=self.env.HYPHA_SERVER_URL,e.token=self.env.HYPHA_TOKEN,e.client_id=self.env.HYPHA_CLIENT_ID,e.workspace=self.env.HYPHA_WORKSPACE):"undefined"!=typeof globalThis&&globalThis.env&&(e.server_url=globalThis.env.HYPHA_SERVER_URL,e.token=globalThis.env.HYPHA_TOKEN,e.client_id=globalThis.env.HYPHA_CLIENT_ID,e.workspace=globalThis.env.HYPHA_WORKSPACE));let n=normalizeServerUrl(e.server_url),r=new WebsocketRPCConnection(n,t,e.workspace,e.token,e.reconnection_token,e.method_timeout||60,e.WebSocketClass,e.token_refresh_interval,e.additional_headers);const o=await r.open();if((0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.assert)(o,"Failed to connect to the server, no connection info obtained. This issue is most likely due to an outdated Hypha server version. Please use `imjoy-rpc` for compatibility, or upgrade the Hypha server to the latest version."),await new Promise(e=>setTimeout(e,100)),!r.manager_id){console.warn("Manager ID not set immediately, waiting...");const e=5e3,t=100,n=Date.now();for(;!r.manager_id&&Date.now()-n<e;)await new Promise(e=>setTimeout(e,t));if(!r.manager_id)throw console.error("Manager ID still not set after waiting"),new Error("Failed to get manager ID from server");console.info(`Manager ID set after waiting: ${r.manager_id}`)}if(e.workspace&&o.workspace!==e.workspace)throw new Error(`Connected to the wrong workspace: ${o.workspace}, expected: ${e.workspace}`);const s=o.workspace,i=new _rpc_js__WEBPACK_IMPORTED_MODULE_0__.RPC(r,{client_id:t,workspace:s,default_context:{connection_type:"websocket"},name:e.name,method_timeout:e.method_timeout,app_id:e.app_id,server_base_url:o.public_base_url,long_message_chunk_size:e.long_message_chunk_size});await i.waitFor("services_registered",e.method_timeout||120);const c=await i.get_manager_service({timeout:e.method_timeout,case_conversion:"camel",kwargs_expansion:e.kwargs_expansion||!1});if(c.rpc=i,o&&(c.config=Object.assign(c.config,o)),c.export=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction)(async function(t){t.id="default",t.name=t.name||e.name||t.id,t.description=t.description||e.description,await i.register_service(t,{overwrite:!0})},{name:"export",description:"Export the api.",parameters:{properties:{api:{description:"The api to export",type:"object"}},required:["api"],type:"object"}}),c.getApp=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction)(async function(e){return e=e||"*",(0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.assert)(!e.includes(":"),"clientId should not contain ':'"),e.includes("/")||(e=o.workspace+"/"+e),(0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.assert)(2===e.split("/").length,"clientId should match pattern workspace/clientId"),await c.getService(`${e}:default`)},{name:"getApp",description:"Get the app.",parameters:{properties:{clientId:{default:"*",description:"The clientId",type:"string"}},type:"object"}}),c.listApps=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction)(async function(e){e=e||s,(0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.assert)(!e.includes(":"),"workspace should not contain ':'"),(0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.assert)(!e.includes("/"),"workspace should not contain '/'");const t={workspace:e,service_id:"default"};return await c.listServices(t)},{name:"listApps",description:"List the apps.",parameters:{properties:{workspace:{default:s,description:"The workspace",type:"string"}},type:"object"}}),c.disconnect=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction)(i.disconnect.bind(i),{name:"disconnect",description:"Disconnect from the server.",parameters:{type:"object",properties:{},required:[]}}),c.registerCodec=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction)(i.register_codec.bind(i),{name:"registerCodec",description:"Register a codec for the webrtc connection",parameters:{type:"object",properties:{codec:{type:"object",description:"Codec to register",properties:{name:{type:"string"},type:{},encoder:{type:"function"},decoder:{type:"function"}}}}}}),c.emit=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction)(i.emit.bind(i),{name:"emit",description:"Emit a message.",parameters:{properties:{data:{description:"The data to emit",type:"object"}},required:["data"],type:"object"}}),c.on=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction)(i.on.bind(i),{name:"on",description:"Register a message handler.",parameters:{properties:{event:{description:"The event to listen to",type:"string"},handler:{description:"The handler function",type:"function"}},required:["event","handler"],type:"object"}}),c.off=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction)(i.off.bind(i),{name:"off",description:"Remove a message handler.",parameters:{properties:{event:{description:"The event to remove",type:"string"},handler:{description:"The handler function",type:"function"}},required:["event","handler"],type:"object"}}),c.once=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction)(i.once.bind(i),{name:"once",description:"Register a one-time message handler.",parameters:{properties:{event:{description:"The event to listen to",type:"string"},handler:{description:"The handler function",type:"function"}},required:["event","handler"],type:"object"}}),c.getServiceSchema=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction)(i.get_service_schema,{name:"getServiceSchema",description:"Get the service schema.",parameters:{properties:{service:{description:"The service to extract schema",type:"object"}},required:["service"],type:"object"}}),c.registerService=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction)(i.register_service.bind(i),{name:"registerService",description:"Register a service.",parameters:{properties:{service:{description:"The service to register",type:"object"},force:{default:!1,description:"Force to register the service",type:"boolean"}},required:["service"],type:"object"}}),c.unregisterService=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction)(i.unregister_service.bind(i),{name:"unregisterService",description:"Unregister a service.",parameters:{properties:{service:{description:"The service id to unregister",type:"string"},notify:{default:!0,description:"Notify the workspace manager",type:"boolean"}},required:["service"],type:"object"}}),r.manager_id&&i.on("force-exit",async e=>{e.from==="*/"+r.manager_id&&(console.log("Disconnecting from server, reason:",e.reason),await i.disconnect())}),e.webrtc){await(0,_webrtc_client_js__WEBPACK_IMPORTED_MODULE_3__.registerRTCService)(c,`${t}-rtc`,e.webrtc_config);const n=Object.assign({},c),r=n.getService.__schema__.description,o=n.getService.__schema__.parameters;c.getService=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction)(webrtcGetService.bind(null,n),{name:"getService",description:r,parameters:o}),c.getRTCService=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction)(_webrtc_client_js__WEBPACK_IMPORTED_MODULE_3__.getRTCService.bind(null,c),{name:"getRTCService",description:"Get the webrtc connection, returns a peer connection.",parameters:{properties:{config:{description:"The config for the webrtc service",type:"object"}},required:["config"],type:"object"}})}else{const e=c.getService;c.getService=(t,n)=>e(t,n=n||{}),c.getService.__schema__=e.__schema__}return c.registerProbes=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction)(async function(e){return e.id="probes",e.name="Probes",e.config={visibility:"public"},e.type="probes",e.description=`Probes Service, visit ${n}/${s}services/probes for the available probes.`,await c.registerService(e,{overwrite:!0})},{name:"registerProbes",description:"Register probes service",parameters:{properties:{probes:{description:"The probes to register, e.g. {'liveness': {'type': 'function', 'description': 'Check the liveness of the service'}}",type:"object"}},required:["probes"],type:"object"}}),c}async function getRemoteService(e,t={}){const{serverUrl:n,workspace:r,clientId:o,serviceId:s,appId:i}=(0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.parseServiceUrl)(e),c=`${r}/${o}:${s}@${i}`;if(t.serverUrl&&t.serverUrl!==n)throw new Error("server_url in config does not match the server_url in the url");t.serverUrl=n;const a=await connectToServer(t);return await a.getService(c)}class LocalWebSocket{constructor(e,t,n){this.url=e,this.onopen=()=>{},this.onmessage=()=>{},this.onclose=()=>{},this.onerror=()=>{},this.client_id=t,this.workspace=n;const r="undefined"!=typeof window?window:self,o="undefined"!=typeof window;if(this.postMessage=e=>{o?window.parent.postMessage(e,"*"):self.postMessage(e)},this.readyState=WebSocket.CONNECTING,this._context=r,this._messageListener=e=>{const{type:t,data:n,to:r}=e.data;if(r===this.client_id)switch(t){case"message":this.readyState===WebSocket.OPEN&&this.onmessage&&this.onmessage({data:n});break;case"connected":this.readyState=WebSocket.OPEN,this.onopen(e);break;case"closed":this.readyState=WebSocket.CLOSED,this.onclose(e)}},r.addEventListener("message",this._messageListener,!1),!this.client_id)throw new Error("client_id is required");if(!this.workspace)throw new Error("workspace is required");this.postMessage({type:"connect",url:this.url,from:this.client_id,workspace:this.workspace})}send(e){this.readyState===WebSocket.OPEN&&this.postMessage({type:"message",data:e,from:this.client_id,workspace:this.workspace})}close(){this.readyState=WebSocket.CLOSING,this.postMessage({type:"close",from:this.client_id,workspace:this.workspace}),this._context&&this._messageListener&&(this._context.removeEventListener("message",this._messageListener,!1),this._messageListener=null),this.onclose()}addEventListener(e,t){"message"===e&&(this.onmessage=t),"open"===e&&(this.onopen=t),"close"===e&&(this.onclose=t),"error"===e&&(this.onerror=t)}}const hyphaWebsocketClient={RPC:_rpc_js__WEBPACK_IMPORTED_MODULE_0__.RPC,API_VERSION:_rpc_js__WEBPACK_IMPORTED_MODULE_0__.API_VERSION,schemaFunction:_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction,loadRequirements:_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.loadRequirements,login:login,logout:logout,connectToServer:connectToServer,connectToServerHTTP:_http_client_js__WEBPACK_IMPORTED_MODULE_4__.connectToServerHTTP,getRemoteService:getRemoteService,getRemoteServiceHTTP:_http_client_js__WEBPACK_IMPORTED_MODULE_4__.getRemoteServiceHTTP,getRTCService:_webrtc_client_js__WEBPACK_IMPORTED_MODULE_3__.getRTCService,registerRTCService:_webrtc_client_js__WEBPACK_IMPORTED_MODULE_3__.registerRTCService,get setupLocalClient(){return setupLocalClient},get LocalWebSocket(){return LocalWebSocket},HTTPStreamingRPCConnection:_http_client_js__WEBPACK_IMPORTED_MODULE_4__.HTTPStreamingRPCConnection,normalizeServerUrlHTTP:_http_client_js__WEBPACK_IMPORTED_MODULE_4__.normalizeServerUrl};function setupLocalClient({enable_execution:enable_execution=!1,on_ready:on_ready=null}){return new Promise((resolve,reject)=>{const context="undefined"!=typeof window?window:self,isWindow="undefined"!=typeof window;context.addEventListener("message",event=>{const{type:type,server_url:server_url,workspace:workspace,client_id:client_id,token:token,method_timeout:method_timeout,name:name,config:config}=event.data;if("initializeHyphaClient"===type){if(!server_url||!workspace||!client_id)return void console.error("server_url, workspace, and client_id are required.");if(!server_url.startsWith("https://local-hypha-server:"))return void console.error("server_url should start with https://local-hypha-server:");class FixedLocalWebSocket extends LocalWebSocket{constructor(e){super(e,client_id,workspace)}}connectToServer({server_url:server_url,workspace:workspace,client_id:client_id,token:token,method_timeout:method_timeout,name:name,WebSocketClass:FixedLocalWebSocket}).then(async server=>{globalThis.api=server;try{if(isWindow&&enable_execution){function e(e){return new Promise((t,n)=>{const r=document.createElement("script");r.innerHTML=e.content,r.lang=e.lang,r.onload=()=>t(),r.onerror=e=>n(e),document.head.appendChild(r)})}if(config.styles&&config.styles.length>0)for(const t of config.styles){const n=document.createElement("style");n.innerHTML=t.content,n.lang=t.lang,document.head.appendChild(n)}if(config.links&&config.links.length>0)for(const r of config.links){const o=document.createElement("a");o.href=r.url,o.innerText=r.text,document.body.appendChild(o)}if(config.windows&&config.windows.length>0)for(const s of config.windows){document.body.innerHTML=s.content;break}if(config.scripts&&config.scripts.length>0)for(const i of config.scripts){if("javascript"!==i.lang)throw new Error("Only javascript scripts are supported");await e(i)}}else if(!isWindow&&enable_execution&&config.scripts&&config.scripts.length>0)for(const script of config.scripts){if("javascript"!==script.lang)throw new Error("Only javascript scripts are supported");eval(script.content)}on_ready&&await on_ready(server,config),resolve(server)}catch(c){reject(c)}})}},!1),isWindow?window.parent.postMessage({type:"hyphaClientReady"},"*"):self.postMessage({type:"hyphaClientReady"})})}var __webpack_exports__API_VERSION=__webpack_exports__.API_VERSION,__webpack_exports__HTTPStreamingRPCConnection=__webpack_exports__.HTTPStreamingRPCConnection,__webpack_exports__LocalWebSocket=__webpack_exports__.LocalWebSocket,__webpack_exports__RPC=__webpack_exports__.RPC,__webpack_exports__connectToServer=__webpack_exports__.connectToServer,__webpack_exports__connectToServerHTTP=__webpack_exports__.connectToServerHTTP,__webpack_exports__getRTCService=__webpack_exports__.getRTCService,__webpack_exports__getRemoteService=__webpack_exports__.getRemoteService,__webpack_exports__getRemoteServiceHTTP=__webpack_exports__.getRemoteServiceHTTP,__webpack_exports__hyphaWebsocketClient=__webpack_exports__.hyphaWebsocketClient,__webpack_exports__loadRequirements=__webpack_exports__.loadRequirements,__webpack_exports__login=__webpack_exports__.login,__webpack_exports__logout=__webpack_exports__.logout,__webpack_exports__normalizeServerUrlHTTP=__webpack_exports__.normalizeServerUrlHTTP,__webpack_exports__registerRTCService=__webpack_exports__.registerRTCService,__webpack_exports__schemaFunction=__webpack_exports__.schemaFunction,__webpack_exports__setupLocalClient=__webpack_exports__.setupLocalClient,hyphaRpcWebsocket=Object.freeze({__proto__:null,API_VERSION:__webpack_exports__API_VERSION,HTTPStreamingRPCConnection:__webpack_exports__HTTPStreamingRPCConnection,LocalWebSocket:__webpack_exports__LocalWebSocket,RPC:__webpack_exports__RPC,connectToServer:__webpack_exports__connectToServer,connectToServerHTTP:__webpack_exports__connectToServerHTTP,getRTCService:__webpack_exports__getRTCService,getRemoteService:__webpack_exports__getRemoteService,getRemoteServiceHTTP:__webpack_exports__getRemoteServiceHTTP,hyphaWebsocketClient:__webpack_exports__hyphaWebsocketClient,loadRequirements:__webpack_exports__loadRequirements,login:__webpack_exports__login,logout:__webpack_exports__logout,normalizeServerUrlHTTP:__webpack_exports__normalizeServerUrlHTTP,registerRTCService:__webpack_exports__registerRTCService,schemaFunction:__webpack_exports__schemaFunction,setupLocalClient:__webpack_exports__setupLocalClient}),hyphaRpc=Object.freeze({__proto__:null,API_VERSION:__webpack_exports__API_VERSION,HTTPStreamingRPCConnection:__webpack_exports__HTTPStreamingRPCConnection,LocalWebSocket:__webpack_exports__LocalWebSocket,RPC:__webpack_exports__RPC,connectToServer:__webpack_exports__connectToServer,connectToServerHTTP:__webpack_exports__connectToServerHTTP,getRTCService:__webpack_exports__getRTCService,getRemoteService:__webpack_exports__getRemoteService,getRemoteServiceHTTP:__webpack_exports__getRemoteServiceHTTP,hyphaWebsocketClient:hyphaRpcWebsocket,loadRequirements:__webpack_exports__loadRequirements,login:__webpack_exports__login,logout:__webpack_exports__logout,normalizeServerUrlHTTP:__webpack_exports__normalizeServerUrlHTTP,registerRTCService:__webpack_exports__registerRTCService,schemaFunction:__webpack_exports__schemaFunction,setupLocalClient:__webpack_exports__setupLocalClient});const overlayStyles="\n :host {\n all: initial;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n }\n\n * {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n }\n\n .debugger-icon {\n width: 40px;\n height: 40px;\n border-radius: 50%;\n background: #4a90d9;\n color: white;\n display: flex;\n align-items: center;\n justify-content: center;\n cursor: pointer;\n box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);\n transition: transform 0.15s, background 0.15s;\n user-select: none;\n font-size: 18px;\n line-height: 1;\n }\n\n .debugger-icon:hover {\n transform: scale(1.1);\n background: #357abd;\n }\n\n .debugger-icon.connected {\n background: #27ae60;\n }\n\n .debugger-icon.error {\n background: #e74c3c;\n }\n\n .debugger-panel {\n display: none;\n width: 380px;\n max-height: 520px;\n background: #1e1e2e;\n color: #cdd6f4;\n border-radius: 8px;\n border: 1px solid #45475a;\n box-shadow: 0 8px 32px rgba(0, 0, 0, 0.5);\n overflow: hidden;\n flex-direction: column;\n position: absolute;\n bottom: 50px;\n right: 0;\n font-size: 13px;\n }\n\n .debugger-panel.open {\n display: flex;\n }\n\n .panel-header {\n background: #313244;\n padding: 8px 12px;\n display: flex;\n align-items: center;\n justify-content: space-between;\n cursor: default;\n border-bottom: 1px solid #45475a;\n font-weight: 600;\n font-size: 12px;\n letter-spacing: 0.3px;\n text-transform: uppercase;\n color: #a6adc8;\n }\n\n .panel-header .title {\n display: flex;\n align-items: center;\n gap: 6px;\n }\n\n .panel-header .close-btn {\n cursor: pointer;\n color: #6c7086;\n font-size: 16px;\n line-height: 1;\n padding: 2px 4px;\n border-radius: 3px;\n }\n\n .panel-header .close-btn:hover {\n color: #cdd6f4;\n background: #45475a;\n }\n\n .status-dot {\n width: 8px;\n height: 8px;\n border-radius: 50%;\n display: inline-block;\n background: #6c7086;\n }\n\n .status-dot.connected {\n background: #a6e3a1;\n }\n\n .status-dot.error {\n background: #f38ba8;\n }\n\n .panel-body {\n padding: 10px 12px;\n overflow-y: auto;\n flex: 1;\n max-height: 440px;\n }\n\n .info-row {\n display: flex;\n justify-content: space-between;\n padding: 4px 0;\n border-bottom: 1px solid #313244;\n font-size: 12px;\n }\n\n .info-row .label {\n color: #6c7086;\n }\n\n .info-row .value {\n color: #cdd6f4;\n text-align: right;\n word-break: break-all;\n max-width: 180px;\n font-family: 'SF Mono', Monaco, Consolas, monospace;\n font-size: 11px;\n }\n\n .instructions-section {\n margin-top: 8px;\n padding-top: 6px;\n border-top: 1px solid #313244;\n }\n\n .instructions-header {\n display: flex;\n align-items: center;\n justify-content: space-between;\n margin-bottom: 4px;\n }\n\n .url-label {\n font-size: 11px;\n color: #6c7086;\n text-transform: uppercase;\n letter-spacing: 0.5px;\n margin-bottom: 3px;\n }\n\n .instructions-block {\n font-family: 'SF Mono', Monaco, Consolas, monospace;\n font-size: 10px;\n color: #a6e3a1;\n background: #11111b;\n border: 1px solid #313244;\n border-radius: 4px;\n padding: 8px;\n white-space: pre-wrap;\n word-break: break-all;\n max-height: 200px;\n overflow-y: auto;\n line-height: 1.5;\n }\n\n .copy-btn {\n background: #45475a;\n color: #cdd6f4;\n border: none;\n border-radius: 3px;\n padding: 2px 8px;\n font-size: 10px;\n cursor: pointer;\n white-space: nowrap;\n flex-shrink: 0;\n }\n\n .copy-btn:hover {\n background: #585b70;\n }\n\n .log-section {\n margin-top: 8px;\n }\n\n .log-title {\n font-size: 11px;\n color: #6c7086;\n text-transform: uppercase;\n letter-spacing: 0.5px;\n margin-bottom: 4px;\n }\n\n .log-entry {\n font-family: 'SF Mono', Monaco, Consolas, monospace;\n font-size: 11px;\n padding: 3px 6px;\n border-radius: 3px;\n background: #313244;\n margin-bottom: 2px;\n color: #a6adc8;\n word-break: break-all;\n }\n\n .log-entry.call {\n border-left: 2px solid #89b4fa;\n }\n\n .log-entry.result {\n border-left: 2px solid #a6e3a1;\n }\n\n .log-entry.error {\n border-left: 2px solid #f38ba8;\n color: #f38ba8;\n }\n";class DebugOverlay{constructor(e){this.isOpen=!1,this.isDragging=!1,this.dragOffset={x:0,y:0},this.maxLogEntries=50,this.host=document.createElement("div"),this.host.id="hypha-debugger-host",Object.assign(this.host.style,{position:"fixed",bottom:"20px",right:"20px",zIndex:"2147483647",display:"flex",flexDirection:"column",alignItems:"flex-end"}),e?.position&&(this.host.style.bottom="auto",this.host.style.right="auto",this.host.style.left=e.position.x+"px",this.host.style.top=e.position.y+"px"),this.shadow=this.host.attachShadow({mode:"open"});const t=document.createElement("style");t.textContent=overlayStyles,this.shadow.appendChild(t);const n=document.createElement("div");n.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.alignItems="flex-end",this.panel=document.createElement("div"),this.panel.className="debugger-panel";const r=document.createElement("div");r.className="panel-header";const o=document.createElement("span");o.className="title",this.statusDot=document.createElement("span"),this.statusDot.className="status-dot",o.appendChild(this.statusDot),o.appendChild(document.createTextNode(" Hypha Debugger"));const s=document.createElement("span");s.className="close-btn",s.textContent="×",s.addEventListener("click",()=>this.toggle()),r.appendChild(o),r.appendChild(s);const i=document.createElement("div");i.className="panel-body",this.infoBody=document.createElement("div"),i.appendChild(this.infoBody);const c=document.createElement("div");c.className="log-section";const a=document.createElement("div");a.className="log-title",a.textContent="Remote Operations",this.logContainer=document.createElement("div"),c.appendChild(a),c.appendChild(this.logContainer),i.appendChild(c),this.panel.appendChild(r),this.panel.appendChild(i),this.icon=document.createElement("div"),this.icon.className="debugger-icon",this.icon.textContent="🐛",this.icon.addEventListener("click",e=>{this.isDragging||this.toggle()}),n.appendChild(this.panel),n.appendChild(this.icon),this.shadow.appendChild(n),document.documentElement.appendChild(this.host),this.setupDrag()}setupDrag(){let e=0,t=0,n=!1;this.icon.addEventListener("mousedown",r=>{e=r.clientX,t=r.clientY,n=!1;const o=this.host.getBoundingClientRect();this.dragOffset.x=r.clientX-o.left,this.dragOffset.y=r.clientY-o.top,r.preventDefault()}),document.addEventListener("mousemove",r=>{if(0===e&&0===t)return;const o=Math.abs(r.clientX-e),s=Math.abs(r.clientY-t);(o>3||s>3)&&(n=!0,this.isDragging=!0,this.host.style.left=r.clientX-this.dragOffset.x+"px",this.host.style.top=r.clientY-this.dragOffset.y+"px",this.host.style.right="auto",this.host.style.bottom="auto")}),document.addEventListener("mouseup",()=>{e=0,t=0,n&&setTimeout(()=>{this.isDragging=!1},50)})}toggle(){this.isOpen=!this.isOpen,this.panel.classList.toggle("open",this.isOpen)}setStatus(e){this.statusDot.className="status-dot",this.icon.className="debugger-icon","connected"===e?(this.statusDot.classList.add("connected"),this.icon.classList.add("connected")):"error"===e&&(this.statusDot.classList.add("error"),this.icon.classList.add("error"))}setInfo(e){this.infoBody.querySelectorAll(".info-row").forEach(e=>e.remove());const t=this.infoBody.firstChild;for(const[n,r]of Object.entries(e)){const e=document.createElement("div");e.className="info-row";const o=document.createElement("span");o.className="label",o.textContent=n;const s=document.createElement("span");s.className="value",s.textContent=r,s.title=r,e.appendChild(o),e.appendChild(s),this.infoBody.insertBefore(e,t)}}setInstructions(e){const t=this.infoBody.querySelector(".instructions-section");t&&t.remove();const n=document.createElement("div");n.className="instructions-section";const r=document.createElement("div");r.className="instructions-header";const o=document.createElement("span");o.className="url-label",o.textContent="Instructions";const s=document.createElement("button");s.className="copy-btn",s.textContent="Copy All",s.addEventListener("click",()=>{navigator.clipboard.writeText(e).then(()=>{s.textContent="Copied!",setTimeout(()=>{s.textContent="Copy All"},1500)})}),r.appendChild(o),r.appendChild(s),n.appendChild(r);const i=document.createElement("pre");i.className="instructions-block",i.textContent=e,n.appendChild(i),this.infoBody.appendChild(n)}addLog(e,t="call"){const n=document.createElement("div");for(n.className=`log-entry ${t}`,n.textContent=e,this.logContainer.appendChild(n);this.logContainer.children.length>this.maxLogEntries;)this.logContainer.removeChild(this.logContainer.firstChild);const r=this.panel.querySelector(".panel-body");r&&(r.scrollTop=r.scrollHeight)}destroy(){this.host.remove()}}function detectFrameworks(){const e=[],t=window;if(t.__REACT_DEVTOOLS_GLOBAL_HOOK__?.renderers?.size>0)e.push("react");else{const t=document.querySelector("#root, #app, [data-reactroot]");if(t){Object.keys(t).some(e=>e.startsWith("__reactFiber$")||e.startsWith("__reactInternalInstance$"))&&e.push("react")}}if(t.__VUE__||t.__VUE_DEVTOOLS_GLOBAL_HOOK__)e.push("vue");else{const t=document.querySelector("[data-v-app], #app");t&&t.__vue_app__&&e.push("vue")}return(t.ng||document.querySelector("[ng-version]"))&&e.push("angular"),document.querySelector("[class*='svelte-']")&&e.push("svelte"),t.__NEXT_DATA__&&e.push("nextjs"),e}function collectPageInfo(){const e=performance.getEntriesByType("navigation")[0];return{url:window.location.href,title:document.title,viewport:{width:window.innerWidth,height:window.innerHeight},document_size:{width:document.documentElement.scrollWidth,height:document.documentElement.scrollHeight},user_agent:navigator.userAgent,timestamp:(new Date).toISOString(),cookies_enabled:navigator.cookieEnabled,language:navigator.language,platform:navigator.platform,online:navigator.onLine,performance:{load_time_ms:e?Math.round(e.loadEventEnd-e.startTime):null,dom_content_loaded_ms:e?Math.round(e.domContentLoadedEventEnd-e.startTime):null},frameworks:detectFrameworks()}}function getPageInfo(e,t,n){const r=collectPageInfo();if(e){const e=window.__HYPHA_DEBUGGER__?.consoleLogs??[],o=t??50;let s=n?e.filter(e=>e.level===n):e;r.console_logs=s.slice(-o)}return r}function installConsoleCapture(e=500){var t;const n=(t=window).__HYPHA_DEBUGGER__??(t.__HYPHA_DEBUGGER__={});if(n.consoleInstalled)return;n.consoleLogs=[],n.consoleInstalled=!0;const r=["log","warn","error","info"];for(const t of r){const r=console[t].bind(console);console[t]=(...o)=>{const s=n.consoleLogs;s.push({level:t,message:o.map(e=>{try{return"string"==typeof e?e:JSON.stringify(e)}catch{return String(e)}}).join(" "),timestamp:(new Date).toISOString()}),s.length>e&&s.splice(0,s.length-e),r(...o)}}}function elementToInfo(e){const t=e.getBoundingClientRect(),n={};for(const t of Array.from(e.attributes))n[t.name]=t.value;return{tag:e.tagName.toLowerCase(),id:e.id,classes:Array.from(e.classList),text:(e.textContent??"").trim().slice(0,500),attributes:n,bounds:{x:Math.round(t.x),y:Math.round(t.y),width:Math.round(t.width),height:Math.round(t.height)},visible:t.width>0&&t.height>0&&"hidden"!==getComputedStyle(e).visibility&&"none"!==getComputedStyle(e).display,children_count:e.children.length}}function queryDom(e,t){t=t??20;const n=document.querySelectorAll(e),r=[];for(let e=0;e<Math.min(n.length,t);e++)r.push(elementToInfo(n[e]));return r}function clickElement(e){const t=document.querySelector(e);if(!t)return{success:!1,message:`No element found for selector: ${e}`};const n=t.getBoundingClientRect();return t.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0,view:window,clientX:n.left+n.width/2,clientY:n.top+n.height/2})),{success:!0,message:`Clicked element: ${e}`}}function fillInput(e,t){const n=document.querySelector(e);if(!n)return{success:!1,message:`No element found for selector: ${e}`};const r=n.tagName.toLowerCase();if("input"===r||"textarea"===r){const o=n,s="textarea"===r?HTMLTextAreaElement.prototype:HTMLInputElement.prototype,i=Object.getOwnPropertyDescriptor(s,"value")?.set;return i?i.call(o,t):o.value=t,o.dispatchEvent(new Event("input",{bubbles:!0})),o.dispatchEvent(new Event("change",{bubbles:!0})),{success:!0,message:`Filled ${e} with value`}}if("select"===r){const r=n,o=Object.getOwnPropertyDescriptor(HTMLSelectElement.prototype,"value")?.set;return o?o.call(r,t):r.value=t,r.dispatchEvent(new Event("change",{bubbles:!0})),{success:!0,message:`Set ${e} to ${t}`}}return{success:!1,message:`Element ${e} is not an input/textarea/select`}}function scrollTo(e){if("string"==typeof e){const t=document.querySelector(e);return t?(t.scrollIntoView({behavior:"smooth",block:"center"}),{success:!0,message:`Scrolled to ${e}`}):{success:!1,message:`No element found for selector: ${e}`}}return window.scrollTo({left:e.x,top:e.y,behavior:"smooth"}),{success:!0,message:`Scrolled to (${e.x}, ${e.y})`}}function getHtml(e,t,n){const r=t??!0,o=n??5e4,s=e?document.querySelector(e):document.documentElement;if(!s)return{error:`No element found for selector: ${e}`};const i=r?s.outerHTML:s.innerHTML,c=i.length>o;return{html:c?i.slice(0,o):i,length:i.length,truncated:c}}function resolveUrl(e,t){if(e.match(/^[a-z]+:\/\//i))return e;if(e.match(/^\/\//))return window.location.protocol+e;if(e.match(/^[a-z]+:/i))return e;const n=document.implementation.createHTMLDocument(),r=n.createElement("base"),o=n.createElement("a");return n.head.appendChild(r),n.body.appendChild(o),t&&(r.href=t),o.href=e,o.href}getPageInfo.__schema__={name:"getPageInfo",description:"Get information about the current web page including URL, title, viewport size, detected frameworks, and performance timing. Optionally include recent console logs.",parameters:{type:"object",properties:{include_logs:{type:"boolean",description:"If true, include recent console output in the response. Default: false."},log_limit:{type:"number",description:"Maximum number of console log entries to include (most recent). Default: 50."},log_level:{type:"string",description:'Filter console logs by level: "log", "warn", "error", "info". Omit for all levels.',enum:["log","warn","error","info"]}}}},queryDom.__schema__={name:"queryDom",description:"Query DOM elements by CSS selector. Returns tag, id, classes, text content, attributes, bounding rect, and visibility for each matching element.",parameters:{type:"object",properties:{selector:{type:"string",description:'CSS selector to query, e.g. "button.primary", "#app > div".'},limit:{type:"number",description:"Maximum number of elements to return. Default: 20."}},required:["selector"]}},clickElement.__schema__={name:"clickElement",description:"Click a DOM element matching the CSS selector.",parameters:{type:"object",properties:{selector:{type:"string",description:"CSS selector of the element to click."}},required:["selector"]}},fillInput.__schema__={name:"fillInput",description:"Set the value of an input, textarea, or select element. Works with React controlled components.",parameters:{type:"object",properties:{selector:{type:"string",description:"CSS selector of the input element."},value:{type:"string",description:"The value to set."}},required:["selector","value"]}},scrollTo.__schema__={name:"scrollTo",description:"Scroll to a DOM element (by CSS selector) or to an absolute position {x, y}.",parameters:{type:"object",properties:{target:{description:"CSS selector string to scroll to an element, or an object {x, y} for absolute scroll position."}},required:["target"]}},getHtml.__schema__={name:"getHtml",description:"Get the HTML content of the page or a specific element. Returns outerHTML by default. Useful for understanding page structure.",parameters:{type:"object",properties:{selector:{type:"string",description:"CSS selector of the element. Omit to get the full page HTML."},outer:{type:"boolean",description:"If true (default), return outerHTML (includes the element itself). If false, return innerHTML (children only)."},max_length:{type:"number",description:"Maximum character length of the returned HTML. Default: 50000. Result will be truncated if longer."}}}};const uuid=(()=>{let e=0;return()=>(e+=1,`u${`0000${(Math.random()*36**4|0).toString(36)}`.slice(-4)}${e}`)})();function toArray(e){const t=[];for(let n=0,r=e.length;n<r;n++)t.push(e[n]);return t}let styleProps=null;function getStyleProperties(e={}){return styleProps||(e.includeStyleProperties?(styleProps=e.includeStyleProperties,styleProps):(styleProps=toArray(window.getComputedStyle(document.documentElement)),styleProps))}function px(e,t){const n=(e.ownerDocument.defaultView||window).getComputedStyle(e).getPropertyValue(t);return n?parseFloat(n.replace("px","")):0}function getNodeWidth(e){const t=px(e,"border-left-width"),n=px(e,"border-right-width");return e.clientWidth+t+n}function getNodeHeight(e){const t=px(e,"border-top-width"),n=px(e,"border-bottom-width");return e.clientHeight+t+n}function getImageSize(e,t={}){return{width:t.width||getNodeWidth(e),height:t.height||getNodeHeight(e)}}function getPixelRatio(){let e,t;try{t=process}catch(e){}const n=t&&t.env?t.env.devicePixelRatio:null;return n&&(e=parseInt(n,10),Number.isNaN(e)&&(e=1)),e||window.devicePixelRatio||1}const canvasDimensionLimit=16384;function checkCanvasDimensions(e){(e.width>canvasDimensionLimit||e.height>canvasDimensionLimit)&&(e.width>canvasDimensionLimit&&e.height>canvasDimensionLimit?e.width>e.height?(e.height*=canvasDimensionLimit/e.width,e.width=canvasDimensionLimit):(e.width*=canvasDimensionLimit/e.height,e.height=canvasDimensionLimit):e.width>canvasDimensionLimit?(e.height*=canvasDimensionLimit/e.width,e.width=canvasDimensionLimit):(e.width*=canvasDimensionLimit/e.height,e.height=canvasDimensionLimit))}function createImage(e){return new Promise((t,n)=>{const r=new Image;r.onload=()=>{r.decode().then(()=>{requestAnimationFrame(()=>t(r))})},r.onerror=n,r.crossOrigin="anonymous",r.decoding="async",r.src=e})}async function svgToDataURL(e){return Promise.resolve().then(()=>(new XMLSerializer).serializeToString(e)).then(encodeURIComponent).then(e=>`data:image/svg+xml;charset=utf-8,${e}`)}async function nodeToDataURL(e,t,n){const r="http://www.w3.org/2000/svg",o=document.createElementNS(r,"svg"),s=document.createElementNS(r,"foreignObject");return o.setAttribute("width",`${t}`),o.setAttribute("height",`${n}`),o.setAttribute("viewBox",`0 0 ${t} ${n}`),s.setAttribute("width","100%"),s.setAttribute("height","100%"),s.setAttribute("x","0"),s.setAttribute("y","0"),s.setAttribute("externalResourcesRequired","true"),o.appendChild(s),s.appendChild(e),svgToDataURL(o)}const isInstanceOfElement=(e,t)=>{if(e instanceof t)return!0;const n=Object.getPrototypeOf(e);return null!==n&&(n.constructor.name===t.name||isInstanceOfElement(n,t))};function formatCSSText(e){const t=e.getPropertyValue("content");return`${e.cssText} content: '${t.replace(/'|"/g,"")}';`}function formatCSSProperties(e,t){return getStyleProperties(t).map(t=>`${t}: ${e.getPropertyValue(t)}${e.getPropertyPriority(t)?" !important":""};`).join(" ")}function getPseudoElementStyle(e,t,n,r){const o=`.${e}:${t}`,s=n.cssText?formatCSSText(n):formatCSSProperties(n,r);return document.createTextNode(`${o}{${s}}`)}function clonePseudoElement(e,t,n,r){const o=window.getComputedStyle(e,n),s=o.getPropertyValue("content");if(""===s||"none"===s)return;const i=uuid();try{t.className=`${t.className} ${i}`}catch(e){return}const c=document.createElement("style");c.appendChild(getPseudoElementStyle(i,n,o,r)),t.appendChild(c)}function clonePseudoElements(e,t,n){clonePseudoElement(e,t,":before",n),clonePseudoElement(e,t,":after",n)}const WOFF="application/font-woff",JPEG="image/jpeg",mimes={woff:WOFF,woff2:WOFF,ttf:"application/font-truetype",eot:"application/vnd.ms-fontobject",png:"image/png",jpg:JPEG,jpeg:JPEG,gif:"image/gif",tiff:"image/tiff",svg:"image/svg+xml",webp:"image/webp"};function getExtension(e){const t=/\.([^./]*?)$/g.exec(e);return t?t[1]:""}function getMimeType(e){const t=getExtension(e).toLowerCase();return mimes[t]||""}function getContentFromDataUrl(e){return e.split(/,/)[1]}function isDataUrl(e){return-1!==e.search(/^(data:)/)}function makeDataUrl(e,t){return`data:${t};base64,${e}`}async function fetchAsDataURL(e,t,n){const r=await fetch(e,t);if(404===r.status)throw new Error(`Resource "${r.url}" not found`);const o=await r.blob();return new Promise((e,t)=>{const s=new FileReader;s.onerror=t,s.onloadend=()=>{try{e(n({res:r,result:s.result}))}catch(e){t(e)}},s.readAsDataURL(o)})}const cache={};function getCacheKey(e,t,n){let r=e.replace(/\?.*/,"");return n&&(r=e),/ttf|otf|eot|woff2?/i.test(r)&&(r=r.replace(/.*\//,"")),t?`[${t}]${r}`:r}async function resourceToDataURL(e,t,n){const r=getCacheKey(e,t,n.includeQueryParams);if(null!=cache[r])return cache[r];let o;n.cacheBust&&(e+=(/\?/.test(e)?"&":"?")+(new Date).getTime());try{o=makeDataUrl(await fetchAsDataURL(e,n.fetchRequestInit,({res:e,result:n})=>(t||(t=e.headers.get("Content-Type")||""),getContentFromDataUrl(n))),t)}catch(t){o=n.imagePlaceholder||"";let r=`Failed to fetch resource: ${e}`;t&&(r="string"==typeof t?t:t.message),r&&console.warn(r)}return cache[r]=o,o}async function cloneCanvasElement(e){const t=e.toDataURL();return"data:,"===t?e.cloneNode(!1):createImage(t)}async function cloneVideoElement(e,t){if(e.currentSrc){const t=document.createElement("canvas"),n=t.getContext("2d");t.width=e.clientWidth,t.height=e.clientHeight,null==n||n.drawImage(e,0,0,t.width,t.height);return createImage(t.toDataURL())}const n=e.poster,r=getMimeType(n);return createImage(await resourceToDataURL(n,r,t))}async function cloneIFrameElement(e,t){var n;try{if(null===(n=null==e?void 0:e.contentDocument)||void 0===n?void 0:n.body)return await cloneNode(e.contentDocument.body,t,!0)}catch(e){}return e.cloneNode(!1)}async function cloneSingleNode(e,t){return isInstanceOfElement(e,HTMLCanvasElement)?cloneCanvasElement(e):isInstanceOfElement(e,HTMLVideoElement)?cloneVideoElement(e,t):isInstanceOfElement(e,HTMLIFrameElement)?cloneIFrameElement(e,t):e.cloneNode(isSVGElement(e))}const isSlotElement=e=>null!=e.tagName&&"SLOT"===e.tagName.toUpperCase(),isSVGElement=e=>null!=e.tagName&&"SVG"===e.tagName.toUpperCase();async function cloneChildren(e,t,n){var r,o;if(isSVGElement(t))return t;let s=[];return s=isSlotElement(e)&&e.assignedNodes?toArray(e.assignedNodes()):isInstanceOfElement(e,HTMLIFrameElement)&&(null===(r=e.contentDocument)||void 0===r?void 0:r.body)?toArray(e.contentDocument.body.childNodes):toArray((null!==(o=e.shadowRoot)&&void 0!==o?o:e).childNodes),0===s.length||isInstanceOfElement(e,HTMLVideoElement)||await s.reduce((e,r)=>e.then(()=>cloneNode(r,n)).then(e=>{e&&t.appendChild(e)}),Promise.resolve()),t}function cloneCSSStyle(e,t,n){const r=t.style;if(!r)return;const o=window.getComputedStyle(e);o.cssText?(r.cssText=o.cssText,r.transformOrigin=o.transformOrigin):getStyleProperties(n).forEach(n=>{let s=o.getPropertyValue(n);if("font-size"===n&&s.endsWith("px")){const e=Math.floor(parseFloat(s.substring(0,s.length-2)))-.1;s=`${e}px`}isInstanceOfElement(e,HTMLIFrameElement)&&"display"===n&&"inline"===s&&(s="block"),"d"===n&&t.getAttribute("d")&&(s=`path(${t.getAttribute("d")})`),r.setProperty(n,s,o.getPropertyPriority(n))})}function cloneInputValue(e,t){isInstanceOfElement(e,HTMLTextAreaElement)&&(t.innerHTML=e.value),isInstanceOfElement(e,HTMLInputElement)&&t.setAttribute("value",e.value)}function cloneSelectValue(e,t){if(isInstanceOfElement(e,HTMLSelectElement)){const n=t,r=Array.from(n.children).find(t=>e.value===t.getAttribute("value"));r&&r.setAttribute("selected","")}}function decorate(e,t,n){return isInstanceOfElement(t,Element)&&(cloneCSSStyle(e,t,n),clonePseudoElements(e,t,n),cloneInputValue(e,t),cloneSelectValue(e,t)),t}async function ensureSVGSymbols(e,t){const n=e.querySelectorAll?e.querySelectorAll("use"):[];if(0===n.length)return e;const r={};for(let o=0;o<n.length;o++){const s=n[o].getAttribute("xlink:href");if(s){const n=e.querySelector(s),o=document.querySelector(s);n||!o||r[s]||(r[s]=await cloneNode(o,t,!0))}}const o=Object.values(r);if(o.length){const t="http://www.w3.org/1999/xhtml",n=document.createElementNS(t,"svg");n.setAttribute("xmlns",t),n.style.position="absolute",n.style.width="0",n.style.height="0",n.style.overflow="hidden",n.style.display="none";const r=document.createElementNS(t,"defs");n.appendChild(r);for(let e=0;e<o.length;e++)r.appendChild(o[e]);e.appendChild(n)}return e}async function cloneNode(e,t,n){return n||!t.filter||t.filter(e)?Promise.resolve(e).then(e=>cloneSingleNode(e,t)).then(n=>cloneChildren(e,n,t)).then(n=>decorate(e,n,t)).then(e=>ensureSVGSymbols(e,t)):null}const URL_REGEX=/url\((['"]?)([^'"]+?)\1\)/g,URL_WITH_FORMAT_REGEX=/url\([^)]+\)\s*format\((["']?)([^"']+)\1\)/g,FONT_SRC_REGEX=/src:\s*(?:url\([^)]+\)\s*format\([^)]+\)[,;]\s*)+/g;function toRegex(e){const t=e.replace(/([.*+?^${}()|\[\]\/\\])/g,"\\$1");return new RegExp(`(url\\(['"]?)(${t})(['"]?\\))`,"g")}function parseURLs(e){const t=[];return e.replace(URL_REGEX,(e,n,r)=>(t.push(r),e)),t.filter(e=>!isDataUrl(e))}async function embed(e,t,n,r,o){try{const s=n?resolveUrl(t,n):t,i=getMimeType(t);let c;return o||(c=await resourceToDataURL(s,i,r)),e.replace(toRegex(t),`$1${c}$3`)}catch(e){}return e}function filterPreferredFontFormat(e,{preferredFontFormat:t}){return t?e.replace(FONT_SRC_REGEX,e=>{for(;;){const[n,,r]=URL_WITH_FORMAT_REGEX.exec(e)||[];if(!r)return"";if(r===t)return`src: ${n};`}}):e}function shouldEmbed(e){return-1!==e.search(URL_REGEX)}async function embedResources(e,t,n){if(!shouldEmbed(e))return e;const r=filterPreferredFontFormat(e,n);return parseURLs(r).reduce((e,r)=>e.then(e=>embed(e,r,t,n)),Promise.resolve(r))}async function embedProp(e,t,n){var r;const o=null===(r=t.style)||void 0===r?void 0:r.getPropertyValue(e);if(o){const r=await embedResources(o,null,n);return t.style.setProperty(e,r,t.style.getPropertyPriority(e)),!0}return!1}async function embedBackground(e,t){await embedProp("background",e,t)||await embedProp("background-image",e,t),await embedProp("mask",e,t)||await embedProp("-webkit-mask",e,t)||await embedProp("mask-image",e,t)||await embedProp("-webkit-mask-image",e,t)}async function embedImageNode(e,t){const n=isInstanceOfElement(e,HTMLImageElement);if((!n||isDataUrl(e.src))&&(!isInstanceOfElement(e,SVGImageElement)||isDataUrl(e.href.baseVal)))return;const r=n?e.src:e.href.baseVal,o=await resourceToDataURL(r,getMimeType(r),t);await new Promise((r,s)=>{e.onload=r,e.onerror=t.onImageErrorHandler?(...e)=>{try{r(t.onImageErrorHandler(...e))}catch(e){s(e)}}:s;const i=e;i.decode&&(i.decode=r),"lazy"===i.loading&&(i.loading="eager"),n?(e.srcset="",e.src=o):e.href.baseVal=o})}async function embedChildren(e,t){const n=toArray(e.childNodes).map(e=>embedImages(e,t));await Promise.all(n).then(()=>e)}async function embedImages(e,t){isInstanceOfElement(e,Element)&&(await embedBackground(e,t),await embedImageNode(e,t),await embedChildren(e,t))}function applyStyle(e,t){const{style:n}=e;t.backgroundColor&&(n.backgroundColor=t.backgroundColor),t.width&&(n.width=`${t.width}px`),t.height&&(n.height=`${t.height}px`);const r=t.style;return null!=r&&Object.keys(r).forEach(e=>{n[e]=r[e]}),e}const cssFetchCache={};async function fetchCSS(e){let t=cssFetchCache[e];if(null!=t)return t;const n=await fetch(e);return t={url:e,cssText:await n.text()},cssFetchCache[e]=t,t}async function embedFonts(e,t){let n=e.cssText;const r=/url\(["']?([^"')]+)["']?\)/g,o=(n.match(/url\([^)]+\)/g)||[]).map(async o=>{let s=o.replace(r,"$1");return s.startsWith("https://")||(s=new URL(s,e.url).href),fetchAsDataURL(s,t.fetchRequestInit,({result:e})=>(n=n.replace(o,`url(${e})`),[o,e]))});return Promise.all(o).then(()=>n)}function parseCSS(e){if(null==e)return[];const t=[];let n=e.replace(/(\/\*[\s\S]*?\*\/)/gi,"");const r=new RegExp("((@.*?keyframes [\\s\\S]*?){([\\s\\S]*?}\\s*?)})","gi");for(;;){const e=r.exec(n);if(null===e)break;t.push(e[0])}n=n.replace(r,"");const o=/@import[\s\S]*?url\([^)]*\)[\s\S]*?;/gi,s=new RegExp("((\\s*?(?:\\/\\*[\\s\\S]*?\\*\\/)?\\s*?@media[\\s\\S]*?){([\\s\\S]*?)}\\s*?})|(([\\s\\S]*?){([\\s\\S]*?)})","gi");for(;;){let e=o.exec(n);if(null===e){if(e=s.exec(n),null===e)break;o.lastIndex=s.lastIndex}else s.lastIndex=o.lastIndex;t.push(e[0])}return t}async function getCSSRules(e,t){const n=[],r=[];return e.forEach(n=>{if("cssRules"in n)try{toArray(n.cssRules||[]).forEach((e,o)=>{if(e.type===CSSRule.IMPORT_RULE){let s=o+1;const i=fetchCSS(e.href).then(e=>embedFonts(e,t)).then(e=>parseCSS(e).forEach(e=>{try{n.insertRule(e,e.startsWith("@import")?s+=1:n.cssRules.length)}catch(t){console.error("Error inserting rule from remote css",{rule:e,error:t})}})).catch(e=>{console.error("Error loading remote css",e.toString())});r.push(i)}})}catch(o){const s=e.find(e=>null==e.href)||document.styleSheets[0];null!=n.href&&r.push(fetchCSS(n.href).then(e=>embedFonts(e,t)).then(e=>parseCSS(e).forEach(e=>{s.insertRule(e,s.cssRules.length)})).catch(e=>{console.error("Error loading remote stylesheet",e)})),console.error("Error inlining remote css file",o)}}),Promise.all(r).then(()=>(e.forEach(e=>{if("cssRules"in e)try{toArray(e.cssRules||[]).forEach(e=>{n.push(e)})}catch(t){console.error(`Error while reading CSS rules from ${e.href}`,t)}}),n))}function getWebFontRules(e){return e.filter(e=>e.type===CSSRule.FONT_FACE_RULE).filter(e=>shouldEmbed(e.style.getPropertyValue("src")))}async function parseWebFontRules(e,t){if(null==e.ownerDocument)throw new Error("Provided element is not within a Document");const n=toArray(e.ownerDocument.styleSheets);return getWebFontRules(await getCSSRules(n,t))}function normalizeFontFamily(e){return e.trim().replace(/["']/g,"")}function getUsedFonts(e){const t=new Set;return function e(n){(n.style.fontFamily||getComputedStyle(n).fontFamily).split(",").forEach(e=>{t.add(normalizeFontFamily(e))}),Array.from(n.children).forEach(t=>{t instanceof HTMLElement&&e(t)})}(e),t}async function getWebFontCSS(e,t){const n=await parseWebFontRules(e,t),r=getUsedFonts(e);return(await Promise.all(n.filter(e=>r.has(normalizeFontFamily(e.style.fontFamily))).map(e=>{const n=e.parentStyleSheet?e.parentStyleSheet.href:null;return embedResources(e.cssText,n,t)}))).join("\n")}async function embedWebFonts(e,t){const n=null!=t.fontEmbedCSS?t.fontEmbedCSS:t.skipFonts?null:await getWebFontCSS(e,t);if(n){const t=document.createElement("style"),r=document.createTextNode(n);t.appendChild(r),e.firstChild?e.insertBefore(t,e.firstChild):e.appendChild(t)}}async function toSvg(e,t={}){const{width:n,height:r}=getImageSize(e,t),o=await cloneNode(e,t,!0);await embedWebFonts(o,t),await embedImages(o,t),applyStyle(o,t);return await nodeToDataURL(o,n,r)}async function toCanvas(e,t={}){const{width:n,height:r}=getImageSize(e,t),o=await toSvg(e,t),s=await createImage(o),i=document.createElement("canvas"),c=i.getContext("2d"),a=t.pixelRatio||getPixelRatio(),l=t.canvasWidth||n,_=t.canvasHeight||r;return i.width=l*a,i.height=_*a,t.skipAutoScale||checkCanvasDimensions(i),i.style.width=`${l}`,i.style.height=`${_}`,t.backgroundColor&&(c.fillStyle=t.backgroundColor,c.fillRect(0,0,i.width,i.height)),c.drawImage(s,0,0,i.width,i.height),i}async function toPng(e,t={}){return(await toCanvas(e,t)).toDataURL()}async function toJpeg(e,t={}){return(await toCanvas(e,t)).toDataURL("image/jpeg",t.quality||1)}async function takeScreenshot(e,t,n,r,o,s){const i=t??"png",c=n??.92,a=r??1,l=e?document.querySelector(e):document.body;if(!l)return{error:`No element found for selector: ${e}`};try{const e=l,t={quality:c,pixelRatio:a,cacheBust:!0,skipAutoScale:!0,filter:e=>"hypha-debugger-host"!==e.id};let n;n="jpeg"===i?await toJpeg(e,t):await toPng(e,t);const r=e.getBoundingClientRect();let _=Math.round(r.width*a),d=Math.round(r.height*a);if(o&&_>o){const e=o/_;_=o,d=Math.round(d*e)}if(s&&d>s){const e=s/d;d=s,_=Math.round(_*e)}return{data:n,format:i,width:_,height:d}}catch(e){return{error:`Screenshot failed: ${e.message??e}`}}}async function executeScript(e,t){const n=t??1e4;try{const t=await Promise.race([new Function("return (async () => {"+e+"})()")(),new Promise((e,t)=>setTimeout(()=>t(new Error("Execution timed out")),n))]);let r,o=typeof t;try{void 0===t?(r=null,o="undefined"):t instanceof HTMLElement?(r={tag:t.tagName.toLowerCase(),id:t.id,text:(t.textContent??"").trim().slice(0,500)},o="HTMLElement"):t instanceof NodeList||t instanceof HTMLCollection?(r=Array.from(t).map(e=>({tag:e.tagName?.toLowerCase(),id:e.id,text:(e.textContent??"").trim().slice(0,200)})),o="NodeList"):r=JSON.parse(JSON.stringify(t))}catch{r=String(t),o="string (serialized)"}return{result:r,type:o}}catch(e){return{error:`Execution error: ${e.message??e}`}}}function navigate(e){try{return window.location.href=e,{success:!0,message:`Navigating to ${e}`}}catch(e){return{success:!1,message:`Navigation failed: ${e.message??e}`}}}function getFiberFromDOM(e){const t=Object.keys(e).find(e=>e.startsWith("__reactFiber$")||e.startsWith("__reactInternalInstance$"));return t?e[t]:null}function getComponentName(e){const{type:t}=e;if(!t)return"(unknown)";if("string"==typeof t)return t;if("function"==typeof t)return t.displayName||t.name||"Anonymous";if("object"==typeof t){if(t.displayName)return t.displayName;if(t.render)return t.render.displayName||t.render.name||"ForwardRef";if(t.type)return getComponentName({type:t.type});if("Symbol(react.memo)"===t.$$typeof?.toString())return`Memo(${getComponentName({type:t.type})})`}return"(unknown)"}function getFiberType(e){return 0===e.tag||11===e.tag||14===e.tag||15===e.tag?"function":1===e.tag?"class":5===e.tag||6===e.tag?"host":"other"}function safeSerialize(e,t=0,n=2){if(t>n)return"[max depth]";if(null==e)return e;if("function"==typeof e)return`[Function: ${e.name||"anonymous"}]`;if("object"!=typeof e)return e;if(e instanceof HTMLElement)return`[${e.tagName.toLowerCase()}#${e.id}]`;if(Array.isArray(e))return e.slice(0,10).map(e=>safeSerialize(e,t+1,n));const r={},o=Object.keys(e).slice(0,20);for(const s of o)if(!s.startsWith("_")&&!s.startsWith("$$"))try{r[s]=safeSerialize(e[s],t+1,n)}catch{r[s]="[unserializable]"}return r}function extractState(e){if(1===e.tag&&e.stateNode)return safeSerialize(e.stateNode.state);if(0===e.tag||11===e.tag||15===e.tag){const t=[];let n=e.memoizedState,r=0;for(;n&&r<20;)null!==n.queue&&void 0!==n.queue&&t.push(safeSerialize(n.memoizedState)),n=n.next,r++;return t.length>0?t:null}return null}function fiberToInfo(e,t,n){const r=getFiberType(e),o="function"===r||"class"===r,s={name:getComponentName(e),type:r,props:o?safeSerialize(e.memoizedProps):{},state:o?extractState(e):null,key:e.key,children:[]};if(t<n){let r=e.child;for(;r;){const e=fiberToInfo(r,t+1,n);e&&("host"!==e.type||e.children.length>0)&&s.children.push(e),r=r.sibling}}return s}function getReactTree(e,t){e=e??"#root";const n=t??5,r=document.querySelector(e);if(!r)return{error:`No element found for selector: ${e}`};const o=getFiberFromDOM(r);if(!o)return{error:`No React fiber found on element "${e}". Is this a React app?`};let s=o;for(;s&&3===s.tag;)s=s.child;if(!s)return{error:"Could not find root React component fiber."};const i=fiberToInfo(s,0,n);return i||{error:"Could not build React component tree."}}function generateSkillMd(e,t){const n=["---","name: web-debugger","description: Remote web page debugger. Inspect DOM, take screenshots, execute JavaScript, fill forms, click elements, and navigate pages — all via HTTP API calls.","compatibility: Requires network access to the Hypha server. Works with any HTTP client (curl, fetch, Python requests).","metadata:",' version: "0.1"',' author: "hypha-debugger"',"---"].join("\n"),r=["","# Web Debugger Skill","","This skill allows you to remotely debug and interact with a web page through a set of HTTP API endpoints.","","## How to call functions","","All functions are available as HTTP endpoints. Use the service URL provided in the instructions.","","**GET request** (for functions with no required parameters):","```","curl '{SERVICE_URL}/get_page_info?_mode=last' -H 'Authorization: Bearer {TOKEN}'","```","","**POST request** (for functions with parameters):","```","curl -X POST '{SERVICE_URL}/query_dom?_mode=last' \\"," -H 'Authorization: Bearer {TOKEN}' \\"," -H 'Content-Type: application/json' \\",' -d \'{"selector": "button"}\'',"```","","Replace `{SERVICE_URL}` and `{TOKEN}` with the actual values from the instruction block.","","**Note:** The `_mode=last` query parameter ensures the latest debugger instance is used,","even if multiple sessions have connected to the same workspace.",""].join("\n"),o=["## Available Functions",""],s=Object.entries(e).filter(([e,t])=>t?.__schema__&&"get_skill_md"!==e);for(const[e,t]of s){const n=t.__schema__;o.push(`### \`${e}\``),o.push(""),o.push(n.description),o.push("");const r=n.parameters?.properties,s=n.parameters?.required??[];if(r&&Object.keys(r).length>0){o.push("**Parameters:**"),o.push(""),o.push("| Parameter | Type | Required | Description |"),o.push("|-----------|------|----------|-------------|");for(const[e,t]of Object.entries(r)){const n=s.includes(e);let r=t.type??"any";t.enum&&(r=t.enum.map(e=>`"${e}"`).join(" | ")),t.items&&(r=`${t.items.type}[]`),o.push(`| \`${e}\` | ${r} | ${n?"Yes":"No"} | ${t.description??""} |`)}if(o.push(""),s.length>0){const t={};for(const e of s){const n=r[e];t[e]="string"===n?.type?`<${e}>`:"number"===n?.type?"0":`<${e}>`}o.push("**Example:**"),o.push("```bash"),o.push(`curl -X POST '{SERVICE_URL}/${e}?_mode=last' \\`),o.push(" -H 'Authorization: Bearer {TOKEN}' \\"),o.push(" -H 'Content-Type: application/json' \\"),o.push(` -d '${JSON.stringify(t)}'`),o.push("```")}else o.push("**Example:**"),o.push("```bash"),o.push(`curl '{SERVICE_URL}/${e}?_mode=last' -H 'Authorization: Bearer {TOKEN}'`),o.push("```")}else o.push("**Parameters:** None"),o.push(""),o.push("**Example:**"),o.push("```bash"),o.push(`curl '{SERVICE_URL}/${e}?_mode=last' -H 'Authorization: Bearer {TOKEN}'`),o.push("```");o.push("")}const i=["## Tips","","- **Start with `get_page_info`** to understand the page structure, URL, title, and viewport.","- **Use `query_dom`** with CSS selectors to find elements before clicking or filling them.","- **Use `take_screenshot`** to visually verify the page state.","- **Use `execute_script`** for anything not covered by the built-in functions — it runs arbitrary JavaScript.","- **Use `get_page_info` with `include_logs=true`** to check for JavaScript errors or debug output.","- **Use `get_react_tree`** if the page uses React — it gives you component names, props, and state.","- All POST endpoints accept JSON body with the parameter names as keys.","- All endpoints require the `Authorization: Bearer {TOKEN}` header.",""].join("\n");return[n,r,o.join("\n"),i].join("\n")}takeScreenshot.__schema__={name:"takeScreenshot",description:"Capture a screenshot of the entire page or a specific element. Returns a base64-encoded data URL.",parameters:{type:"object",properties:{selector:{type:"string",description:"CSS selector of the element to capture. Omit to capture the entire page body."},format:{type:"string",enum:["png","jpeg"],description:'Image format. Default: "png".'},quality:{type:"number",description:"Image quality (0-1) for JPEG. Default: 0.92."},scale:{type:"number",description:"Pixel ratio / scale factor. Default: 1. Use 2 for retina."},max_width:{type:"number",description:"Maximum width in pixels. Image will be scaled down if larger."},max_height:{type:"number",description:"Maximum height in pixels. Image will be scaled down if larger."}}}},executeScript.__schema__={name:"executeScript",description:"Execute arbitrary JavaScript code in the page context. Supports async/await. Returns the result of the last expression.",parameters:{type:"object",properties:{code:{type:"string",description:'JavaScript code to execute. The result of the last expression is returned. Example: "return document.title"'},timeout_ms:{type:"number",description:"Maximum execution time in milliseconds. Default: 10000."}},required:["code"]}},navigate.__schema__={name:"navigate",description:"Navigate the browser to a new URL.",parameters:{type:"object",properties:{url:{type:"string",description:"The URL to navigate to."}},required:["url"]}},getReactTree.__schema__={name:"getReactTree",description:"Inspect the React component tree starting from a DOM element. Returns component names, props, state (including hooks), and children hierarchy.",parameters:{type:"object",properties:{selector:{type:"string",description:'CSS selector of the React root element. Default: "#root".'},max_depth:{type:"number",description:"Maximum depth to traverse the component tree. Default: 5."}}}};class HyphaDebugger{constructor(e){this.overlay=null,this.server=null,this.serviceInfo=null,this.config={server_url:e.server_url,workspace:e.workspace??"",token:e.token??"",service_id:e.service_id??"web-debugger",service_name:e.service_name??"Web Debugger",show_ui:e.show_ui??!0,visibility:e.visibility??"public"}}async start(){installConsoleCapture();const e=window;if(e.__HYPHA_DEBUGGER__?.instance)return console.warn("[hypha-debugger] Already running, returning existing session."),e.__HYPHA_DEBUGGER__.session;this.config.show_ui&&(this.overlay=new DebugOverlay,this.overlay.setStatus("disconnected"),this.overlay.setInfo({Status:"Connecting..."}));try{const t=this.getConnectToServer(),n={server_url:this.config.server_url};this.config.workspace&&(n.workspace=this.config.workspace),this.config.token&&(n.token=this.config.token),this.server=await t(n),this.serviceInfo=await this.server.registerService(this.buildServiceDefinition());const r=await this.updateSession();return this.overlay&&this.overlay.addLog("Service registered","result"),e.__HYPHA_DEBUGGER__=e.__HYPHA_DEBUGGER__??{},e.__HYPHA_DEBUGGER__.instance=this,r}catch(e){throw console.error("[hypha-debugger] Failed to start:",e),this.overlay&&(this.overlay.setStatus("error"),this.overlay.setInfo({Status:"Error",Error:e.message??String(e)})),e}}async destroy(){try{this.serviceInfo&&this.server&&await this.server.unregisterService(this.serviceInfo.id)}catch{}this.overlay?.destroy(),this.overlay=null;const e=window;e.__HYPHA_DEBUGGER__&&(delete e.__HYPHA_DEBUGGER__.instance,delete e.__HYPHA_DEBUGGER__.session)}async updateSession(e){const t=this.serviceInfo?.id??this.config.service_id,n=await this.server.generateToken(),r=this.buildServiceUrl(t),o=this.server.config?.workspace??"";this.overlay&&(this.overlay.setStatus("connected"),this.overlay.setInfo({Status:"Connected",Server:this.config.server_url,...e}),this.overlay.setInstructions(this.buildInstructionBlock(r,n))),console.log(`[hypha-debugger] Service URL: ${r}`),console.log(`[hypha-debugger] Token: ${n}`),console.log(`[hypha-debugger] Test:\n curl '${r}/get_page_info?_mode=last' -H 'Authorization: Bearer ${n}'`);const s={service_id:t,workspace:o,server:this.server,service_url:r,token:n,destroy:()=>this.destroy()},i=window;return i.__HYPHA_DEBUGGER__=i.__HYPHA_DEBUGGER__??{},i.__HYPHA_DEBUGGER__.session=s,s}buildServiceUrl(e){const t=this.config.server_url.replace(/\/+$/,""),n=e.indexOf("/");if(-1!==n){const r=e.substring(0,n),o=e.substring(n+1),s=o.indexOf(":");return`${t}/${r}/services/${-1!==s?o.substring(s+1):o}`}return`${t}/services/${e}`}getHyphaModule(){if(__webpack_exports__connectToServer)return hyphaRpc;if(__webpack_exports__connectToServer)return hyphaRpcWebsocket;const e=window;if(e.hyphaWebsocketClient?.connectToServer)return e.hyphaWebsocketClient;throw new Error('hypha-rpc not found. Install it via npm or load it via: <script src="https://cdn.jsdelivr.net/npm/hypha-rpc@0.20.97/dist/hypha-rpc-websocket.min.js"><\/script>')}getConnectToServer(){return this.getHyphaModule().connectToServer}buildServiceDefinition(){return{id:this.config.service_id,name:this.config.service_name,type:"debugger",description:"Remote web page debugger. Allows inspecting DOM, taking screenshots, executing JavaScript, and interacting with the page.",config:{visibility:this.config.visibility},get_page_info:this.wrapFn(getPageInfo,"get_page_info"),get_html:this.wrapFn(getHtml,"get_html"),query_dom:this.wrapFn(queryDom,"query_dom"),click_element:this.wrapFn(clickElement,"click_element"),fill_input:this.wrapFn(fillInput,"fill_input"),scroll_to:this.wrapFn(scrollTo,"scroll_to"),take_screenshot:this.wrapFn(takeScreenshot,"take_screenshot"),execute_script:this.wrapFn(executeScript,"execute_script"),navigate:this.wrapFn(navigate,"navigate"),get_react_tree:this.wrapFn(getReactTree,"get_react_tree"),get_skill_md:this.wrapFn(this.createGetSkillMd(),"get_skill_md")}}createGetSkillMd(){const e=()=>{const e={},t={get_page_info:getPageInfo,get_html:getHtml,query_dom:queryDom,click_element:clickElement,fill_input:fillInput,scroll_to:scrollTo,take_screenshot:takeScreenshot,execute_script:executeScript,navigate:navigate,get_react_tree:getReactTree};for(const[n,r]of Object.entries(t))r.__schema__&&(e[n]=r);return!this.serviceInfo||this.buildServiceUrl(this.serviceInfo.id??this.config.service_id),generateSkillMd(e)};return e.__schema__={name:"getSkillMd",description:"Get the SKILL.md document describing all available debugger functions, their parameters, and usage examples. Follows the agentskills.io specification.",parameters:{type:"object",properties:{}}},e}buildInstructionBlock(e,t){return[`SERVICE_URL="${e}"`,`TOKEN="${t}"`,"","# Quick test:",'curl "$SERVICE_URL/get_page_info?_mode=last" -H "Authorization: Bearer $TOKEN"',"","# Full API docs:",'curl "$SERVICE_URL/get_skill_md?_mode=last" -H "Authorization: Bearer $TOKEN"'].join("\n")}wrapFn(e,t){const n=async(...n)=>{if(1===n.length&&n[0]&&"object"==typeof n[0]&&!Array.isArray(n[0])&&e.__schema__?.parameters?.properties){const t=n[0],r=e.__schema__.parameters.properties,o=Object.keys(r);if(o.some(e=>e in t))for(n=o.map(e=>t[e]);n.length>0&&void 0===n[n.length-1];)n.pop()}this.overlay?.addLog(`${t}(${this.summarizeArgs(n)})`,"call");try{const r=await e(...n);return r&&"object"==typeof r&&"error"in r?this.overlay?.addLog(`${t}: ${r.error}`,"error"):this.overlay?.addLog(`${t} -> OK`,"result"),r}catch(e){throw this.overlay?.addLog(`${t}: ${e.message}`,"error"),e}};return e.__schema__&&(n.__schema__=e.__schema__),n}summarizeArgs(e){return 0===e.length?"":e.map(e=>"string"==typeof e?e.length>40?e.slice(0,40)+"...":e:"object"==typeof e&&null!==e?"{...}":String(e)).join(", ")}}async function startDebugger(e){return new HyphaDebugger(e).start()}function autoStart(){if("undefined"==typeof window||"undefined"==typeof document)return;const e=document.querySelectorAll("script[src]");let t=null;for(const n of Array.from(e))if(n.src&&n.src.includes("hypha-debugger")){t=n;break}if(t?.hasAttribute("data-manual"))return;if(window.__HYPHA_DEBUGGER__?.instance)return;const n={server_url:t?.getAttribute("data-server-url")??"https://hypha.aicell.io"};t?.getAttribute("data-workspace")&&(n.workspace=t.getAttribute("data-workspace")),t?.getAttribute("data-token")&&(n.token=t.getAttribute("data-token")),t?.getAttribute("data-service-id")&&(n.service_id=t.getAttribute("data-service-id")),t?.hasAttribute("data-no-ui")&&(n.show_ui=!1),startDebugger(n).catch(e=>{console.error("[hypha-debugger] Auto-start failed:",e)})}"undefined"!=typeof window&&("loading"===document.readyState?document.addEventListener("DOMContentLoaded",autoStart):autoStart()),exports.HyphaDebugger=HyphaDebugger,exports.startDebugger=startDebugger});
58
+ \*********************************/__webpack_require__.r(__webpack_exports__),__webpack_require__.d(__webpack_exports__,{API_VERSION:()=>_rpc_js__WEBPACK_IMPORTED_MODULE_0__.API_VERSION,HTTPStreamingRPCConnection:()=>_http_client_js__WEBPACK_IMPORTED_MODULE_4__.HTTPStreamingRPCConnection,LocalWebSocket:()=>LocalWebSocket,RPC:()=>_rpc_js__WEBPACK_IMPORTED_MODULE_0__.RPC,connectToServer:()=>connectToServer,connectToServerHTTP:()=>_http_client_js__WEBPACK_IMPORTED_MODULE_4__.connectToServerHTTP,getRTCService:()=>_webrtc_client_js__WEBPACK_IMPORTED_MODULE_3__.getRTCService,getRemoteService:()=>getRemoteService,getRemoteServiceHTTP:()=>_http_client_js__WEBPACK_IMPORTED_MODULE_4__.getRemoteServiceHTTP,hyphaWebsocketClient:()=>hyphaWebsocketClient,loadRequirements:()=>_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.loadRequirements,login:()=>login,logout:()=>logout,normalizeServerUrlHTTP:()=>_http_client_js__WEBPACK_IMPORTED_MODULE_4__.normalizeServerUrl,registerRTCService:()=>_webrtc_client_js__WEBPACK_IMPORTED_MODULE_3__.registerRTCService,schemaFunction:()=>_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction,setupLocalClient:()=>setupLocalClient});var _rpc_js__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__(/*! ./rpc.js */"./src/rpc.js"),_utils_index_js__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__(/*! ./utils/index.js */"./src/utils/index.js"),_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__=__webpack_require__(/*! ./utils/schema.js */"./src/utils/schema.js"),_webrtc_client_js__WEBPACK_IMPORTED_MODULE_3__=__webpack_require__(/*! ./webrtc-client.js */"./src/webrtc-client.js"),_http_client_js__WEBPACK_IMPORTED_MODULE_4__=__webpack_require__(/*! ./http-client.js */"./src/http-client.js");const MAX_RETRY=1e6;class WebsocketRPCConnection{constructor(e,t,n,r,o=null,i=60,s=null,c=7200,a=null){(0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.assert)(e&&t,"server_url and client_id are required"),this._server_url=e,this._client_id=t,this._workspace=n,this._token=r,this._reconnection_token=o,this._websocket=null,this._handle_message=null,this._handle_connected=null,this._handle_disconnected=null,this._timeout=i,this._WebSocketClass=s||WebSocket,this._closed=!1,this._legacy_auth=null,this.connection_info=null,this._enable_reconnect=!1,this._token_refresh_interval=c,this.manager_id=null,this._refresh_token_task=null,this._reconnect_timeouts=new Set,this._additional_headers=a,this._reconnecting=!1,this._disconnectedNotified=!1}_cleanup(){this._refresh_token_delay&&(clearTimeout(this._refresh_token_delay),this._refresh_token_delay=null),this._refresh_token_task&&(clearInterval(this._refresh_token_task),this._refresh_token_task=null);for(const e of this._reconnect_timeouts)clearTimeout(e);this._reconnect_timeouts.clear()}on_message(e){(0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.assert)(e,"handler is required"),this._handle_message=e}on_connected(e){this._handle_connected=e}on_disconnected(e){this._handle_disconnected=e}async _attempt_connection(e,t=!0){return new Promise((n,r)=>{this._legacy_auth=!1;const o=new this._WebSocketClass(e);o.binaryType="arraybuffer",o.onopen=()=>{console.info("WebSocket connection established"),n(o)},o.onerror=e=>{console.error("WebSocket connection error:",e),r(new Error(`WebSocket connection error: ${e}`))},o.onclose=o=>{1003===o.code&&t?(console.info("Received 1003 error, attempting connection with query parameters."),this._legacy_auth=!0,this._attempt_connection_with_query_params(e).then(n).catch(r)):this._notifyDisconnected(o.reason)}})}async _attempt_connection_with_query_params(e){const t=[];this._client_id&&t.push(`client_id=${encodeURIComponent(this._client_id)}`),this._workspace&&t.push(`workspace=${encodeURIComponent(this._workspace)}`),this._token&&t.push(`token=${encodeURIComponent(this._token)}`),this._reconnection_token&&t.push(`reconnection_token=${encodeURIComponent(this._reconnection_token)}`);const n=e+(t.length>0?`?${t.join("&")}`:"");return await this._attempt_connection(n,!1)}_establish_connection(){return new Promise((e,t)=>{this._websocket.onmessage=n=>{const r=n.data,o=JSON.parse(r);if("connection_info"!=o.type){if("error"==o.type){const e="ConnectionAbortedError: "+o.message;return console.error("Failed to connect, "+e),void t(new Error(e))}return console.error("ConnectionAbortedError: Unexpected message received from the server:",r),void t(new Error("ConnectionAbortedError: Unexpected message received from the server"))}this.connection_info=o,this._workspace&&(0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.assert)(this.connection_info.workspace===this._workspace,`Connected to the wrong workspace: ${this.connection_info.workspace}, expected: ${this._workspace}`),this.connection_info.reconnection_token&&(this._reconnection_token=this.connection_info.reconnection_token),this.connection_info.reconnection_token_life_time&&this._token_refresh_interval>this.connection_info.reconnection_token_life_time/1.5&&(console.warn(`Token refresh interval is too long (${this._token_refresh_interval}), setting it to 1.5 times of the token life time(${this.connection_info.reconnection_token_life_time}).`),this._token_refresh_interval=this.connection_info.reconnection_token_life_time/1.5),this.manager_id=this.connection_info.manager_id||null,console.log(`Successfully connected to the server, workspace: ${this.connection_info.workspace}, manager_id: ${this.manager_id}`),this.connection_info.announcement&&console.log(`${this.connection_info.announcement}`),e(this.connection_info)}})}async open(){console.log("Creating a new websocket connection to",this._server_url.split("?")[0]);try{if(this._websocket=await this._attempt_connection(this._server_url),this._legacy_auth)throw new Error("NotImplementedError: Legacy authentication is not supported");const e=JSON.stringify({client_id:this._client_id,workspace:this._workspace,token:this._token,reconnection_token:this._reconnection_token});return this._websocket.send(e),await(0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.waitFor)(this._establish_connection(),this._timeout,"Failed to receive the first message from the server"),this._token_refresh_interval>0&&(this._refresh_token_delay=setTimeout(()=>{this._refresh_token_delay=null,this._closed||(this._send_refresh_token(),this._refresh_token_task=setInterval(()=>{this._send_refresh_token()},1e3*this._token_refresh_interval))},2e3)),this._enable_reconnect=!0,this._closed=!1,this._disconnectedNotified=!1,this._websocket.onmessage=e=>{if("string"==typeof e.data){const t=JSON.parse(e.data);"reconnection_token"===t.type?this._reconnection_token=t.reconnection_token:console.log("Received message from the server:",t)}else this._handle_message(e.data)},this._websocket.onerror=e=>{console.error("WebSocket connection error:",e),this._cleanup()},this._websocket.onclose=this._handle_close.bind(this),this._handle_connected&&this._handle_connected(this.connection_info),this.connection_info}catch(e){throw this._cleanup(),console.error("Failed to connect to",this._server_url.split("?")[0],e),e}}_send_refresh_token(){if(this._websocket&&this._websocket.readyState===WebSocket.OPEN){const e=JSON.stringify({type:"refresh_token"});this._websocket.send(e)}}_notifyDisconnected(e){this._disconnectedNotified||(this._disconnectedNotified=!0,this._handle_disconnected&&this._handle_disconnected(e))}_handle_close(e){if(!this._closed&&this._websocket&&this._websocket.readyState===WebSocket.CLOSED){if(this._cleanup(),this._disconnectedNotified=!1,this._enable_reconnect){if([1e3,1001].includes(e.code)?console.warn(`Websocket connection closed gracefully by server (code: ${e.code}): ${e.reason} - attempting reconnect`):console.warn("Websocket connection closed unexpectedly (code: %s): %s",e.code,e.reason),this._notifyDisconnected(e.reason),this._reconnecting)return void console.debug("Reconnection already in progress, skipping");this._reconnecting=!0;let t=0;const n=1e3,r=6e4,o=.1,i=async()=>{if(this._closed)return console.info("Connection was closed, stopping reconnection"),void(this._reconnecting=!1);try{console.warn(`Reconnecting to ${this._server_url.split("?")[0]} (attempt #${t})`),await this.open(),await new Promise(e=>setTimeout(e,500)),console.warn(`Successfully reconnected to server ${this._server_url} (services re-registered)`),this._reconnecting=!1}catch(e){if(`${e}`.includes("ConnectionAbortedError:"))return console.warn("Server refused to reconnect:",e),this._closed=!0,this._reconnecting=!1,void this._notifyDisconnected(`Server refused reconnection: ${e}`);if(`${e}`.includes("NotImplementedError:"))return console.error(`${e}\nIt appears that you are trying to connect to a hypha server that is older than 0.20.0, please upgrade the hypha server or use the websocket client in imjoy-rpc(https://www.npmjs.com/package/imjoy-rpc) instead`),this._closed=!0,this._reconnecting=!1,void this._notifyDisconnected(`Server too old: ${e}`);"NetworkError"===e.name||e.message.includes("network")?console.error(`Network error during reconnection: ${e.message}`):"TimeoutError"===e.name||e.message.includes("timeout")?console.error(`Connection timeout during reconnection: ${e.message}`):console.error(`Unexpected error during reconnection: ${e.message}`);const s=Math.min(n*Math.pow(2,t),r),c=(2*Math.random()-1)*o*s,a=Math.max(100,s+c);console.debug(`Waiting ${(a/1e3).toFixed(2)}s before next reconnection attempt`);const l=setTimeout(async()=>(this._reconnect_timeouts.delete(l),this._websocket&&this._websocket.readyState===WebSocket.OPEN?(console.info("Connection restored externally"),void(this._reconnecting=!1)):this._closed?(console.info("Connection was closed, stopping reconnection"),void(this._reconnecting=!1)):(t+=1,void(t<MAX_RETRY?await i():(console.error(`Failed to reconnect after ${MAX_RETRY} attempts, giving up.`),this._closed=!0,this._reconnecting=!1,this._notifyDisconnected("Max reconnection attempts exceeded"))))),a);this._reconnect_timeouts.add(l)}};i()}}else this._cleanup(),this._notifyDisconnected(e.reason)}async emit_message(e){if(this._closed)throw new Error("Connection is closed");this._websocket&&this._websocket.readyState===WebSocket.OPEN||await this.open();try{this._websocket.send(e)}catch(e){throw console.error(`Failed to send data, error: ${e}`),e}}disconnect(e){this._closed=!0,this._reconnecting=!1,this._websocket&&this._websocket.readyState!==WebSocket.CLOSED&&this._websocket.readyState!==WebSocket.CLOSING&&this._websocket.close(1e3,e),this._cleanup(),console.info(`WebSocket connection disconnected (${e})`)}}function normalizeServerUrl(e){if(!e)throw new Error("server_url is required");return e.startsWith("http://")?e=e.replace("http://","ws://").replace(/\/$/,"")+"/ws":e.startsWith("https://")&&(e=e.replace("https://","wss://").replace(/\/$/,"")+"/ws"),e}async function login(e){const t=e.login_service_id||"public/hypha-login",n=e.workspace,r=e.expires_in,o=e.login_timeout||60,i=e.login_callback,s=e.profile,c=e.additional_headers,a=e.transport||"websocket",l=await connectToServer({name:"initial login client",server_url:e.server_url,additional_headers:c,transport:a});try{const e=await l.getService(t);let c;return(0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.assert)(e,`Failed to get the login service: ${t}`),c=n?await e.start({workspace:n,expires_in:r,_rkwargs:!0}):await e.start(),i?await i(c):console.log(`Please open your browser and login at ${c.login_url}`),await e.check(c.key,{timeout:o,profile:s,_rkwargs:!0})}catch(e){throw e}finally{await l.disconnect()}}async function logout(e){const t=e.login_service_id||"public/hypha-login",n=e.logout_callback,r=e.additional_headers,o=e.transport||"websocket",i=await connectToServer({name:"initial logout client",server_url:e.server_url,additional_headers:r,transport:o});try{const e=await i.getService(t);if((0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.assert)(e,`Failed to get the login service: ${t}`),!e.logout)throw new Error("Logout is not supported by this server. Please upgrade the Hypha server to a version that supports logout.");const r=await e.logout({});return n?await n(r):console.log(`Please open your browser to logout at ${r.logout_url}`),r}catch(e){throw e}finally{await i.disconnect()}}async function webrtcGetService(e,t,n){const r=void 0!==(n=n||{}).webrtc?n.webrtc:"auto",o=n.webrtc_config;void 0!==n.webrtc&&delete n.webrtc,void 0!==n.webrtc_config&&delete n.webrtc_config,(0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.assert)([void 0,!0,!1,"auto"].includes(r),"webrtc must be true, false or 'auto'");const i=await e.getService(t,n);if(!0===r||"auto"===r){if(i.id.includes(":")&&i.id.includes("/"))try{const t=i.id.split(":")[0].split("/"),r=t[t.length-1],s=`${t.slice(0,-1).join("/")}/${r}-rtc`,c=await(0,_webrtc_client_js__WEBPACK_IMPORTED_MODULE_3__.getRTCService)(e,s,o),a=await c.getService(i.id.split(":")[1],n);return a._webrtc=!0,a._peer=c,a._service=i,a}catch(e){console.warn("Failed to get webrtc service, using websocket connection",e)}if(!0===r)throw new Error("Failed to get the service via webrtc")}return i}async function connectToServer(e){if("http"===(e.transport||"websocket"))return await(0,_http_client_js__WEBPACK_IMPORTED_MODULE_4__.connectToServerHTTP)(e);e.server&&(e.server_url=e.server_url||e.server.url,e.WebSocketClass=e.WebSocketClass||e.server.WebSocketClass);let t=e.client_id;t||(t=(0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.randId)(),e.client_id=t),0===Object.keys(e).length&&("undefined"!=typeof process&&process.env?(e.server_url=process.env.HYPHA_SERVER_URL,e.token=process.env.HYPHA_TOKEN,e.client_id=process.env.HYPHA_CLIENT_ID,e.workspace=process.env.HYPHA_WORKSPACE):"undefined"!=typeof self&&self.env?(e.server_url=self.env.HYPHA_SERVER_URL,e.token=self.env.HYPHA_TOKEN,e.client_id=self.env.HYPHA_CLIENT_ID,e.workspace=self.env.HYPHA_WORKSPACE):"undefined"!=typeof globalThis&&globalThis.env&&(e.server_url=globalThis.env.HYPHA_SERVER_URL,e.token=globalThis.env.HYPHA_TOKEN,e.client_id=globalThis.env.HYPHA_CLIENT_ID,e.workspace=globalThis.env.HYPHA_WORKSPACE));let n=normalizeServerUrl(e.server_url),r=new WebsocketRPCConnection(n,t,e.workspace,e.token,e.reconnection_token,e.method_timeout||60,e.WebSocketClass,e.token_refresh_interval,e.additional_headers);const o=await r.open();if((0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.assert)(o,"Failed to connect to the server, no connection info obtained. This issue is most likely due to an outdated Hypha server version. Please use `imjoy-rpc` for compatibility, or upgrade the Hypha server to the latest version."),await new Promise(e=>setTimeout(e,100)),!r.manager_id){console.warn("Manager ID not set immediately, waiting...");const e=5e3,t=100,n=Date.now();for(;!r.manager_id&&Date.now()-n<e;)await new Promise(e=>setTimeout(e,t));if(!r.manager_id)throw console.error("Manager ID still not set after waiting"),new Error("Failed to get manager ID from server");console.info(`Manager ID set after waiting: ${r.manager_id}`)}if(e.workspace&&o.workspace!==e.workspace)throw new Error(`Connected to the wrong workspace: ${o.workspace}, expected: ${e.workspace}`);const i=o.workspace,s=new _rpc_js__WEBPACK_IMPORTED_MODULE_0__.RPC(r,{client_id:t,workspace:i,default_context:{connection_type:"websocket"},name:e.name,method_timeout:e.method_timeout,app_id:e.app_id,server_base_url:o.public_base_url,long_message_chunk_size:e.long_message_chunk_size});await s.waitFor("services_registered",e.method_timeout||120);const c=await s.get_manager_service({timeout:e.method_timeout,case_conversion:"camel",kwargs_expansion:e.kwargs_expansion||!1});if(c.rpc=s,o&&(c.config=Object.assign(c.config,o)),c.export=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction)(async function(t){t.id="default",t.name=t.name||e.name||t.id,t.description=t.description||e.description,await s.register_service(t,{overwrite:!0})},{name:"export",description:"Export the api.",parameters:{properties:{api:{description:"The api to export",type:"object"}},required:["api"],type:"object"}}),c.getApp=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction)(async function(e){return e=e||"*",(0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.assert)(!e.includes(":"),"clientId should not contain ':'"),e.includes("/")||(e=o.workspace+"/"+e),(0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.assert)(2===e.split("/").length,"clientId should match pattern workspace/clientId"),await c.getService(`${e}:default`)},{name:"getApp",description:"Get the app.",parameters:{properties:{clientId:{default:"*",description:"The clientId",type:"string"}},type:"object"}}),c.listApps=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction)(async function(e){e=e||i,(0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.assert)(!e.includes(":"),"workspace should not contain ':'"),(0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.assert)(!e.includes("/"),"workspace should not contain '/'");const t={workspace:e,service_id:"default"};return await c.listServices(t)},{name:"listApps",description:"List the apps.",parameters:{properties:{workspace:{default:i,description:"The workspace",type:"string"}},type:"object"}}),c.disconnect=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction)(s.disconnect.bind(s),{name:"disconnect",description:"Disconnect from the server.",parameters:{type:"object",properties:{},required:[]}}),c.registerCodec=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction)(s.register_codec.bind(s),{name:"registerCodec",description:"Register a codec for the webrtc connection",parameters:{type:"object",properties:{codec:{type:"object",description:"Codec to register",properties:{name:{type:"string"},type:{},encoder:{type:"function"},decoder:{type:"function"}}}}}}),c.emit=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction)(s.emit.bind(s),{name:"emit",description:"Emit a message.",parameters:{properties:{data:{description:"The data to emit",type:"object"}},required:["data"],type:"object"}}),c.on=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction)(s.on.bind(s),{name:"on",description:"Register a message handler.",parameters:{properties:{event:{description:"The event to listen to",type:"string"},handler:{description:"The handler function",type:"function"}},required:["event","handler"],type:"object"}}),c.off=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction)(s.off.bind(s),{name:"off",description:"Remove a message handler.",parameters:{properties:{event:{description:"The event to remove",type:"string"},handler:{description:"The handler function",type:"function"}},required:["event","handler"],type:"object"}}),c.once=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction)(s.once.bind(s),{name:"once",description:"Register a one-time message handler.",parameters:{properties:{event:{description:"The event to listen to",type:"string"},handler:{description:"The handler function",type:"function"}},required:["event","handler"],type:"object"}}),c.getServiceSchema=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction)(s.get_service_schema,{name:"getServiceSchema",description:"Get the service schema.",parameters:{properties:{service:{description:"The service to extract schema",type:"object"}},required:["service"],type:"object"}}),c.registerService=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction)(s.register_service.bind(s),{name:"registerService",description:"Register a service.",parameters:{properties:{service:{description:"The service to register",type:"object"},force:{default:!1,description:"Force to register the service",type:"boolean"}},required:["service"],type:"object"}}),c.unregisterService=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction)(s.unregister_service.bind(s),{name:"unregisterService",description:"Unregister a service.",parameters:{properties:{service:{description:"The service id to unregister",type:"string"},notify:{default:!0,description:"Notify the workspace manager",type:"boolean"}},required:["service"],type:"object"}}),r.manager_id&&s.on("force-exit",async e=>{e.from==="*/"+r.manager_id&&(console.log("Disconnecting from server, reason:",e.reason),await s.disconnect())}),e.webrtc){await(0,_webrtc_client_js__WEBPACK_IMPORTED_MODULE_3__.registerRTCService)(c,`${t}-rtc`,e.webrtc_config);const n=Object.assign({},c),r=n.getService.__schema__.description,o=n.getService.__schema__.parameters;c.getService=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction)(webrtcGetService.bind(null,n),{name:"getService",description:r,parameters:o}),c.getRTCService=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction)(_webrtc_client_js__WEBPACK_IMPORTED_MODULE_3__.getRTCService.bind(null,c),{name:"getRTCService",description:"Get the webrtc connection, returns a peer connection.",parameters:{properties:{config:{description:"The config for the webrtc service",type:"object"}},required:["config"],type:"object"}})}else{const e=c.getService;c.getService=(t,n)=>e(t,n=n||{}),c.getService.__schema__=e.__schema__}return c.registerProbes=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction)(async function(e){return e.id="probes",e.name="Probes",e.config={visibility:"public"},e.type="probes",e.description=`Probes Service, visit ${n}/${i}services/probes for the available probes.`,await c.registerService(e,{overwrite:!0})},{name:"registerProbes",description:"Register probes service",parameters:{properties:{probes:{description:"The probes to register, e.g. {'liveness': {'type': 'function', 'description': 'Check the liveness of the service'}}",type:"object"}},required:["probes"],type:"object"}}),c}async function getRemoteService(e,t={}){const{serverUrl:n,workspace:r,clientId:o,serviceId:i,appId:s}=(0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.parseServiceUrl)(e),c=`${r}/${o}:${i}@${s}`;if(t.serverUrl&&t.serverUrl!==n)throw new Error("server_url in config does not match the server_url in the url");t.serverUrl=n;const a=await connectToServer(t);return await a.getService(c)}class LocalWebSocket{constructor(e,t,n){this.url=e,this.onopen=()=>{},this.onmessage=()=>{},this.onclose=()=>{},this.onerror=()=>{},this.client_id=t,this.workspace=n;const r="undefined"!=typeof window?window:self,o="undefined"!=typeof window;if(this.postMessage=e=>{o?window.parent.postMessage(e,"*"):self.postMessage(e)},this.readyState=WebSocket.CONNECTING,this._context=r,this._messageListener=e=>{const{type:t,data:n,to:r}=e.data;if(r===this.client_id)switch(t){case"message":this.readyState===WebSocket.OPEN&&this.onmessage&&this.onmessage({data:n});break;case"connected":this.readyState=WebSocket.OPEN,this.onopen(e);break;case"closed":this.readyState=WebSocket.CLOSED,this.onclose(e)}},r.addEventListener("message",this._messageListener,!1),!this.client_id)throw new Error("client_id is required");if(!this.workspace)throw new Error("workspace is required");this.postMessage({type:"connect",url:this.url,from:this.client_id,workspace:this.workspace})}send(e){this.readyState===WebSocket.OPEN&&this.postMessage({type:"message",data:e,from:this.client_id,workspace:this.workspace})}close(){this.readyState=WebSocket.CLOSING,this.postMessage({type:"close",from:this.client_id,workspace:this.workspace}),this._context&&this._messageListener&&(this._context.removeEventListener("message",this._messageListener,!1),this._messageListener=null),this.onclose()}addEventListener(e,t){"message"===e&&(this.onmessage=t),"open"===e&&(this.onopen=t),"close"===e&&(this.onclose=t),"error"===e&&(this.onerror=t)}}const hyphaWebsocketClient={RPC:_rpc_js__WEBPACK_IMPORTED_MODULE_0__.RPC,API_VERSION:_rpc_js__WEBPACK_IMPORTED_MODULE_0__.API_VERSION,schemaFunction:_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction,loadRequirements:_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.loadRequirements,login:login,logout:logout,connectToServer:connectToServer,connectToServerHTTP:_http_client_js__WEBPACK_IMPORTED_MODULE_4__.connectToServerHTTP,getRemoteService:getRemoteService,getRemoteServiceHTTP:_http_client_js__WEBPACK_IMPORTED_MODULE_4__.getRemoteServiceHTTP,getRTCService:_webrtc_client_js__WEBPACK_IMPORTED_MODULE_3__.getRTCService,registerRTCService:_webrtc_client_js__WEBPACK_IMPORTED_MODULE_3__.registerRTCService,get setupLocalClient(){return setupLocalClient},get LocalWebSocket(){return LocalWebSocket},HTTPStreamingRPCConnection:_http_client_js__WEBPACK_IMPORTED_MODULE_4__.HTTPStreamingRPCConnection,normalizeServerUrlHTTP:_http_client_js__WEBPACK_IMPORTED_MODULE_4__.normalizeServerUrl};function setupLocalClient({enable_execution:enable_execution=!1,on_ready:on_ready=null}){return new Promise((resolve,reject)=>{const context="undefined"!=typeof window?window:self,isWindow="undefined"!=typeof window;context.addEventListener("message",event=>{const{type:type,server_url:server_url,workspace:workspace,client_id:client_id,token:token,method_timeout:method_timeout,name:name,config:config}=event.data;if("initializeHyphaClient"===type){if(!server_url||!workspace||!client_id)return void console.error("server_url, workspace, and client_id are required.");if(!server_url.startsWith("https://local-hypha-server:"))return void console.error("server_url should start with https://local-hypha-server:");class FixedLocalWebSocket extends LocalWebSocket{constructor(e){super(e,client_id,workspace)}}connectToServer({server_url:server_url,workspace:workspace,client_id:client_id,token:token,method_timeout:method_timeout,name:name,WebSocketClass:FixedLocalWebSocket}).then(async server=>{globalThis.api=server;try{if(isWindow&&enable_execution){function e(e){return new Promise((t,n)=>{const r=document.createElement("script");r.innerHTML=e.content,r.lang=e.lang,r.onload=()=>t(),r.onerror=e=>n(e),document.head.appendChild(r)})}if(config.styles&&config.styles.length>0)for(const t of config.styles){const n=document.createElement("style");n.innerHTML=t.content,n.lang=t.lang,document.head.appendChild(n)}if(config.links&&config.links.length>0)for(const r of config.links){const o=document.createElement("a");o.href=r.url,o.innerText=r.text,document.body.appendChild(o)}if(config.windows&&config.windows.length>0)for(const i of config.windows){document.body.innerHTML=i.content;break}if(config.scripts&&config.scripts.length>0)for(const s of config.scripts){if("javascript"!==s.lang)throw new Error("Only javascript scripts are supported");await e(s)}}else if(!isWindow&&enable_execution&&config.scripts&&config.scripts.length>0)for(const script of config.scripts){if("javascript"!==script.lang)throw new Error("Only javascript scripts are supported");eval(script.content)}on_ready&&await on_ready(server,config),resolve(server)}catch(c){reject(c)}})}},!1),isWindow?window.parent.postMessage({type:"hyphaClientReady"},"*"):self.postMessage({type:"hyphaClientReady"})})}var __webpack_exports__API_VERSION=__webpack_exports__.API_VERSION,__webpack_exports__HTTPStreamingRPCConnection=__webpack_exports__.HTTPStreamingRPCConnection,__webpack_exports__LocalWebSocket=__webpack_exports__.LocalWebSocket,__webpack_exports__RPC=__webpack_exports__.RPC,__webpack_exports__connectToServer=__webpack_exports__.connectToServer,__webpack_exports__connectToServerHTTP=__webpack_exports__.connectToServerHTTP,__webpack_exports__getRTCService=__webpack_exports__.getRTCService,__webpack_exports__getRemoteService=__webpack_exports__.getRemoteService,__webpack_exports__getRemoteServiceHTTP=__webpack_exports__.getRemoteServiceHTTP,__webpack_exports__hyphaWebsocketClient=__webpack_exports__.hyphaWebsocketClient,__webpack_exports__loadRequirements=__webpack_exports__.loadRequirements,__webpack_exports__login=__webpack_exports__.login,__webpack_exports__logout=__webpack_exports__.logout,__webpack_exports__normalizeServerUrlHTTP=__webpack_exports__.normalizeServerUrlHTTP,__webpack_exports__registerRTCService=__webpack_exports__.registerRTCService,__webpack_exports__schemaFunction=__webpack_exports__.schemaFunction,__webpack_exports__setupLocalClient=__webpack_exports__.setupLocalClient,hyphaRpcWebsocket=Object.freeze({__proto__:null,API_VERSION:__webpack_exports__API_VERSION,HTTPStreamingRPCConnection:__webpack_exports__HTTPStreamingRPCConnection,LocalWebSocket:__webpack_exports__LocalWebSocket,RPC:__webpack_exports__RPC,connectToServer:__webpack_exports__connectToServer,connectToServerHTTP:__webpack_exports__connectToServerHTTP,getRTCService:__webpack_exports__getRTCService,getRemoteService:__webpack_exports__getRemoteService,getRemoteServiceHTTP:__webpack_exports__getRemoteServiceHTTP,hyphaWebsocketClient:__webpack_exports__hyphaWebsocketClient,loadRequirements:__webpack_exports__loadRequirements,login:__webpack_exports__login,logout:__webpack_exports__logout,normalizeServerUrlHTTP:__webpack_exports__normalizeServerUrlHTTP,registerRTCService:__webpack_exports__registerRTCService,schemaFunction:__webpack_exports__schemaFunction,setupLocalClient:__webpack_exports__setupLocalClient}),hyphaRpc=Object.freeze({__proto__:null,API_VERSION:__webpack_exports__API_VERSION,HTTPStreamingRPCConnection:__webpack_exports__HTTPStreamingRPCConnection,LocalWebSocket:__webpack_exports__LocalWebSocket,RPC:__webpack_exports__RPC,connectToServer:__webpack_exports__connectToServer,connectToServerHTTP:__webpack_exports__connectToServerHTTP,getRTCService:__webpack_exports__getRTCService,getRemoteService:__webpack_exports__getRemoteService,getRemoteServiceHTTP:__webpack_exports__getRemoteServiceHTTP,hyphaWebsocketClient:hyphaRpcWebsocket,loadRequirements:__webpack_exports__loadRequirements,login:__webpack_exports__login,logout:__webpack_exports__logout,normalizeServerUrlHTTP:__webpack_exports__normalizeServerUrlHTTP,registerRTCService:__webpack_exports__registerRTCService,schemaFunction:__webpack_exports__schemaFunction,setupLocalClient:__webpack_exports__setupLocalClient});const overlayStyles="\n :host {\n all: initial;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n }\n\n * {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n }\n\n .debugger-icon {\n width: 40px;\n height: 40px;\n border-radius: 50%;\n background: #4a90d9;\n color: white;\n display: flex;\n align-items: center;\n justify-content: center;\n cursor: pointer;\n box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);\n transition: transform 0.15s, background 0.15s;\n user-select: none;\n font-size: 18px;\n line-height: 1;\n }\n\n .debugger-icon:hover {\n transform: scale(1.1);\n background: #357abd;\n }\n\n .debugger-icon.connected {\n background: #27ae60;\n }\n\n .debugger-icon.error {\n background: #e74c3c;\n }\n\n .debugger-panel {\n display: none;\n width: 380px;\n max-height: 520px;\n background: #1e1e2e;\n color: #cdd6f4;\n border-radius: 8px;\n border: 1px solid #45475a;\n box-shadow: 0 8px 32px rgba(0, 0, 0, 0.5);\n overflow: hidden;\n flex-direction: column;\n position: absolute;\n bottom: 50px;\n right: 0;\n font-size: 13px;\n }\n\n .debugger-panel.open {\n display: flex;\n }\n\n .panel-header {\n background: #313244;\n padding: 8px 12px;\n display: flex;\n align-items: center;\n justify-content: space-between;\n cursor: default;\n border-bottom: 1px solid #45475a;\n font-weight: 600;\n font-size: 12px;\n letter-spacing: 0.3px;\n text-transform: uppercase;\n color: #a6adc8;\n }\n\n .panel-header .title {\n display: flex;\n align-items: center;\n gap: 6px;\n }\n\n .panel-header .close-btn {\n cursor: pointer;\n color: #6c7086;\n font-size: 16px;\n line-height: 1;\n padding: 2px 4px;\n border-radius: 3px;\n }\n\n .panel-header .close-btn:hover {\n color: #cdd6f4;\n background: #45475a;\n }\n\n .status-dot {\n width: 8px;\n height: 8px;\n border-radius: 50%;\n display: inline-block;\n background: #6c7086;\n }\n\n .status-dot.connected {\n background: #a6e3a1;\n }\n\n .status-dot.error {\n background: #f38ba8;\n }\n\n .panel-body {\n padding: 10px 12px;\n overflow-y: auto;\n flex: 1;\n max-height: 440px;\n }\n\n .info-row {\n display: flex;\n justify-content: space-between;\n padding: 4px 0;\n border-bottom: 1px solid #313244;\n font-size: 12px;\n }\n\n .info-row .label {\n color: #6c7086;\n }\n\n .info-row .value {\n color: #cdd6f4;\n text-align: right;\n word-break: break-all;\n max-width: 180px;\n font-family: 'SF Mono', Monaco, Consolas, monospace;\n font-size: 11px;\n }\n\n .instructions-section {\n margin-top: 8px;\n padding-top: 6px;\n border-top: 1px solid #313244;\n }\n\n .instructions-header {\n display: flex;\n align-items: center;\n justify-content: space-between;\n margin-bottom: 4px;\n }\n\n .url-label {\n font-size: 11px;\n color: #6c7086;\n text-transform: uppercase;\n letter-spacing: 0.5px;\n margin-bottom: 3px;\n }\n\n .instructions-block {\n font-family: 'SF Mono', Monaco, Consolas, monospace;\n font-size: 10px;\n color: #a6e3a1;\n background: #11111b;\n border: 1px solid #313244;\n border-radius: 4px;\n padding: 8px;\n white-space: pre-wrap;\n word-break: break-all;\n max-height: 200px;\n overflow-y: auto;\n line-height: 1.5;\n }\n\n .copy-btn {\n background: #45475a;\n color: #cdd6f4;\n border: none;\n border-radius: 3px;\n padding: 2px 8px;\n font-size: 10px;\n cursor: pointer;\n white-space: nowrap;\n flex-shrink: 0;\n }\n\n .copy-btn:hover {\n background: #585b70;\n }\n\n .log-section {\n margin-top: 8px;\n }\n\n .log-title {\n font-size: 11px;\n color: #6c7086;\n text-transform: uppercase;\n letter-spacing: 0.5px;\n margin-bottom: 4px;\n }\n\n .log-entry {\n font-family: 'SF Mono', Monaco, Consolas, monospace;\n font-size: 11px;\n padding: 3px 6px;\n border-radius: 3px;\n background: #313244;\n margin-bottom: 2px;\n color: #a6adc8;\n word-break: break-all;\n }\n\n .log-entry.call {\n border-left: 2px solid #89b4fa;\n }\n\n .log-entry.result {\n border-left: 2px solid #a6e3a1;\n }\n\n .log-entry.error {\n border-left: 2px solid #f38ba8;\n color: #f38ba8;\n }\n";class DebugOverlay{constructor(e){this.isOpen=!1,this.isDragging=!1,this.dragOffset={x:0,y:0},this.maxLogEntries=50,this.host=document.createElement("div"),this.host.id="hypha-debugger-host",Object.assign(this.host.style,{position:"fixed",bottom:"20px",right:"20px",zIndex:"2147483647",display:"flex",flexDirection:"column",alignItems:"flex-end"}),e?.position&&(this.host.style.bottom="auto",this.host.style.right="auto",this.host.style.left=e.position.x+"px",this.host.style.top=e.position.y+"px"),this.shadow=this.host.attachShadow({mode:"open"});const t=document.createElement("style");t.textContent=overlayStyles,this.shadow.appendChild(t);const n=document.createElement("div");n.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.alignItems="flex-end",this.panel=document.createElement("div"),this.panel.className="debugger-panel";const r=document.createElement("div");r.className="panel-header";const o=document.createElement("span");o.className="title",this.statusDot=document.createElement("span"),this.statusDot.className="status-dot",o.appendChild(this.statusDot),o.appendChild(document.createTextNode(" Hypha Debugger"));const i=document.createElement("span");i.className="close-btn",i.textContent="×",i.addEventListener("click",()=>this.toggle()),r.appendChild(o),r.appendChild(i);const s=document.createElement("div");s.className="panel-body",this.infoBody=document.createElement("div"),s.appendChild(this.infoBody);const c=document.createElement("div");c.className="log-section";const a=document.createElement("div");a.className="log-title",a.textContent="Remote Operations",this.logContainer=document.createElement("div"),c.appendChild(a),c.appendChild(this.logContainer),s.appendChild(c),this.panel.appendChild(r),this.panel.appendChild(s),this.icon=document.createElement("div"),this.icon.className="debugger-icon",this.icon.textContent="🐛",this.icon.addEventListener("click",e=>{this.isDragging||this.toggle()}),n.appendChild(this.panel),n.appendChild(this.icon),this.shadow.appendChild(n),document.documentElement.appendChild(this.host),this.setupDrag()}setupDrag(){let e=0,t=0,n=!1;this.icon.addEventListener("mousedown",r=>{e=r.clientX,t=r.clientY,n=!1;const o=this.host.getBoundingClientRect();this.dragOffset.x=r.clientX-o.left,this.dragOffset.y=r.clientY-o.top,r.preventDefault()}),document.addEventListener("mousemove",r=>{if(0===e&&0===t)return;const o=Math.abs(r.clientX-e),i=Math.abs(r.clientY-t);(o>3||i>3)&&(n=!0,this.isDragging=!0,this.host.style.left=r.clientX-this.dragOffset.x+"px",this.host.style.top=r.clientY-this.dragOffset.y+"px",this.host.style.right="auto",this.host.style.bottom="auto")}),document.addEventListener("mouseup",()=>{e=0,t=0,n&&setTimeout(()=>{this.isDragging=!1},50)})}toggle(){this.isOpen=!this.isOpen,this.panel.classList.toggle("open",this.isOpen)}setStatus(e){this.statusDot.className="status-dot",this.icon.className="debugger-icon","connected"===e?(this.statusDot.classList.add("connected"),this.icon.classList.add("connected")):"error"===e&&(this.statusDot.classList.add("error"),this.icon.classList.add("error"))}setInfo(e){this.infoBody.querySelectorAll(".info-row").forEach(e=>e.remove());const t=this.infoBody.firstChild;for(const[n,r]of Object.entries(e)){const e=document.createElement("div");e.className="info-row";const o=document.createElement("span");o.className="label",o.textContent=n;const i=document.createElement("span");i.className="value",i.textContent=r,i.title=r,e.appendChild(o),e.appendChild(i),this.infoBody.insertBefore(e,t)}}setInstructions(e){const t=this.infoBody.querySelector(".instructions-section");t&&t.remove();const n=document.createElement("div");n.className="instructions-section";const r=document.createElement("div");r.className="instructions-header";const o=document.createElement("span");o.className="url-label",o.textContent="Instructions";const i=document.createElement("button");i.className="copy-btn",i.textContent="Copy All",i.addEventListener("click",()=>{navigator.clipboard.writeText(e).then(()=>{i.textContent="Copied!",setTimeout(()=>{i.textContent="Copy All"},1500)})}),r.appendChild(o),r.appendChild(i),n.appendChild(r);const s=document.createElement("pre");s.className="instructions-block",s.textContent=e,n.appendChild(s),this.infoBody.appendChild(n)}addLog(e,t="call"){const n=document.createElement("div");for(n.className=`log-entry ${t}`,n.textContent=e,this.logContainer.appendChild(n);this.logContainer.children.length>this.maxLogEntries;)this.logContainer.removeChild(this.logContainer.firstChild);const r=this.panel.querySelector(".panel-body");r&&(r.scrollTop=r.scrollHeight)}destroy(){this.host.remove()}}const CURSOR_BORDER_SVG='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" fill="none"><g><path d="M 15 42 L 15 36.99 Q 15 31.99 23.7 31.99 L 28.05 31.99 Q 32.41 31.99 32.41 21.99 L 32.41 17 Q 32.41 12 41.09 16.95 L 76.31 37.05 Q 85 42 76.31 46.95 L 41.09 67.05 Q 32.41 72 32.41 62.01 L 32.41 57.01 Q 32.41 52.01 23.7 52.01 L 19.35 52.01 Q 15 52.01 15 47.01 Z" fill="none" stroke="currentColor" stroke-width="6" stroke-miterlimit="10"/></g></svg>',CURSOR_FILL_SVG='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><g style="filter: drop-shadow(rgba(0, 0, 0, 0.3) 3px 4px 4px);"><path d="M 15 42 L 15 36.99 Q 15 31.99 23.7 31.99 L 28.05 31.99 Q 32.41 31.99 32.41 21.99 L 32.41 17 Q 32.41 12 41.09 16.95 L 76.31 37.05 Q 85 42 76.31 46.95 L 41.09 67.05 Q 32.41 72 32.41 62.01 L 32.41 57.01 Q 32.41 52.01 23.7 52.01 L 19.35 52.01 Q 15 52.01 15 47.01 Z" fill="#ffffff" stroke="none"/></g></svg>',CURSOR_CSS="\n .hypha-cursor {\n position: fixed;\n width: 50px;\n height: 50px;\n pointer-events: none;\n z-index: 2147483646;\n transition: opacity 0.2s;\n opacity: 0;\n }\n .hypha-cursor.visible {\n opacity: 1;\n }\n .hypha-cursor-border {\n position: absolute;\n width: 100%;\n height: 100%;\n background: linear-gradient(45deg, rgb(57, 182, 255), rgb(189, 69, 251));\n mask-image: var(--cursor-border);\n -webkit-mask-image: var(--cursor-border);\n mask-size: 100% 100%;\n -webkit-mask-size: 100% 100%;\n mask-repeat: no-repeat;\n -webkit-mask-repeat: no-repeat;\n transform-origin: center;\n transform: rotate(-135deg) scale(1.2);\n margin-left: -10px;\n margin-top: -14px;\n }\n .hypha-cursor-fill {\n position: absolute;\n width: 100%;\n height: 100%;\n background-image: var(--cursor-fill);\n background-size: 100% 100%;\n background-repeat: no-repeat;\n transform-origin: center;\n transform: rotate(-135deg) scale(1.2);\n margin-left: -10px;\n margin-top: -14px;\n }\n .hypha-cursor-ripple {\n position: absolute;\n width: 100%;\n height: 100%;\n pointer-events: none;\n margin-left: -50%;\n margin-top: -50%;\n }\n .hypha-cursor-ripple::after {\n content: '';\n opacity: 0;\n position: absolute;\n inset: 0;\n border: 3px solid rgba(57, 182, 255, 1);\n border-radius: 50%;\n }\n .hypha-cursor.clicking .hypha-cursor-ripple::after {\n animation: hypha-cursor-ripple 400ms ease-out forwards;\n }\n @keyframes hypha-cursor-ripple {\n 0% { transform: scale(0); opacity: 1; }\n 100% { transform: scale(2.5); opacity: 0; }\n }\n";class AICursor{constructor(){this.currentX=0,this.currentY=0,this.targetX=0,this.targetY=0,this.animating=!1,this.visible=!1,this.hideTimeout=null,this.container=document.createElement("div"),this.container.id="hypha-debugger-cursor",this.container.setAttribute("data-browser-use-ignore","true"),this.container.setAttribute("data-page-agent-ignore","true");const e=document.createElement("style");e.textContent=CURSOR_CSS,this.container.appendChild(e),this.cursor=document.createElement("div"),this.cursor.className="hypha-cursor";const t='url("data:image/svg+xml,'+encodeURIComponent(CURSOR_BORDER_SVG)+'")',n='url("data:image/svg+xml,'+encodeURIComponent(CURSOR_FILL_SVG)+'")';this.cursor.style.setProperty("--cursor-border",t),this.cursor.style.setProperty("--cursor-fill",n);const r=document.createElement("div");r.className="hypha-cursor-ripple",this.cursor.appendChild(r);const o=document.createElement("div");o.className="hypha-cursor-fill",this.cursor.appendChild(o);const i=document.createElement("div");i.className="hypha-cursor-border",this.cursor.appendChild(i),this.container.appendChild(this.cursor),document.body.appendChild(this.container),window.addEventListener("HyphaDebugger::MovePointerTo",e=>{const{x:t,y:n}=e.detail;this.moveTo(t,n)}),window.addEventListener("HyphaDebugger::ClickPointer",()=>{this.triggerClickAnimation()})}moveTo(e,t){this.targetX=e,this.targetY=t,this.visible||(this.visible=!0,this.currentX=e,this.currentY=t,this.cursor.style.left=`${e}px`,this.cursor.style.top=`${t}px`,this.cursor.classList.add("visible")),this.hideTimeout&&(clearTimeout(this.hideTimeout),this.hideTimeout=null),this.animating||(this.animating=!0,this.animateLoop())}animateLoop(){const e=this.targetX-this.currentX,t=this.targetY-this.currentY;Math.abs(e)>1||Math.abs(t)>1?(this.currentX+=.18*e,this.currentY+=.18*t,this.cursor.style.left=`${this.currentX}px`,this.cursor.style.top=`${this.currentY}px`,requestAnimationFrame(()=>this.animateLoop())):(this.currentX=this.targetX,this.currentY=this.targetY,this.cursor.style.left=`${this.currentX}px`,this.cursor.style.top=`${this.currentY}px`,this.animating=!1,this.hideTimeout=setTimeout(()=>{this.visible=!1,this.cursor.classList.remove("visible")},2e3))}triggerClickAnimation(){this.cursor.classList.remove("clicking"),this.cursor.offsetHeight,this.cursor.classList.add("clicking")}destroy(){this.hideTimeout&&clearTimeout(this.hideTimeout),this.container.remove()}}function detectFrameworks(){const e=[],t=window;if(t.__REACT_DEVTOOLS_GLOBAL_HOOK__?.renderers?.size>0)e.push("react");else{const t=document.querySelector("#root, #app, [data-reactroot]");if(t){Object.keys(t).some(e=>e.startsWith("__reactFiber$")||e.startsWith("__reactInternalInstance$"))&&e.push("react")}}if(t.__VUE__||t.__VUE_DEVTOOLS_GLOBAL_HOOK__)e.push("vue");else{const t=document.querySelector("[data-v-app], #app");t&&t.__vue_app__&&e.push("vue")}return(t.ng||document.querySelector("[ng-version]"))&&e.push("angular"),document.querySelector("[class*='svelte-']")&&e.push("svelte"),t.__NEXT_DATA__&&e.push("nextjs"),e}function collectPageInfo(){const e=performance.getEntriesByType("navigation")[0];return{url:window.location.href,title:document.title,viewport:{width:window.innerWidth,height:window.innerHeight},document_size:{width:document.documentElement.scrollWidth,height:document.documentElement.scrollHeight},user_agent:navigator.userAgent,timestamp:(new Date).toISOString(),cookies_enabled:navigator.cookieEnabled,language:navigator.language,platform:navigator.platform,online:navigator.onLine,performance:{load_time_ms:e?Math.round(e.loadEventEnd-e.startTime):null,dom_content_loaded_ms:e?Math.round(e.domContentLoadedEventEnd-e.startTime):null},frameworks:detectFrameworks()}}function getPageInfo(e,t,n){const r=collectPageInfo();if(e){const e=window.__HYPHA_DEBUGGER__?.consoleLogs??[],o=t??50;let i=n?e.filter(e=>e.level===n):e;r.console_logs=i.slice(-o)}return r}function installConsoleCapture(e=500){var t;const n=(t=window).__HYPHA_DEBUGGER__??(t.__HYPHA_DEBUGGER__={});if(n.consoleInstalled)return;n.consoleLogs=[],n.consoleInstalled=!0;const r=["log","warn","error","info"];for(const t of r){const r=console[t].bind(console);console[t]=(...o)=>{const i=n.consoleLogs;i.push({level:t,message:o.map(e=>{try{return"string"==typeof e?e:JSON.stringify(e)}catch{return String(e)}}).join(" "),timestamp:(new Date).toISOString()}),i.length>e&&i.splice(0,i.length-e),r(...o)}}}function elementToInfo(e){const t=e.getBoundingClientRect(),n={};for(const t of Array.from(e.attributes))n[t.name]=t.value;return{tag:e.tagName.toLowerCase(),id:e.id,classes:Array.from(e.classList),text:(e.textContent??"").trim().slice(0,500),attributes:n,bounds:{x:Math.round(t.x),y:Math.round(t.y),width:Math.round(t.width),height:Math.round(t.height)},visible:t.width>0&&t.height>0&&"hidden"!==getComputedStyle(e).visibility&&"none"!==getComputedStyle(e).display,children_count:e.children.length}}function queryDom(e,t){t=t??20;const n=document.querySelectorAll(e),r=[];for(let e=0;e<Math.min(n.length,t);e++)r.push(elementToInfo(n[e]));return r}function clickElement$1(e){const t=document.querySelector(e);if(!t)return{success:!1,message:`No element found for selector: ${e}`};const n=t.getBoundingClientRect();return t.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0,view:window,clientX:n.left+n.width/2,clientY:n.top+n.height/2})),{success:!0,message:`Clicked element: ${e}`}}function fillInput(e,t){const n=document.querySelector(e);if(!n)return{success:!1,message:`No element found for selector: ${e}`};const r=n.tagName.toLowerCase();if("input"===r||"textarea"===r){const o=n,i="textarea"===r?HTMLTextAreaElement.prototype:HTMLInputElement.prototype,s=Object.getOwnPropertyDescriptor(i,"value")?.set;return s?s.call(o,t):o.value=t,o.dispatchEvent(new Event("input",{bubbles:!0})),o.dispatchEvent(new Event("change",{bubbles:!0})),{success:!0,message:`Filled ${e} with value`}}if("select"===r){const r=n,o=Object.getOwnPropertyDescriptor(HTMLSelectElement.prototype,"value")?.set;return o?o.call(r,t):r.value=t,r.dispatchEvent(new Event("change",{bubbles:!0})),{success:!0,message:`Set ${e} to ${t}`}}return{success:!1,message:`Element ${e} is not an input/textarea/select`}}function scrollTo(e){if("string"==typeof e){const t=document.querySelector(e);return t?(t.scrollIntoView({behavior:"smooth",block:"center"}),{success:!0,message:`Scrolled to ${e}`}):{success:!1,message:`No element found for selector: ${e}`}}return window.scrollTo({left:e.x,top:e.y,behavior:"smooth"}),{success:!0,message:`Scrolled to (${e.x}, ${e.y})`}}function getHtml(e,t,n){const r=t??!0,o=n??5e4,i=e?document.querySelector(e):document.documentElement;if(!i)return{error:`No element found for selector: ${e}`};const s=r?i.outerHTML:i.innerHTML,c=s.length>o;return{html:c?s.slice(0,o):s,length:s.length,truncated:c}}function resolveUrl(e,t){if(e.match(/^[a-z]+:\/\//i))return e;if(e.match(/^\/\//))return window.location.protocol+e;if(e.match(/^[a-z]+:/i))return e;const n=document.implementation.createHTMLDocument(),r=n.createElement("base"),o=n.createElement("a");return n.head.appendChild(r),n.body.appendChild(o),t&&(r.href=t),o.href=e,o.href}getPageInfo.__schema__={name:"getPageInfo",description:"Get information about the current web page including URL, title, viewport size, detected frameworks, and performance timing. Optionally include recent console logs.",parameters:{type:"object",properties:{include_logs:{type:"boolean",description:"If true, include recent console output in the response. Default: false."},log_limit:{type:"number",description:"Maximum number of console log entries to include (most recent). Default: 50."},log_level:{type:"string",description:'Filter console logs by level: "log", "warn", "error", "info". Omit for all levels.',enum:["log","warn","error","info"]}}}},queryDom.__schema__={name:"queryDom",description:"Query DOM elements by CSS selector. Returns tag, id, classes, text content, attributes, bounding rect, and visibility for each matching element.",parameters:{type:"object",properties:{selector:{type:"string",description:'CSS selector to query, e.g. "button.primary", "#app > div".'},limit:{type:"number",description:"Maximum number of elements to return. Default: 20."}},required:["selector"]}},clickElement$1.__schema__={name:"clickElement",description:"Click a DOM element matching the CSS selector.",parameters:{type:"object",properties:{selector:{type:"string",description:"CSS selector of the element to click."}},required:["selector"]}},fillInput.__schema__={name:"fillInput",description:"Set the value of an input, textarea, or select element. Works with React controlled components.",parameters:{type:"object",properties:{selector:{type:"string",description:"CSS selector of the input element."},value:{type:"string",description:"The value to set."}},required:["selector","value"]}},scrollTo.__schema__={name:"scrollTo",description:"Scroll to a DOM element (by CSS selector) or to an absolute position {x, y}.",parameters:{type:"object",properties:{target:{description:"CSS selector string to scroll to an element, or an object {x, y} for absolute scroll position."}},required:["target"]}},getHtml.__schema__={name:"getHtml",description:"Get the HTML content of the page or a specific element. Returns outerHTML by default. Useful for understanding page structure.",parameters:{type:"object",properties:{selector:{type:"string",description:"CSS selector of the element. Omit to get the full page HTML."},outer:{type:"boolean",description:"If true (default), return outerHTML (includes the element itself). If false, return innerHTML (children only)."},max_length:{type:"number",description:"Maximum character length of the returned HTML. Default: 50000. Result will be truncated if longer."}}}};const uuid=(()=>{let e=0;return()=>(e+=1,`u${`0000${(Math.random()*36**4|0).toString(36)}`.slice(-4)}${e}`)})();function toArray(e){const t=[];for(let n=0,r=e.length;n<r;n++)t.push(e[n]);return t}let styleProps=null;function getStyleProperties(e={}){return styleProps||(e.includeStyleProperties?(styleProps=e.includeStyleProperties,styleProps):(styleProps=toArray(window.getComputedStyle(document.documentElement)),styleProps))}function px(e,t){const n=(e.ownerDocument.defaultView||window).getComputedStyle(e).getPropertyValue(t);return n?parseFloat(n.replace("px","")):0}function getNodeWidth(e){const t=px(e,"border-left-width"),n=px(e,"border-right-width");return e.clientWidth+t+n}function getNodeHeight(e){const t=px(e,"border-top-width"),n=px(e,"border-bottom-width");return e.clientHeight+t+n}function getImageSize(e,t={}){return{width:t.width||getNodeWidth(e),height:t.height||getNodeHeight(e)}}function getPixelRatio(){let e,t;try{t=process}catch(e){}const n=t&&t.env?t.env.devicePixelRatio:null;return n&&(e=parseInt(n,10),Number.isNaN(e)&&(e=1)),e||window.devicePixelRatio||1}const canvasDimensionLimit=16384;function checkCanvasDimensions(e){(e.width>canvasDimensionLimit||e.height>canvasDimensionLimit)&&(e.width>canvasDimensionLimit&&e.height>canvasDimensionLimit?e.width>e.height?(e.height*=canvasDimensionLimit/e.width,e.width=canvasDimensionLimit):(e.width*=canvasDimensionLimit/e.height,e.height=canvasDimensionLimit):e.width>canvasDimensionLimit?(e.height*=canvasDimensionLimit/e.width,e.width=canvasDimensionLimit):(e.width*=canvasDimensionLimit/e.height,e.height=canvasDimensionLimit))}function createImage(e){return new Promise((t,n)=>{const r=new Image;r.onload=()=>{r.decode().then(()=>{requestAnimationFrame(()=>t(r))})},r.onerror=n,r.crossOrigin="anonymous",r.decoding="async",r.src=e})}async function svgToDataURL(e){return Promise.resolve().then(()=>(new XMLSerializer).serializeToString(e)).then(encodeURIComponent).then(e=>`data:image/svg+xml;charset=utf-8,${e}`)}async function nodeToDataURL(e,t,n){const r="http://www.w3.org/2000/svg",o=document.createElementNS(r,"svg"),i=document.createElementNS(r,"foreignObject");return o.setAttribute("width",`${t}`),o.setAttribute("height",`${n}`),o.setAttribute("viewBox",`0 0 ${t} ${n}`),i.setAttribute("width","100%"),i.setAttribute("height","100%"),i.setAttribute("x","0"),i.setAttribute("y","0"),i.setAttribute("externalResourcesRequired","true"),o.appendChild(i),i.appendChild(e),svgToDataURL(o)}const isInstanceOfElement=(e,t)=>{if(e instanceof t)return!0;const n=Object.getPrototypeOf(e);return null!==n&&(n.constructor.name===t.name||isInstanceOfElement(n,t))};function formatCSSText(e){const t=e.getPropertyValue("content");return`${e.cssText} content: '${t.replace(/'|"/g,"")}';`}function formatCSSProperties(e,t){return getStyleProperties(t).map(t=>`${t}: ${e.getPropertyValue(t)}${e.getPropertyPriority(t)?" !important":""};`).join(" ")}function getPseudoElementStyle(e,t,n,r){const o=`.${e}:${t}`,i=n.cssText?formatCSSText(n):formatCSSProperties(n,r);return document.createTextNode(`${o}{${i}}`)}function clonePseudoElement(e,t,n,r){const o=window.getComputedStyle(e,n),i=o.getPropertyValue("content");if(""===i||"none"===i)return;const s=uuid();try{t.className=`${t.className} ${s}`}catch(e){return}const c=document.createElement("style");c.appendChild(getPseudoElementStyle(s,n,o,r)),t.appendChild(c)}function clonePseudoElements(e,t,n){clonePseudoElement(e,t,":before",n),clonePseudoElement(e,t,":after",n)}const WOFF="application/font-woff",JPEG="image/jpeg",mimes={woff:WOFF,woff2:WOFF,ttf:"application/font-truetype",eot:"application/vnd.ms-fontobject",png:"image/png",jpg:JPEG,jpeg:JPEG,gif:"image/gif",tiff:"image/tiff",svg:"image/svg+xml",webp:"image/webp"};function getExtension(e){const t=/\.([^./]*?)$/g.exec(e);return t?t[1]:""}function getMimeType(e){const t=getExtension(e).toLowerCase();return mimes[t]||""}function getContentFromDataUrl(e){return e.split(/,/)[1]}function isDataUrl(e){return-1!==e.search(/^(data:)/)}function makeDataUrl(e,t){return`data:${t};base64,${e}`}async function fetchAsDataURL(e,t,n){const r=await fetch(e,t);if(404===r.status)throw new Error(`Resource "${r.url}" not found`);const o=await r.blob();return new Promise((e,t)=>{const i=new FileReader;i.onerror=t,i.onloadend=()=>{try{e(n({res:r,result:i.result}))}catch(e){t(e)}},i.readAsDataURL(o)})}const cache={};function getCacheKey(e,t,n){let r=e.replace(/\?.*/,"");return n&&(r=e),/ttf|otf|eot|woff2?/i.test(r)&&(r=r.replace(/.*\//,"")),t?`[${t}]${r}`:r}async function resourceToDataURL(e,t,n){const r=getCacheKey(e,t,n.includeQueryParams);if(null!=cache[r])return cache[r];let o;n.cacheBust&&(e+=(/\?/.test(e)?"&":"?")+(new Date).getTime());try{o=makeDataUrl(await fetchAsDataURL(e,n.fetchRequestInit,({res:e,result:n})=>(t||(t=e.headers.get("Content-Type")||""),getContentFromDataUrl(n))),t)}catch(t){o=n.imagePlaceholder||"";let r=`Failed to fetch resource: ${e}`;t&&(r="string"==typeof t?t:t.message),r&&console.warn(r)}return cache[r]=o,o}async function cloneCanvasElement(e){const t=e.toDataURL();return"data:,"===t?e.cloneNode(!1):createImage(t)}async function cloneVideoElement(e,t){if(e.currentSrc){const t=document.createElement("canvas"),n=t.getContext("2d");t.width=e.clientWidth,t.height=e.clientHeight,null==n||n.drawImage(e,0,0,t.width,t.height);return createImage(t.toDataURL())}const n=e.poster,r=getMimeType(n);return createImage(await resourceToDataURL(n,r,t))}async function cloneIFrameElement(e,t){var n;try{if(null===(n=null==e?void 0:e.contentDocument)||void 0===n?void 0:n.body)return await cloneNode(e.contentDocument.body,t,!0)}catch(e){}return e.cloneNode(!1)}async function cloneSingleNode(e,t){return isInstanceOfElement(e,HTMLCanvasElement)?cloneCanvasElement(e):isInstanceOfElement(e,HTMLVideoElement)?cloneVideoElement(e,t):isInstanceOfElement(e,HTMLIFrameElement)?cloneIFrameElement(e,t):e.cloneNode(isSVGElement(e))}const isSlotElement=e=>null!=e.tagName&&"SLOT"===e.tagName.toUpperCase(),isSVGElement=e=>null!=e.tagName&&"SVG"===e.tagName.toUpperCase();async function cloneChildren(e,t,n){var r,o;if(isSVGElement(t))return t;let i=[];return i=isSlotElement(e)&&e.assignedNodes?toArray(e.assignedNodes()):isInstanceOfElement(e,HTMLIFrameElement)&&(null===(r=e.contentDocument)||void 0===r?void 0:r.body)?toArray(e.contentDocument.body.childNodes):toArray((null!==(o=e.shadowRoot)&&void 0!==o?o:e).childNodes),0===i.length||isInstanceOfElement(e,HTMLVideoElement)||await i.reduce((e,r)=>e.then(()=>cloneNode(r,n)).then(e=>{e&&t.appendChild(e)}),Promise.resolve()),t}function cloneCSSStyle(e,t,n){const r=t.style;if(!r)return;const o=window.getComputedStyle(e);o.cssText?(r.cssText=o.cssText,r.transformOrigin=o.transformOrigin):getStyleProperties(n).forEach(n=>{let i=o.getPropertyValue(n);if("font-size"===n&&i.endsWith("px")){const e=Math.floor(parseFloat(i.substring(0,i.length-2)))-.1;i=`${e}px`}isInstanceOfElement(e,HTMLIFrameElement)&&"display"===n&&"inline"===i&&(i="block"),"d"===n&&t.getAttribute("d")&&(i=`path(${t.getAttribute("d")})`),r.setProperty(n,i,o.getPropertyPriority(n))})}function cloneInputValue(e,t){isInstanceOfElement(e,HTMLTextAreaElement)&&(t.innerHTML=e.value),isInstanceOfElement(e,HTMLInputElement)&&t.setAttribute("value",e.value)}function cloneSelectValue(e,t){if(isInstanceOfElement(e,HTMLSelectElement)){const n=t,r=Array.from(n.children).find(t=>e.value===t.getAttribute("value"));r&&r.setAttribute("selected","")}}function decorate(e,t,n){return isInstanceOfElement(t,Element)&&(cloneCSSStyle(e,t,n),clonePseudoElements(e,t,n),cloneInputValue(e,t),cloneSelectValue(e,t)),t}async function ensureSVGSymbols(e,t){const n=e.querySelectorAll?e.querySelectorAll("use"):[];if(0===n.length)return e;const r={};for(let o=0;o<n.length;o++){const i=n[o].getAttribute("xlink:href");if(i){const n=e.querySelector(i),o=document.querySelector(i);n||!o||r[i]||(r[i]=await cloneNode(o,t,!0))}}const o=Object.values(r);if(o.length){const t="http://www.w3.org/1999/xhtml",n=document.createElementNS(t,"svg");n.setAttribute("xmlns",t),n.style.position="absolute",n.style.width="0",n.style.height="0",n.style.overflow="hidden",n.style.display="none";const r=document.createElementNS(t,"defs");n.appendChild(r);for(let e=0;e<o.length;e++)r.appendChild(o[e]);e.appendChild(n)}return e}async function cloneNode(e,t,n){return n||!t.filter||t.filter(e)?Promise.resolve(e).then(e=>cloneSingleNode(e,t)).then(n=>cloneChildren(e,n,t)).then(n=>decorate(e,n,t)).then(e=>ensureSVGSymbols(e,t)):null}const URL_REGEX=/url\((['"]?)([^'"]+?)\1\)/g,URL_WITH_FORMAT_REGEX=/url\([^)]+\)\s*format\((["']?)([^"']+)\1\)/g,FONT_SRC_REGEX=/src:\s*(?:url\([^)]+\)\s*format\([^)]+\)[,;]\s*)+/g;function toRegex(e){const t=e.replace(/([.*+?^${}()|\[\]\/\\])/g,"\\$1");return new RegExp(`(url\\(['"]?)(${t})(['"]?\\))`,"g")}function parseURLs(e){const t=[];return e.replace(URL_REGEX,(e,n,r)=>(t.push(r),e)),t.filter(e=>!isDataUrl(e))}async function embed(e,t,n,r,o){try{const i=n?resolveUrl(t,n):t,s=getMimeType(t);let c;return o||(c=await resourceToDataURL(i,s,r)),e.replace(toRegex(t),`$1${c}$3`)}catch(e){}return e}function filterPreferredFontFormat(e,{preferredFontFormat:t}){return t?e.replace(FONT_SRC_REGEX,e=>{for(;;){const[n,,r]=URL_WITH_FORMAT_REGEX.exec(e)||[];if(!r)return"";if(r===t)return`src: ${n};`}}):e}function shouldEmbed(e){return-1!==e.search(URL_REGEX)}async function embedResources(e,t,n){if(!shouldEmbed(e))return e;const r=filterPreferredFontFormat(e,n);return parseURLs(r).reduce((e,r)=>e.then(e=>embed(e,r,t,n)),Promise.resolve(r))}async function embedProp(e,t,n){var r;const o=null===(r=t.style)||void 0===r?void 0:r.getPropertyValue(e);if(o){const r=await embedResources(o,null,n);return t.style.setProperty(e,r,t.style.getPropertyPriority(e)),!0}return!1}async function embedBackground(e,t){await embedProp("background",e,t)||await embedProp("background-image",e,t),await embedProp("mask",e,t)||await embedProp("-webkit-mask",e,t)||await embedProp("mask-image",e,t)||await embedProp("-webkit-mask-image",e,t)}async function embedImageNode(e,t){const n=isInstanceOfElement(e,HTMLImageElement);if((!n||isDataUrl(e.src))&&(!isInstanceOfElement(e,SVGImageElement)||isDataUrl(e.href.baseVal)))return;const r=n?e.src:e.href.baseVal,o=await resourceToDataURL(r,getMimeType(r),t);await new Promise((r,i)=>{e.onload=r,e.onerror=t.onImageErrorHandler?(...e)=>{try{r(t.onImageErrorHandler(...e))}catch(e){i(e)}}:i;const s=e;s.decode&&(s.decode=r),"lazy"===s.loading&&(s.loading="eager"),n?(e.srcset="",e.src=o):e.href.baseVal=o})}async function embedChildren(e,t){const n=toArray(e.childNodes).map(e=>embedImages(e,t));await Promise.all(n).then(()=>e)}async function embedImages(e,t){isInstanceOfElement(e,Element)&&(await embedBackground(e,t),await embedImageNode(e,t),await embedChildren(e,t))}function applyStyle(e,t){const{style:n}=e;t.backgroundColor&&(n.backgroundColor=t.backgroundColor),t.width&&(n.width=`${t.width}px`),t.height&&(n.height=`${t.height}px`);const r=t.style;return null!=r&&Object.keys(r).forEach(e=>{n[e]=r[e]}),e}const cssFetchCache={};async function fetchCSS(e){let t=cssFetchCache[e];if(null!=t)return t;const n=await fetch(e);return t={url:e,cssText:await n.text()},cssFetchCache[e]=t,t}async function embedFonts(e,t){let n=e.cssText;const r=/url\(["']?([^"')]+)["']?\)/g,o=(n.match(/url\([^)]+\)/g)||[]).map(async o=>{let i=o.replace(r,"$1");return i.startsWith("https://")||(i=new URL(i,e.url).href),fetchAsDataURL(i,t.fetchRequestInit,({result:e})=>(n=n.replace(o,`url(${e})`),[o,e]))});return Promise.all(o).then(()=>n)}function parseCSS(e){if(null==e)return[];const t=[];let n=e.replace(/(\/\*[\s\S]*?\*\/)/gi,"");const r=new RegExp("((@.*?keyframes [\\s\\S]*?){([\\s\\S]*?}\\s*?)})","gi");for(;;){const e=r.exec(n);if(null===e)break;t.push(e[0])}n=n.replace(r,"");const o=/@import[\s\S]*?url\([^)]*\)[\s\S]*?;/gi,i=new RegExp("((\\s*?(?:\\/\\*[\\s\\S]*?\\*\\/)?\\s*?@media[\\s\\S]*?){([\\s\\S]*?)}\\s*?})|(([\\s\\S]*?){([\\s\\S]*?)})","gi");for(;;){let e=o.exec(n);if(null===e){if(e=i.exec(n),null===e)break;o.lastIndex=i.lastIndex}else i.lastIndex=o.lastIndex;t.push(e[0])}return t}async function getCSSRules(e,t){const n=[],r=[];return e.forEach(n=>{if("cssRules"in n)try{toArray(n.cssRules||[]).forEach((e,o)=>{if(e.type===CSSRule.IMPORT_RULE){let i=o+1;const s=fetchCSS(e.href).then(e=>embedFonts(e,t)).then(e=>parseCSS(e).forEach(e=>{try{n.insertRule(e,e.startsWith("@import")?i+=1:n.cssRules.length)}catch(t){console.error("Error inserting rule from remote css",{rule:e,error:t})}})).catch(e=>{console.error("Error loading remote css",e.toString())});r.push(s)}})}catch(o){const i=e.find(e=>null==e.href)||document.styleSheets[0];null!=n.href&&r.push(fetchCSS(n.href).then(e=>embedFonts(e,t)).then(e=>parseCSS(e).forEach(e=>{i.insertRule(e,i.cssRules.length)})).catch(e=>{console.error("Error loading remote stylesheet",e)})),console.error("Error inlining remote css file",o)}}),Promise.all(r).then(()=>(e.forEach(e=>{if("cssRules"in e)try{toArray(e.cssRules||[]).forEach(e=>{n.push(e)})}catch(t){console.error(`Error while reading CSS rules from ${e.href}`,t)}}),n))}function getWebFontRules(e){return e.filter(e=>e.type===CSSRule.FONT_FACE_RULE).filter(e=>shouldEmbed(e.style.getPropertyValue("src")))}async function parseWebFontRules(e,t){if(null==e.ownerDocument)throw new Error("Provided element is not within a Document");const n=toArray(e.ownerDocument.styleSheets);return getWebFontRules(await getCSSRules(n,t))}function normalizeFontFamily(e){return e.trim().replace(/["']/g,"")}function getUsedFonts(e){const t=new Set;return function e(n){(n.style.fontFamily||getComputedStyle(n).fontFamily).split(",").forEach(e=>{t.add(normalizeFontFamily(e))}),Array.from(n.children).forEach(t=>{t instanceof HTMLElement&&e(t)})}(e),t}async function getWebFontCSS(e,t){const n=await parseWebFontRules(e,t),r=getUsedFonts(e);return(await Promise.all(n.filter(e=>r.has(normalizeFontFamily(e.style.fontFamily))).map(e=>{const n=e.parentStyleSheet?e.parentStyleSheet.href:null;return embedResources(e.cssText,n,t)}))).join("\n")}async function embedWebFonts(e,t){const n=null!=t.fontEmbedCSS?t.fontEmbedCSS:t.skipFonts?null:await getWebFontCSS(e,t);if(n){const t=document.createElement("style"),r=document.createTextNode(n);t.appendChild(r),e.firstChild?e.insertBefore(t,e.firstChild):e.appendChild(t)}}async function toSvg(e,t={}){const{width:n,height:r}=getImageSize(e,t),o=await cloneNode(e,t,!0);await embedWebFonts(o,t),await embedImages(o,t),applyStyle(o,t);return await nodeToDataURL(o,n,r)}async function toCanvas(e,t={}){const{width:n,height:r}=getImageSize(e,t),o=await toSvg(e,t),i=await createImage(o),s=document.createElement("canvas"),c=s.getContext("2d"),a=t.pixelRatio||getPixelRatio(),l=t.canvasWidth||n,d=t.canvasHeight||r;return s.width=l*a,s.height=d*a,t.skipAutoScale||checkCanvasDimensions(s),s.style.width=`${l}`,s.style.height=`${d}`,t.backgroundColor&&(c.fillStyle=t.backgroundColor,c.fillRect(0,0,s.width,s.height)),c.drawImage(i,0,0,s.width,s.height),s}async function toPng(e,t={}){return(await toCanvas(e,t)).toDataURL()}async function toJpeg(e,t={}){return(await toCanvas(e,t)).toDataURL("image/jpeg",t.quality||1)}async function takeScreenshot(e,t,n,r,o,i){const s=t??"png",c=n??.92,a=r??1,l=e?document.querySelector(e):document.body;if(!l)return{error:`No element found for selector: ${e}`};try{const e=l,t={quality:c,pixelRatio:a,cacheBust:!0,skipAutoScale:!0,filter:e=>"hypha-debugger-host"!==e.id};let n;n="jpeg"===s?await toJpeg(e,t):await toPng(e,t);const r=e.getBoundingClientRect();let d=Math.round(r.width*a),h=Math.round(r.height*a);if(o&&d>o){const e=o/d;d=o,h=Math.round(h*e)}if(i&&h>i){const e=i/h;h=i,d=Math.round(d*e)}return{data:n,format:s,width:d,height:h}}catch(e){return{error:`Screenshot failed: ${e.message??e}`}}}async function executeScript(e,t){const n=t??1e4;try{const t=await Promise.race([new Function("return (async () => {"+e+"})()")(),new Promise((e,t)=>setTimeout(()=>t(new Error("Execution timed out")),n))]);let r,o=typeof t;try{void 0===t?(r=null,o="undefined"):t instanceof HTMLElement?(r={tag:t.tagName.toLowerCase(),id:t.id,text:(t.textContent??"").trim().slice(0,500)},o="HTMLElement"):t instanceof NodeList||t instanceof HTMLCollection?(r=Array.from(t).map(e=>({tag:e.tagName?.toLowerCase(),id:e.id,text:(e.textContent??"").trim().slice(0,200)})),o="NodeList"):r=JSON.parse(JSON.stringify(t))}catch{r=String(t),o="string (serialized)"}return{result:r,type:o}}catch(e){return{error:`Execution error: ${e.message??e}`}}}function navigate(e){try{return window.location.href=e,{success:!0,message:`Navigating to ${e}`}}catch(e){return{success:!1,message:`Navigation failed: ${e.message??e}`}}}function getFiberFromDOM(e){const t=Object.keys(e).find(e=>e.startsWith("__reactFiber$")||e.startsWith("__reactInternalInstance$"));return t?e[t]:null}function getComponentName(e){const{type:t}=e;if(!t)return"(unknown)";if("string"==typeof t)return t;if("function"==typeof t)return t.displayName||t.name||"Anonymous";if("object"==typeof t){if(t.displayName)return t.displayName;if(t.render)return t.render.displayName||t.render.name||"ForwardRef";if(t.type)return getComponentName({type:t.type});if("Symbol(react.memo)"===t.$$typeof?.toString())return`Memo(${getComponentName({type:t.type})})`}return"(unknown)"}function getFiberType(e){return 0===e.tag||11===e.tag||14===e.tag||15===e.tag?"function":1===e.tag?"class":5===e.tag||6===e.tag?"host":"other"}function safeSerialize(e,t=0,n=2){if(t>n)return"[max depth]";if(null==e)return e;if("function"==typeof e)return`[Function: ${e.name||"anonymous"}]`;if("object"!=typeof e)return e;if(e instanceof HTMLElement)return`[${e.tagName.toLowerCase()}#${e.id}]`;if(Array.isArray(e))return e.slice(0,10).map(e=>safeSerialize(e,t+1,n));const r={},o=Object.keys(e).slice(0,20);for(const i of o)if(!i.startsWith("_")&&!i.startsWith("$$"))try{r[i]=safeSerialize(e[i],t+1,n)}catch{r[i]="[unserializable]"}return r}function extractState(e){if(1===e.tag&&e.stateNode)return safeSerialize(e.stateNode.state);if(0===e.tag||11===e.tag||15===e.tag){const t=[];let n=e.memoizedState,r=0;for(;n&&r<20;)null!==n.queue&&void 0!==n.queue&&t.push(safeSerialize(n.memoizedState)),n=n.next,r++;return t.length>0?t:null}return null}function fiberToInfo(e,t,n){const r=getFiberType(e),o="function"===r||"class"===r,i={name:getComponentName(e),type:r,props:o?safeSerialize(e.memoizedProps):{},state:o?extractState(e):null,key:e.key,children:[]};if(t<n){let r=e.child;for(;r;){const e=fiberToInfo(r,t+1,n);e&&("host"!==e.type||e.children.length>0)&&i.children.push(e),r=r.sibling}}return i}function getReactTree(e,t){e=e??"#root";const n=t??5,r=document.querySelector(e);if(!r)return{error:`No element found for selector: ${e}`};const o=getFiberFromDOM(r);if(!o)return{error:`No React fiber found on element "${e}". Is this a React app?`};let i=o;for(;i&&3===i.tag;)i=i.child;if(!i)return{error:"Could not find root React component fiber."};const s=fiberToInfo(i,0,n);return s||{error:"Could not build React component tree."}}function generateSkillMd(e,t){const n=["---","name: web-debugger","description: Remote web page debugger. Inspect DOM, take screenshots, execute JavaScript, fill forms, click elements, and navigate pages — all via HTTP API calls.","compatibility: Requires network access to the Hypha server. Works with any HTTP client (curl, fetch, Python requests).","metadata:",' version: "0.1"',' author: "hypha-debugger"',"---"].join("\n"),r=["","# Web Debugger Skill","","This skill allows you to remotely debug and interact with a web page through HTTP API endpoints.","","## Recommended Workflow (Index-Based Interaction)","","The most reliable way to interact with a page is using the smart DOM analysis:","","### Step 1: Observe the page","```bash","curl '{SERVICE_URL}/get_browser_state'","```","This returns all interactive elements indexed as `[0]`, `[1]`, `[2]`, etc.","Elements are detected via smart heuristics: CSS cursor, ARIA roles, event listeners, tag names.","Visual highlight labels are overlaid on the page for each detected element.","","Example output:","```","[0]<a aria-label=Home>Home />","[1]<input placeholder=Search... />","[2]<button>Sign In />","[3]<select name=language>English />",'[4]<div data-scrollable="top=200, bottom=1500">Content area />',"```","","### Step 2: Act on elements by index","```bash","# Click a button (e.g. [2] Sign In):","curl -X POST '{SERVICE_URL}/click_element_by_index' \\"," -H 'Content-Type: application/json' -d '{\"index\": 2}'","","# Type into an input (e.g. [1] Search):","curl -X POST '{SERVICE_URL}/input_text' \\",' -H \'Content-Type: application/json\' -d \'{"index": 1, "text": "hello world"}\'',"","# Select a dropdown option (e.g. [3] Language):","curl -X POST '{SERVICE_URL}/select_option' \\",' -H \'Content-Type: application/json\' -d \'{"index": 3, "option_text": "French"}\'',"","# Scroll down:","curl -X POST '{SERVICE_URL}/scroll' \\"," -H 'Content-Type: application/json' -d '{\"direction\": \"down\"}'","","# Scroll a specific container (e.g. [4]):","curl -X POST '{SERVICE_URL}/scroll' \\",' -H \'Content-Type: application/json\' -d \'{"direction": "down", "index": 4}\'',"```","","### Step 3: Verify","```bash","curl '{SERVICE_URL}/take_screenshot'","```","","### Remove visual highlights (optional, for clean screenshots)","```bash","curl '{SERVICE_URL}/remove_highlights'","```","","## CSS Selector-Based Functions (Alternative)","","You can also use CSS selectors directly for precise targeting:","```bash","curl -X POST '{SERVICE_URL}/click_element' \\"," -H 'Content-Type: application/json' -d '{\"selector\": \"button.submit\"}'","","curl -X POST '{SERVICE_URL}/fill_input' \\",' -H \'Content-Type: application/json\' -d \'{"selector": "#email", "value": "user@example.com"}\'',"```","","## How to call functions","","All functions are available as HTTP endpoints. Replace `{SERVICE_URL}` with the actual service URL.","","- **GET** for functions with no required parameters","- **POST** with JSON body for functions with parameters",""].join("\n"),o=["## Available Functions",""],i=Object.entries(e).filter(([e,t])=>t?.__schema__&&"get_skill_md"!==e);for(const[e,t]of i){const n=t.__schema__;o.push(`### \`${e}\``),o.push(""),o.push(n.description),o.push("");const r=n.parameters?.properties,i=n.parameters?.required??[];if(r&&Object.keys(r).length>0){o.push("**Parameters:**"),o.push(""),o.push("| Parameter | Type | Required | Description |"),o.push("|-----------|------|----------|-------------|");for(const[e,t]of Object.entries(r)){const n=i.includes(e);let r=t.type??"any";t.enum&&(r=t.enum.map(e=>`"${e}"`).join(" | ")),t.items&&(r=`${t.items.type}[]`),o.push(`| \`${e}\` | ${r} | ${n?"Yes":"No"} | ${t.description??""} |`)}if(o.push(""),i.length>0){const t={};for(const e of i){const n=r[e];t[e]="string"===n?.type?`<${e}>`:"number"===n?.type?"0":`<${e}>`}o.push("**Example:**"),o.push("```bash"),o.push(`curl -X POST '{SERVICE_URL}/${e}' \\`),o.push(" -H 'Content-Type: application/json' \\"),o.push(` -d '${JSON.stringify(t)}'`),o.push("```")}else o.push("**Example:**"),o.push("```bash"),o.push(`curl '{SERVICE_URL}/${e}'`),o.push("```")}else o.push("**Parameters:** None"),o.push(""),o.push("**Example:**"),o.push("```bash"),o.push(`curl '{SERVICE_URL}/${e}'`),o.push("```");o.push("")}const s=["## Tips","","- **Start with `get_browser_state`** — it's the best way to understand what's on the page and what you can interact with.","- **Prefer index-based interaction** (`click_element_by_index`, `input_text`, `select_option`) over CSS selectors — indices are more reliable across dynamic pages.","- **After each action, call `get_browser_state` again** — element indices change when the DOM updates.","- **Use `take_screenshot`** to visually verify the page state. Call `remove_highlights` first for a clean view.","- **Use `execute_script`** for anything not covered by the built-in functions — it runs arbitrary JavaScript.","- **Use `scroll`** with an element index to scroll inside a specific container (e.g. a chat window, sidebar).","- **Use `get_page_info` with `include_logs=true`** to check for JavaScript errors or debug output.","- **Use `get_react_tree`** if the page uses React — it gives you component names, props, and state.","- All POST endpoints accept JSON body with the parameter names as keys.",""].join("\n");return[n,r,o.join("\n"),s].join("\n")}takeScreenshot.__schema__={name:"takeScreenshot",description:"Capture a screenshot of the entire page or a specific element. Returns a base64-encoded data URL.",parameters:{type:"object",properties:{selector:{type:"string",description:"CSS selector of the element to capture. Omit to capture the entire page body."},format:{type:"string",enum:["png","jpeg"],description:'Image format. Default: "png".'},quality:{type:"number",description:"Image quality (0-1) for JPEG. Default: 0.92."},scale:{type:"number",description:"Pixel ratio / scale factor. Default: 1. Use 2 for retina."},max_width:{type:"number",description:"Maximum width in pixels. Image will be scaled down if larger."},max_height:{type:"number",description:"Maximum height in pixels. Image will be scaled down if larger."}}}},executeScript.__schema__={name:"executeScript",description:"Execute arbitrary JavaScript code in the page context. Supports async/await. Returns the result of the last expression.",parameters:{type:"object",properties:{code:{type:"string",description:'JavaScript code to execute. The result of the last expression is returned. Example: "return document.title"'},timeout_ms:{type:"number",description:"Maximum execution time in milliseconds. Default: 10000."}},required:["code"]}},navigate.__schema__={name:"navigate",description:"Navigate the browser to a new URL.",parameters:{type:"object",properties:{url:{type:"string",description:"The URL to navigate to."}},required:["url"]}},getReactTree.__schema__={name:"getReactTree",description:"Inspect the React component tree starting from a DOM element. Returns component names, props, state (including hooks), and children hierarchy.",parameters:{type:"object",properties:{selector:{type:"string",description:'CSS selector of the React root element. Default: "#root".'},max_depth:{type:"number",description:"Maximum depth to traverse the component tree. Default: 5."}}}};var domTree=(e={doHighlightElements:!0,focusHighlightIndex:-1,viewportExpansion:0,debugMode:!1,interactiveBlacklist:[],interactiveWhitelist:[],highlightOpacity:.1,highlightLabelOpacity:.5})=>{const{interactiveBlacklist:t,interactiveWhitelist:n,highlightOpacity:r,highlightLabelOpacity:o}=e,{doHighlightElements:i,focusHighlightIndex:s,viewportExpansion:c,debugMode:a}=e;let l=0;const d=new WeakMap;const h={boundingRects:new WeakMap,clientRects:new WeakMap,computedStyles:new WeakMap,clearCache:()=>{h.boundingRects=new WeakMap,h.clientRects=new WeakMap,h.computedStyles=new WeakMap}};function u(e){if(!e)return null;if(h.boundingRects.has(e))return h.boundingRects.get(e);const t=e.getBoundingClientRect();return t&&h.boundingRects.set(e,t),t}function _(e){if(!e)return null;if(h.computedStyles.has(e))return h.computedStyles.get(e);const t=window.getComputedStyle(e);return t&&h.computedStyles.set(e,t),t}const p={},f={current:0},m="playwright-highlight-container";function g(e,t,n=null){if(!e)return t;const i=[];let s=null,c=20,a=16,l=null;try{let d=document.getElementById(m);d||(d=document.createElement("div"),d.id=m,d.style.position="fixed",d.style.pointerEvents="none",d.style.top="0",d.style.left="0",d.style.width="100%",d.style.height="100%",d.style.zIndex="2147483640",d.style.backgroundColor="transparent",document.body.appendChild(d));const h=e.getClientRects();if(!h||0===h.length)return t;const u=["#FF0000","#00FF00","#0000FF","#FFA500","#800080","#008080","#FF69B4","#4B0082","#FF4500","#2E8B57","#DC143C","#4682B4"];let _=u[t%u.length];const p=_+Math.floor(255*r).toString(16).padStart(2,"0");_+=Math.floor(255*o).toString(16).padStart(2,"0");let f={x:0,y:0};if(n){const e=n.getBoundingClientRect();f.x=e.left,f.y=e.top}const g=document.createDocumentFragment();for(const e of h){if(0===e.width||0===e.height)continue;const t=document.createElement("div");t.style.position="fixed",t.style.border=`2px solid ${_}`,t.style.backgroundColor=p,t.style.pointerEvents="none",t.style.boxSizing="border-box";const n=e.top+f.y,r=e.left+f.x;t.style.top=`${n}px`,t.style.left=`${r}px`,t.style.width=`${e.width}px`,t.style.height=`${e.height}px`,g.appendChild(t),i.push({element:t,initialRect:e})}const y=h[0];s=document.createElement("div"),s.className="playwright-highlight-label",s.style.position="fixed",s.style.background=_,s.style.color="white",s.style.padding="1px 4px",s.style.borderRadius="4px",s.style.fontSize=`${Math.min(12,Math.max(8,y.height/2))}px`,s.textContent=t.toString(),c=s.offsetWidth>0?s.offsetWidth:c,a=s.offsetHeight>0?s.offsetHeight:a;const w=y.top+f.y,b=y.left+f.x;let v=w+2,E=b+y.width-c-2;(y.width<c+4||y.height<a+4)&&(v=w-a-2,E=b+y.width-c,E<f.x&&(E=b)),v=Math.max(0,Math.min(v,window.innerHeight-a)),E=Math.max(0,Math.min(E,window.innerWidth-c)),s.style.top=`${v}px`,s.style.left=`${E}px`,g.appendChild(s);const k=(e,t)=>{let n=0;return(...r)=>{const o=performance.now();if(!(o-n<t))return n=o,e(...r)}},x=k(()=>{const t=e.getClientRects();let r={x:0,y:0};if(n){const e=n.getBoundingClientRect();r.x=e.left,r.y=e.top}if(i.forEach((e,n)=>{if(n<t.length){const o=t[n],i=o.top+r.y,s=o.left+r.x;e.element.style.top=`${i}px`,e.element.style.left=`${s}px`,e.element.style.width=`${o.width}px`,e.element.style.height=`${o.height}px`,e.element.style.display=0===o.width||0===o.height?"none":"block"}else e.element.style.display="none"}),t.length<i.length)for(let e=t.length;e<i.length;e++)i[e].element.style.display="none";if(s&&t.length>0){const e=t[0],n=e.top+r.y,o=e.left+r.x;let i=n+2,l=o+e.width-c-2;(e.width<c+4||e.height<a+4)&&(i=n-a-2,l=o+e.width-c,l<r.x&&(l=o)),i=Math.max(0,Math.min(i,window.innerHeight-a)),l=Math.max(0,Math.min(l,window.innerWidth-c)),s.style.top=`${i}px`,s.style.left=`${l}px`,s.style.display="block"}else s&&(s.style.display="none")},16);return window.addEventListener("scroll",x,!0),window.addEventListener("resize",x),l=()=>{window.removeEventListener("scroll",x,!0),window.removeEventListener("resize",x),i.forEach(e=>e.element.remove()),s&&s.remove()},d.appendChild(g),t+1}finally{l&&(window._highlightCleanupFunctions=window._highlightCleanupFunctions||[]).push(l)}}function y(e){if(!e||e.nodeType!==Node.ELEMENT_NODE)return null;const t=_(e);if(!t)return null;const n=t.display;if("inline"===n||"inline-block"===n)return null;const r=t.overflowX,o=t.overflowY,i="auto"===r||"scroll"===r,s="auto"===o||"scroll"===o;if(!i&&!s)return null;const c=e.scrollWidth-e.clientWidth,a=e.scrollHeight-e.clientHeight;if(c<4&&a<4)return null;if(!s&&c<4)return null;if(!i&&a<4)return null;const l=e.scrollTop,h=e.scrollLeft,u={top:l,right:e.scrollWidth-e.clientWidth-e.scrollLeft,bottom:e.scrollHeight-e.clientHeight-e.scrollTop,left:h};return function(e,t){e&&e.nodeType===Node.ELEMENT_NODE&&d.set(e,{...d.get(e),...t})}(e,{scrollable:!0,scrollData:u}),u}function w(e){try{if(-1===c){const t=e.parentElement;if(!t)return!1;try{return t.checkVisibility({checkOpacity:!0,checkVisibilityCSS:!0})}catch(e){const n=window.getComputedStyle(t);return"none"!==n.display&&"hidden"!==n.visibility&&"0"!==n.opacity}}const t=document.createRange();t.selectNodeContents(e);const n=t.getClientRects();if(!n||0===n.length)return!1;let r=!1,o=!1;for(const e of n)if(e.width>0&&e.height>0&&(r=!0,!(e.bottom<-c||e.top>window.innerHeight+c||e.right<-c||e.left>window.innerWidth+c))){o=!0;break}if(!r||!o)return!1;const i=e.parentElement;if(!i)return!1;try{return i.checkVisibility({checkOpacity:!0,checkVisibilityCSS:!0})}catch(e){const t=window.getComputedStyle(i);return"none"!==t.display&&"hidden"!==t.visibility&&"0"!==t.opacity}}catch(e){return console.warn("Error checking text node visibility:",e),!1}}function b(e){const t=_(e);return e.offsetWidth>0&&e.offsetHeight>0&&"hidden"!==t?.visibility&&"none"!==t?.display}function v(e){if(!e||e.nodeType!==Node.ELEMENT_NODE)return!1;if(t.includes(e))return!1;if(n.includes(e))return!0;const r=e.tagName.toLowerCase(),o=_(e),i=new Set(["pointer","move","text","grab","grabbing","cell","copy","alias","all-scroll","col-resize","context-menu","crosshair","e-resize","ew-resize","help","n-resize","ne-resize","nesw-resize","ns-resize","nw-resize","nwse-resize","row-resize","s-resize","se-resize","sw-resize","vertical-text","w-resize","zoom-in","zoom-out"]),s=new Set(["not-allowed","no-drop","wait","progress","initial","inherit"]);let c=function(e){return"html"!==e.tagName.toLowerCase()&&!(!o?.cursor||!i.has(o.cursor))}(e);if(c)return!0;const a=new Set(["a","button","input","select","textarea","details","summary","label","option","optgroup","fieldset","legend"]),l=new Set(["disabled","readonly"]);if(a.has(r)){if(o?.cursor&&s.has(o.cursor))return!1;for(const t of l)if(e.hasAttribute(t)||"true"===e.getAttribute(t)||""===e.getAttribute(t))return!1;return!e.disabled&&(!e.readOnly&&!e.inert)}const d=e.getAttribute("role"),h=e.getAttribute("aria-role");if("true"===e.getAttribute("contenteditable")||e.isContentEditable)return!0;if(e.classList&&(e.classList.contains("button")||e.classList.contains("dropdown-toggle")||e.getAttribute("data-index")||"dropdown"===e.getAttribute("data-toggle")||"true"===e.getAttribute("aria-haspopup")))return!0;const u=new Set(["button","menu","menubar","menuitem","menuitemradio","menuitemcheckbox","radio","checkbox","tab","switch","slider","spinbutton","combobox","searchbox","textbox","listbox","option","scrollbar"]);if(a.has(r)||d&&u.has(d)||h&&u.has(h))return!0;try{if("function"==typeof getEventListeners){const t=getEventListeners(e),n=["click","mousedown","mouseup","dblclick"];for(const e of n)if(t[e]&&t[e].length>0)return!0}const t=e?.ownerDocument?.defaultView?.getEventListenersForNode||window.getEventListenersForNode;if("function"==typeof t){const n=t(e),r=["click","mousedown","mouseup","keydown","keyup","submit","change","input","focus","blur"];for(const e of r)for(const t of n)if(t.type===e)return!0}const n=["onclick","onmousedown","onmouseup","ondblclick"];for(const t of n)if(e.hasAttribute(t)||"function"==typeof e[t])return!0}catch(e){}return!!y(e)}function E(e){if(-1===c)return!0;const t=function(e){if(!e)return null;if(h.clientRects.has(e))return h.clientRects.get(e);const t=e.getClientRects();return t&&h.clientRects.set(e,t),t}(e);if(!t||0===t.length)return!1;let n=!1;for(const e of t)if(e.width>0&&e.height>0&&!(e.bottom<-c||e.top>window.innerHeight+c||e.right<-c||e.left>window.innerWidth+c)){n=!0;break}if(!n)return!1;if(e.ownerDocument!==window.document)return!0;let r=Array.from(t).find(e=>e.width>0&&e.height>0);if(!r)return!1;const o=e.getRootNode();if(o instanceof ShadowRoot){const t=r.left+r.width/2,n=r.top+r.height/2;try{const r=o.elementFromPoint(t,n);if(!r)return!1;let i=r;for(;i&&i!==o;){if(i===e)return!0;i=i.parentElement}return!1}catch(e){return!0}}return[{x:r.left+r.width/2,y:r.top+r.height/2},{x:r.left+5,y:r.top+5},{x:r.right-5,y:r.bottom-5}].some(({x:t,y:n})=>{try{const r=document.elementFromPoint(t,n);if(!r)return!1;let o=r;for(;o&&o!==document.documentElement;){if(o===e)return!0;o=o.parentElement}return!1}catch(e){return!0}})}const k=new Set(["a","button","input","select","textarea","summary","details","label","option"]),x=new Set(["button","link","menuitem","menuitemradio","menuitemcheckbox","radio","checkbox","tab","switch","slider","spinbutton","combobox","searchbox","textbox","listbox","option","scrollbar"]);function S(e){if(!e||e.nodeType!==Node.ELEMENT_NODE)return!1;const t=e.tagName.toLowerCase(),n=e.getAttribute("role");if("iframe"===t)return!0;if(k.has(t))return!0;if(n&&x.has(n))return!0;if(e.isContentEditable||"true"===e.getAttribute("contenteditable"))return!0;if(e.hasAttribute("data-testid")||e.hasAttribute("data-cy")||e.hasAttribute("data-test"))return!0;if(e.hasAttribute("onclick")||"function"==typeof e.onclick)return!0;try{const t=e?.ownerDocument?.defaultView?.getEventListenersForNode||window.getEventListenersForNode;if("function"==typeof t){const n=t(e),r=["click","mousedown","mouseup","keydown","keyup","submit","change","input","focus","blur"];for(const e of r)for(const t of n)if(t.type===e)return!0}if(["onmousedown","onmouseup","onkeydown","onkeyup","onsubmit","onchange","oninput","onfocus","onblur"].some(t=>e.hasAttribute(t)))return!0}catch(e){}return!!function(e){if(!e||e.nodeType!==Node.ELEMENT_NODE)return!1;if(!b(e))return!1;const t=e.hasAttribute("role")||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||"function"==typeof e.onclick,n=/\b(btn|clickable|menu|item|entry|link)\b/i.test(e.className||""),r=Boolean(e.closest('button,a,[role="button"],.menu,.dropdown,.list,.toolbar')),o=[...e.children].some(b),i=e.parentElement&&e.parentElement.isSameNode(document.body);return(v(e)||t||n)&&o&&r&&!i}(e)}function T(e,t,n,r){if(!e.isInteractive)return!1;let o=!1;return o=!r||!!S(t),!(!o||(e.isInViewport=function(e,t){if(-1===t)return!0;const n=e.getClientRects();if(!n||0===n.length){const n=u(e);return!(!n||0===n.width||0===n.height||n.bottom<-t||n.top>window.innerHeight+t||n.right<-t||n.left>window.innerWidth+t)}for(const e of n)if(0!==e.width&&0!==e.height&&!(e.bottom<-t||e.top>window.innerHeight+t||e.right<-t||e.left>window.innerWidth+t))return!0;return!1}(t,c),!e.isInViewport&&-1!==c||(e.highlightIndex=l++,!i)))&&(s>=0?s===e.highlightIndex&&g(t,e.highlightIndex,n):g(t,e.highlightIndex,n),!0)}const C=function e(t,n=null,r=!1){if(!t||t.id===m||t.nodeType!==Node.ELEMENT_NODE&&t.nodeType!==Node.TEXT_NODE)return null;if(!t||t.id===m)return null;if("true"===t.dataset?.browserUseIgnore||"true"===t.dataset?.pageAgentIgnore)return null;if(t.getAttribute&&"true"===t.getAttribute("aria-hidden"))return null;if(t===document.body){const r={tagName:"body",attributes:{},xpath:"/body",children:[]};for(const o of t.childNodes){const t=e(o,n,!1);t&&r.children.push(t)}const o=""+f.current++;return p[o]=r,o}if(t.nodeType!==Node.ELEMENT_NODE&&t.nodeType!==Node.TEXT_NODE)return null;if(t.nodeType===Node.TEXT_NODE){const e=t.textContent?.trim();if(!e)return null;const n=t.parentElement;if(!n||"script"===n.tagName.toLowerCase())return null;const r=""+f.current++;return p[r]={type:"TEXT_NODE",text:e,isVisible:w(t)},r}if(t.nodeType===Node.ELEMENT_NODE&&!function(e){if(!e||!e.tagName)return!1;const t=new Set(["body","div","main","article","section","nav","header","footer"]),n=e.tagName.toLowerCase();return!!t.has(n)||!new Set(["svg","script","style","link","meta","noscript","template"]).has(n)}(t))return null;if(-1!==c&&!t.shadowRoot){const e=u(t),n=_(t),r=n&&("fixed"===n.position||"sticky"===n.position),o=t.offsetWidth>0||t.offsetHeight>0;if(!e||!r&&!o&&(e.bottom<-c||e.top>window.innerHeight+c||e.right<-c||e.left>window.innerWidth+c))return null}const o={tagName:t.tagName.toLowerCase(),attributes:{},children:[]};if(function(e){if(!e||e.nodeType!==Node.ELEMENT_NODE)return!1;const t=e.tagName.toLowerCase();return!!new Set(["a","button","input","select","textarea","details","summary","label"]).has(t)||(e.hasAttribute("onclick")||e.hasAttribute("role")||e.hasAttribute("tabindex")||e.hasAttribute("aria-")||e.hasAttribute("data-action")||"true"===e.getAttribute("contenteditable"))}(t)||"iframe"===t.tagName.toLowerCase()||"body"===t.tagName.toLowerCase()){const e=t.getAttributeNames?.()||[];for(const n of e){const e=t.getAttribute(n);o.attributes[n]=e}"input"!==t.tagName.toLowerCase()||"checkbox"!==t.type&&"radio"!==t.type||(o.attributes.checked=t.checked?"true":"false")}let i=!1;if(t.nodeType===Node.ELEMENT_NODE&&(o.isVisible=b(t),o.isVisible)){o.isTopElement=E(t);const e=t.getAttribute("role"),s="menu"===e||"menubar"===e||"listbox"===e;if((o.isTopElement||s)&&(o.isInteractive=v(t),i=T(o,t,n,r),o.ref=t,o.isInteractive&&0===Object.keys(o.attributes).length)){const e=t.getAttributeNames?.()||[];for(const n of e){const e=t.getAttribute(n);o.attributes[n]=e}}}if(t.tagName){const s=t.tagName.toLowerCase();if("iframe"===s)try{const n=t.contentDocument||t.contentWindow?.document;if(n)for(const r of n.childNodes){const n=e(r,t,!1);n&&o.children.push(n)}}catch(e){console.warn("Unable to access iframe:",e)}else if(t.isContentEditable||"true"===t.getAttribute("contenteditable")||"tinymce"===t.id||t.classList.contains("mce-content-body")||"body"===s&&t.getAttribute("data-id")?.startsWith("mce_"))for(const r of t.childNodes){const t=e(r,n,i);t&&o.children.push(t)}else{if(t.shadowRoot){o.shadowRoot=!0;for(const r of t.shadowRoot.childNodes){const t=e(r,n,i);t&&o.children.push(t)}}for(const s of t.childNodes){const t=e(s,n,i||r);t&&o.children.push(t)}}}if("a"===o.tagName&&0===o.children.length&&!o.attributes.href){const e=u(t);if(!(e&&e.width>0&&e.height>0||t.offsetWidth>0||t.offsetHeight>0))return null}o.extra=d.get(t)||null;const s=""+f.current++;return p[s]=o,s}(document.body);return h.clearCache(),{rootId:C,map:p}};const DEFAULT_VIEWPORT_EXPANSION=-1;function resolveViewportExpansion(e){return e??DEFAULT_VIEWPORT_EXPANSION}const newElementsCache=new WeakMap;function getFlatTree(e){const t=resolveViewportExpansion(e.viewportExpansion),n=[];for(const t of e.interactiveBlacklist||[])"function"==typeof t?n.push(t()):n.push(t);const r=[];for(const t of e.interactiveWhitelist||[])"function"==typeof t?r.push(t()):r.push(t);const o=domTree({doHighlightElements:!0,debugMode:!0,focusHighlightIndex:-1,viewportExpansion:t,interactiveBlacklist:n,interactiveWhitelist:r,highlightOpacity:e.highlightOpacity??0,highlightLabelOpacity:e.highlightLabelOpacity??.1});for(const e in o.map){const t=o.map[e];if(t.isInteractive&&t.ref){const e=t.ref;newElementsCache.has(e)||(newElementsCache.set(e,window.location.href),t.isNew=!0)}}return o}const globRegexCache=new Map;function globToRegex(e){let t=globRegexCache.get(e);if(!t){const n=e.replace(/[.+^${}()|[\]\\]/g,"\\$&");t=new RegExp(`^${n.replace(/\*/g,".*")}$`),globRegexCache.set(e,t)}return t}function matchAttributes(e,t){const n={};for(const r of t)if(r.includes("*")){const t=globToRegex(r);for(const r of Object.keys(e))t.test(r)&&e[r].trim()&&(n[r]=e[r].trim())}else{const t=e[r];t&&t.trim()&&(n[r]=t.trim())}return n}function flatTreeToString(e,t){const n=[...t||[],"title","type","checked","name","role","value","placeholder","data-date-format","alt","aria-label","aria-expanded","data-state","aria-checked","id","for","target","aria-haspopup","aria-controls","aria-owns","contenteditable"],r=t=>{const n=e.map[t];if(!n)return null;if("TEXT_NODE"===n.type){const e=n;return{type:"text",text:e.text,isVisible:e.isVisible,parent:null,children:[]}}{const e=n,t=[];if(e.children)for(const n of e.children){const e=r(n);e&&t.push(e)}return{type:"element",tagName:e.tagName,attributes:e.attributes??{},isVisible:e.isVisible??!1,isInteractive:e.isInteractive??!1,isTopElement:e.isTopElement??!1,isNew:e.isNew??!1,highlightIndex:e.highlightIndex,parent:null,children:t,extra:e.extra??{}}}},o=(e,t=null)=>{e.parent=t;for(const t of e.children)o(t,e)},i=r(e.rootId);if(!i)return"";o(i);const s=(e,t,r)=>{let o=t;const i="\t".repeat(t);if("element"===e.type){if(void 0!==e.highlightIndex){o+=1;const t=getAllTextTillNextClickableElement(e);let s="";if(n.length>0&&e.attributes){const r=matchAttributes(e.attributes,n),o=Object.keys(r);if(o.length>1){const e=new Set,t={};for(const n of o){const o=r[n];o.length>5&&(o in t?e.add(n):t[o]=n)}for(const t of e)delete r[t]}r.role===e.tagName&&delete r.role;const i=["aria-label","placeholder","title"];for(const e of i)r[e]&&r[e].toLowerCase().trim()===t.toLowerCase().trim()&&delete r[e];Object.keys(r).length>0&&(s=Object.entries(r).map(([e,t])=>`${e}=${((e,t)=>e.length>t?e.substring(0,t)+"...":e)(t,20)}`).join(" "))}let c=`${i}${e.isNew?`*[${e.highlightIndex}]`:`[${e.highlightIndex}]`}<${e.tagName??""}`;if(s&&(c+=` ${s}`),e.extra&&e.extra.scrollable){let t="";e.extra.scrollData?.left&&(t+=`left=${e.extra.scrollData.left}, `),e.extra.scrollData?.top&&(t+=`top=${e.extra.scrollData.top}, `),e.extra.scrollData?.right&&(t+=`right=${e.extra.scrollData.right}, `),e.extra.scrollData?.bottom&&(t+=`bottom=${e.extra.scrollData.bottom}`),c+=` data-scrollable="${t}"`}if(t){s||(c+=" "),c+=`>${t.trim()}`}else s||(c+=" ");c+=" />",r.push(c)}for(const t of e.children)s(t,o,r)}else if("text"===e.type){if((e=>{let t=e.parent;for(;t;){if("element"===t.type&&void 0!==t.highlightIndex)return!0;t=t.parent}return!1})(e))return;e.parent&&"element"===e.parent.type&&e.parent.isVisible&&e.parent.isTopElement&&r.push(`${i}${e.text??""}`)}},c=[];return s(i,0,c),c.join("\n")}const getAllTextTillNextClickableElement=(e,t=-1)=>{const n=[],r=(o,i)=>{if(!(-1!==t&&i>t||"element"===o.type&&o!==e&&void 0!==o.highlightIndex))if("text"===o.type&&o.text)n.push(o.text);else if("element"===o.type)for(const e of o.children)r(e,i+1)};return r(e,0),n.join("\n").trim()};function getSelectorMap(e){const t=new Map,n=Object.keys(e.map);for(const r of n){const n=e.map[r];n.isInteractive&&"number"==typeof n.highlightIndex&&t.set(n.highlightIndex,n)}return t}function getElementTextMap(e){const t=e.split("\n").map(e=>e.trim()).filter(e=>e.length>0),n=new Map;for(const e of t){const t=/^\[(\d+)\]<[^>]+>([^<]*)/.exec(e);if(t){const r=parseInt(t[1],10);n.set(r,e)}}return n}function cleanUpHighlights(){const e=window._highlightCleanupFunctions||[];for(const t of e)"function"==typeof t&&t();window._highlightCleanupFunctions=[]}async function waitFor(e){await new Promise(t=>setTimeout(t,1e3*e))}function getElementByIndex(e,t){const n=e.get(t);if(!n)throw new Error(`No interactive element found at index ${t}`);const r=n.ref;if(!r)throw new Error(`Element at index ${t} does not have a reference`);if(!(r instanceof HTMLElement))throw new Error(`Element at index ${t} is not an HTMLElement`);return r}let lastClickedElement=null;function blurLastClickedElement(){lastClickedElement&&(lastClickedElement.blur(),lastClickedElement.dispatchEvent(new MouseEvent("mouseout",{bubbles:!0,cancelable:!0})),lastClickedElement=null)}async function scrollIntoViewIfNeeded(e){const t=e.getBoundingClientRect();t.top>=0&&t.bottom<=window.innerHeight&&t.left>=0&&t.right<=window.innerWidth||(e.scrollIntoView({behavior:"smooth",block:"center",inline:"nearest"}),await waitFor(.4))}async function movePointerToElement(e){const t=e.getBoundingClientRect(),n=t.left+t.width/2,r=t.top+t.height/2;window.dispatchEvent(new CustomEvent("HyphaDebugger::MovePointerTo",{detail:{x:n,y:r}})),await waitFor(.3)}async function clickElement(e){blurLastClickedElement(),lastClickedElement=e,await scrollIntoViewIfNeeded(e),await movePointerToElement(e),window.dispatchEvent(new CustomEvent("HyphaDebugger::ClickPointer")),await waitFor(.05),e.dispatchEvent(new MouseEvent("mouseenter",{bubbles:!0,cancelable:!0})),e.dispatchEvent(new MouseEvent("mouseover",{bubbles:!0,cancelable:!0})),e.dispatchEvent(new MouseEvent("mousedown",{bubbles:!0,cancelable:!0})),e.focus(),e.dispatchEvent(new MouseEvent("mouseup",{bubbles:!0,cancelable:!0})),e.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0})),await waitFor(.2)}let _nativeInputValueSetter=null,_nativeTextAreaValueSetter=null;function getNativeInputValueSetter(){return _nativeInputValueSetter||(_nativeInputValueSetter=Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype,"value").set),_nativeInputValueSetter}function getNativeTextAreaValueSetter(){return _nativeTextAreaValueSetter||(_nativeTextAreaValueSetter=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value").set),_nativeTextAreaValueSetter}async function inputTextElement(e,t){const n=e.isContentEditable;if(!(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||n))throw new Error("Element is not an input, textarea, or contenteditable");await clickElement(e),n?(e.dispatchEvent(new InputEvent("beforeinput",{bubbles:!0,cancelable:!0,inputType:"deleteContent"}))&&(e.innerText="",e.dispatchEvent(new InputEvent("input",{bubbles:!0,inputType:"deleteContent"}))),e.dispatchEvent(new InputEvent("beforeinput",{bubbles:!0,cancelable:!0,inputType:"insertText",data:t}))&&(e.innerText=t,e.dispatchEvent(new InputEvent("input",{bubbles:!0,inputType:"insertText",data:t}))),e.dispatchEvent(new Event("change",{bubbles:!0})),e.blur()):e instanceof HTMLTextAreaElement?getNativeTextAreaValueSetter().call(e,t):getNativeInputValueSetter().call(e,t),n||e.dispatchEvent(new Event("input",{bubbles:!0})),await waitFor(.1),blurLastClickedElement()}async function selectOptionElement(e,t){if(!(e instanceof HTMLSelectElement))throw new Error("Element is not a select element");await scrollIntoViewIfNeeded(e);const n=e.getBoundingClientRect();window.dispatchEvent(new CustomEvent("HyphaDebugger::MovePointerTo",{detail:{x:n.left+n.width/2,y:n.top+n.height/2}})),await waitFor(.3),window.dispatchEvent(new CustomEvent("HyphaDebugger::ClickPointer"));const r=Array.from(e.options).find(e=>e.textContent?.trim()===t.trim());if(!r)throw new Error(`Option with text "${t}" not found in select element`);e.value=r.value,e.dispatchEvent(new Event("change",{bubbles:!0})),await waitFor(.1)}async function scrollVertically(e,t,n){if(n){let e=n,r=!1,o=null,i=0,s=0;const c=t;for(;e&&s<10;){const t=window.getComputedStyle(e),n=/(auto|scroll|overlay)/.test(t.overflowY),a=e.scrollHeight>e.clientHeight;if(n&&a){const t=e.scrollTop,n=e.scrollHeight-e.clientHeight;let s=c/3;s=s>0?Math.min(s,n-t):Math.max(s,-t),e.scrollTop=t+s;const a=e.scrollTop-t;if(Math.abs(a)>.5){r=!0,o=e,i=a;break}}if(e===document.body||e===document.documentElement)break;e=e.parentElement,s++}return r?`Scrolled container (${o?.tagName}) by ${i}px`:`No scrollable container found for element (${n.tagName})`}const r=t,o=e=>e&&/(auto|scroll|overlay)/.test(getComputedStyle(e).overflowY)&&e.scrollHeight>e.clientHeight&&(e=>e.clientHeight>=.5*window.innerHeight)(e);let i=document.activeElement;for(;i&&!o(i)&&i!==document.body;)i=i.parentElement;if(i=o(i)?i:Array.from(document.querySelectorAll("*")).find(o)||document.scrollingElement||document.documentElement,i===document.scrollingElement||i===document.documentElement||i===document.body){const e=window.scrollY;window.scrollBy(0,r);const t=window.scrollY,n=t-e;if(Math.abs(n)<1)return r>0?"Already at the bottom of the page.":"Already at the top of the page.";const o=document.documentElement.scrollHeight-window.innerHeight;return r>0&&t>=o-1?`Scrolled page by ${n}px. Reached the bottom.`:r<0&&t<=1?`Scrolled page by ${n}px. Reached the top.`:`Scrolled page by ${n}px.`}{const e=i.scrollTop,t=i.scrollHeight-i.clientHeight;i.scrollBy({top:r,behavior:"smooth"}),await waitFor(.1);const n=i.scrollTop,o=n-e;if(Math.abs(o)<1)return r>0?`Already at the bottom of container (${i.tagName}).`:`Already at the top of container (${i.tagName}).`;const s=r<0&&n<=1;return r>0&&n>=t-1?`Scrolled container (${i.tagName}) by ${o}px. Reached the bottom.`:s?`Scrolled container (${i.tagName}) by ${o}px. Reached the top.`:`Scrolled container (${i.tagName}) by ${o}px.`}}async function scrollHorizontally(e,t,n){if(n){let r=n,o=!1,i=null,s=0,c=0;const a=e?t:-t;for(;r&&c<10;){const e=window.getComputedStyle(r),t=/(auto|scroll|overlay)/.test(e.overflowX),n=r.scrollWidth>r.clientWidth;if(t&&n){const e=r.scrollLeft,t=r.scrollWidth-r.clientWidth;let n=a/3;n=n>0?Math.min(n,t-e):Math.max(n,-e),r.scrollLeft=e+n;const c=r.scrollLeft-e;if(Math.abs(c)>.5){o=!0,i=r,s=c;break}}if(r===document.body||r===document.documentElement)break;r=r.parentElement,c++}return o?`Scrolled container (${i?.tagName}) horizontally by ${s}px`:`No horizontally scrollable container found for element (${n.tagName})`}const r=e?t:-t,o=e=>e&&/(auto|scroll|overlay)/.test(getComputedStyle(e).overflowX)&&e.scrollWidth>e.clientWidth&&(e=>e.clientWidth>=.5*window.innerWidth)(e);let i=document.activeElement;for(;i&&!o(i)&&i!==document.body;)i=i.parentElement;if(i=o(i)?i:Array.from(document.querySelectorAll("*")).find(o)||document.scrollingElement||document.documentElement,i===document.scrollingElement||i===document.documentElement||i===document.body){const e=window.scrollX,t=document.documentElement.scrollWidth-window.innerWidth;window.scrollBy(r,0);const n=window.scrollX,o=n-e;if(Math.abs(o)<1)return r>0?"Already at the right edge of the page.":"Already at the left edge of the page.";return r>0&&n>=t-1?`Scrolled page by ${o}px. Reached the right edge.`:r<0&&n<=1?`Scrolled page by ${o}px. Reached the left edge.`:`Scrolled page horizontally by ${o}px.`}{const e=i.scrollLeft,t=i.scrollWidth-i.clientWidth;i.scrollBy({left:r,behavior:"smooth"}),await waitFor(.1);const n=i.scrollLeft,o=n-e;if(Math.abs(o)<1)return r>0?`Already at the right edge of container (${i.tagName}).`:`Already at the left edge of container (${i.tagName}).`;const s=r<0&&n<=1;return r>0&&n>=t-1?`Scrolled container (${i.tagName}) by ${o}px. Reached the right edge.`:s?`Scrolled container (${i.tagName}) by ${o}px. Reached the left edge.`:`Scrolled container (${i.tagName}) horizontally by ${o}px.`}}function getPageScrollInfo(){const e=window.innerWidth,t=window.innerHeight,n=Math.max(document.documentElement.scrollWidth,document.body.scrollWidth||0),r=Math.max(document.documentElement.scrollHeight,document.body.scrollHeight||0),o=window.scrollX||window.pageXOffset||document.documentElement.scrollLeft||0,i=window.scrollY||window.pageYOffset||document.documentElement.scrollTop||0,s=Math.max(0,r-(window.innerHeight+i)),c=Math.max(0,n-(window.innerWidth+o));return{viewport_width:e,viewport_height:t,page_width:n,page_height:r,scroll_x:o,scroll_y:i,pixels_above:i,pixels_below:s,pages_above:t>0?i/t:0,pages_below:t>0?s/t:0,total_pages:t>0?r/t:0,current_page_position:i/Math.max(1,r-t),pixels_left:o,pixels_right:c}}class PageController{constructor(e={}){this.flatTree=null,this.selectorMap=new Map,this.elementTextMap=new Map,this.simplifiedHTML="",this.isIndexed=!1,this.config=e}async getBrowserState(){const e=window.location.href,t=document.title,n=getPageScrollInfo(),r=resolveViewportExpansion(this.config.viewportExpansion);await this.updateTree();const o=this.simplifiedHTML;return{url:e,title:t,header:`${`Current Page: [${t}](${e})`}\n${`Page info: ${n.viewport_width}x${n.viewport_height}px viewport, ${n.page_width}x${n.page_height}px total, ${n.pages_above.toFixed(1)} pages above, ${n.pages_below.toFixed(1)} pages below, at ${(100*n.current_page_position).toFixed(0)}%`}\n\n${-1===r?"Interactive elements (full page):":"Interactive elements (viewport):"}\n\n${n.pixels_above>4&&-1!==r?`... ${n.pixels_above} pixels above - scroll to see more ...`:"[Start of page]"}`,content:o,footer:n.pixels_below>4&&-1!==r?`... ${n.pixels_below} pixels below - scroll to see more ...`:"[End of page]",element_count:this.selectorMap.size}}async updateTree(){return cleanUpHighlights(),this.flatTree=getFlatTree(this.config),this.simplifiedHTML=flatTreeToString(this.flatTree,this.config.includeAttributes),this.selectorMap.clear(),this.selectorMap=getSelectorMap(this.flatTree),this.elementTextMap.clear(),this.elementTextMap=getElementTextMap(this.simplifiedHTML),this.isIndexed=!0,this.simplifiedHTML}async cleanUpHighlights(){cleanUpHighlights()}assertIndexed(){if(!this.isIndexed)throw new Error("DOM tree not indexed yet. Call get_browser_state first.")}cleanUpAfterAction(){cleanUpHighlights()}async clickElement(e){try{this.assertIndexed();const t=getElementByIndex(this.selectorMap,e),n=this.elementTextMap.get(e);return this.cleanUpAfterAction(),await clickElement(t),t instanceof HTMLAnchorElement&&"_blank"===t.target?{success:!0,message:`Clicked element (${n??e}). Link opened in a new tab.`}:{success:!0,message:`Clicked element (${n??e}).`}}catch(e){return{success:!1,message:`Failed to click element: ${e}`}}}async inputText(e,t){try{this.assertIndexed();const n=getElementByIndex(this.selectorMap,e),r=this.elementTextMap.get(e);return this.cleanUpAfterAction(),await inputTextElement(n,t),{success:!0,message:`Input text "${t}" into element (${r??e}).`}}catch(e){return{success:!1,message:`Failed to input text: ${e}`}}}async selectOption(e,t){try{this.assertIndexed();const n=getElementByIndex(this.selectorMap,e),r=this.elementTextMap.get(e);return this.cleanUpAfterAction(),await selectOptionElement(n,t),{success:!0,message:`Selected option "${t}" in element (${r??e}).`}}catch(e){return{success:!1,message:`Failed to select option: ${e}`}}}async scroll(e){try{this.assertIndexed(),this.cleanUpAfterAction();const{direction:t,amount:n,index:r}=e,o=void 0!==r?getElementByIndex(this.selectorMap,r):null;let i;if("left"===t||"right"===t){const e=n??.8*window.innerWidth;i=await scrollHorizontally("right"===t,e,o)}else{const e=n??.8*window.innerHeight,r="down"===t?e:-e;i=await scrollVertically("down"===t,r,o)}return{success:!0,message:i}}catch(e){return{success:!1,message:`Failed to scroll: ${e}`}}}dispose(){cleanUpHighlights(),this.flatTree=null,this.selectorMap.clear(),this.elementTextMap.clear(),this.simplifiedHTML="",this.isIndexed=!1}}let controller=null;function getController(){return controller||(controller=new PageController({viewportExpansion:-1,highlightOpacity:.1,highlightLabelOpacity:.5})),controller}async function getBrowserState(e){const t=getController();return void 0!==e&&(t.config.viewportExpansion=e?0:-1),t.getBrowserState()}async function clickElementByIndex(e){return getController().clickElement(e)}async function inputText(e,t){return getController().inputText(e,t)}async function selectOption(e,t){return getController().selectOption(e,t)}async function scroll(e,t,n){return getController().scroll({direction:e,amount:t,index:n})}async function removeHighlights(){return getController().cleanUpHighlights(),{success:!0,message:"Highlights removed."}}function disposeController(){controller&&(controller.dispose(),controller=null)}function randomHex(e=8){const t=new Uint8Array(e);return crypto.getRandomValues(t),Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}getBrowserState.__schema__={name:"getBrowserState",description:"Get the current page state with all interactive elements indexed as [0], [1], [2], etc. Returns a simplified HTML representation optimized for LLM consumption. Interactive elements (buttons, links, inputs, scrollable areas) are detected via smart heuristics (CSS cursor, ARIA roles, event listeners, tag names). Use the returned indices with click_element_by_index, input_text, select_option, or scroll. Call this first to understand the page before performing any actions.",parameters:{type:"object",properties:{viewport_only:{type:"boolean",description:"If true, only return elements visible in the current viewport. Default: false (full page)."}}}},clickElementByIndex.__schema__={name:"clickElementByIndex",description:"Click an interactive element by its numeric index from get_browser_state output. Simulates a full mouse event sequence (hover, mousedown, focus, mouseup, click) to trigger all event listeners including React/Vue handlers.",parameters:{type:"object",properties:{index:{type:"number",description:"The element index from get_browser_state (e.g. 0 for [0], 5 for [5])."}},required:["index"]}},inputText.__schema__={name:"inputText",description:"Type text into an input, textarea, or contenteditable element by its index. Replaces existing content. Works with React controlled components, contenteditable editors (LinkedIn, Quill), and native inputs.",parameters:{type:"object",properties:{index:{type:"number",description:"The element index from get_browser_state."},text:{type:"string",description:"The text to type into the element."}},required:["index","text"]}},selectOption.__schema__={name:"selectOption",description:"Select a dropdown option in a <select> element by its index and the visible option text.",parameters:{type:"object",properties:{index:{type:"number",description:"The <select> element index from get_browser_state."},option_text:{type:"string",description:"The visible text of the option to select (case-sensitive, trimmed)."}},required:["index","option_text"]}},scroll.__schema__={name:"scroll",description:"Scroll the page or a specific scrollable container. If index is provided, scrolls the nearest scrollable ancestor of that element. Otherwise scrolls the page or the largest scrollable container.",parameters:{type:"object",properties:{direction:{type:"string",enum:["up","down","left","right"],description:"Scroll direction."},amount:{type:"number",description:"Scroll amount in pixels. Default: ~80% of viewport height (vertical) or width (horizontal)."},index:{type:"number",description:"Optional element index. If provided, scrolls the nearest scrollable ancestor of this element."}},required:["direction"]}},removeHighlights.__schema__={name:"removeHighlights",description:"Remove all visual element index labels/highlights from the page. Useful after taking a screenshot if you want a clean view.",parameters:{type:"object",properties:{}}};class HyphaDebugger{constructor(e){this.overlay=null,this.cursor=null,this.server=null,this.serviceInfo=null;const t=e.require_token??!1;let n=e.service_id??"web-debugger";e.service_id||(n=`web-debugger-${randomHex(16)}`);const r=e.visibility??(t?"protected":"unlisted");this.config={server_url:e.server_url,workspace:e.workspace??"",token:e.token??"",service_id:n,service_name:e.service_name??"Web Debugger",show_ui:e.show_ui??!0,visibility:r,require_token:t}}async start(){installConsoleCapture();const e=window;if(e.__HYPHA_DEBUGGER__?.instance)return console.warn("[hypha-debugger] Already running, returning existing session."),e.__HYPHA_DEBUGGER__.session;this.config.show_ui&&(this.overlay=new DebugOverlay,this.overlay.setStatus("disconnected"),this.overlay.setInfo({Status:"Connecting..."}),this.cursor=new AICursor);try{const t=this.getConnectToServer(),n={server_url:this.config.server_url};this.config.workspace&&(n.workspace=this.config.workspace),this.config.token&&(n.token=this.config.token),this.server=await t(n),this.serviceInfo=await this.server.registerService(this.buildServiceDefinition());const r=await this.updateSession();return this.overlay&&this.overlay.addLog("Service registered","result"),e.__HYPHA_DEBUGGER__=e.__HYPHA_DEBUGGER__??{},e.__HYPHA_DEBUGGER__.instance=this,r}catch(e){throw console.error("[hypha-debugger] Failed to start:",e),this.overlay&&(this.overlay.setStatus("error"),this.overlay.setInfo({Status:"Error",Error:e.message??String(e)})),e}}async destroy(){try{this.serviceInfo&&this.server&&await this.server.unregisterService(this.serviceInfo.id)}catch{}disposeController(),this.cursor?.destroy(),this.cursor=null,this.overlay?.destroy(),this.overlay=null;const e=window;e.__HYPHA_DEBUGGER__&&(delete e.__HYPHA_DEBUGGER__.instance,delete e.__HYPHA_DEBUGGER__.session)}async updateSession(e){const t=this.serviceInfo?.id??this.config.service_id,n=this.buildServiceUrl(t),r=this.server.config?.workspace??"",o=this.config.require_token?await this.server.generateToken({expires_in:86400}):"";this.overlay&&(this.overlay.setStatus("connected"),this.overlay.setInfo({Status:"Connected",Server:this.config.server_url,...e}),this.overlay.setInstructions(this.buildInstructionBlock(n,o))),console.log(`[hypha-debugger] Service URL: ${n}`),o?(console.log(`[hypha-debugger] Token: ${o}`),console.log(`[hypha-debugger] Test:\n curl '${n}/get_page_info' -H 'Authorization: Bearer ${o}'`)):console.log(`[hypha-debugger] Test:\n curl '${n}/get_page_info'`);const i={service_id:t,workspace:r,server:this.server,service_url:n,token:o,destroy:()=>this.destroy()},s=window;return s.__HYPHA_DEBUGGER__=s.__HYPHA_DEBUGGER__??{},s.__HYPHA_DEBUGGER__.session=i,i}buildServiceUrl(e){const t=this.config.server_url.replace(/\/+$/,""),n=e.indexOf("/");if(-1!==n){const r=e.substring(0,n),o=e.substring(n+1),i=o.indexOf(":");return`${t}/${r}/services/${-1!==i?o.substring(i+1):o}`}return`${t}/services/${e}`}getHyphaModule(){if(__webpack_exports__connectToServer)return hyphaRpc;if(__webpack_exports__connectToServer)return hyphaRpcWebsocket;const e=window;if(e.hyphaWebsocketClient?.connectToServer)return e.hyphaWebsocketClient;throw new Error('hypha-rpc not found. Install it via npm or load it via: <script src="https://cdn.jsdelivr.net/npm/hypha-rpc@0.20.97/dist/hypha-rpc-websocket.min.js"><\/script>')}getConnectToServer(){return this.getHyphaModule().connectToServer}buildServiceDefinition(){return{id:this.config.service_id,name:this.config.service_name,type:"debugger",description:"Remote web page debugger. Allows inspecting DOM, taking screenshots, executing JavaScript, and interacting with the page.",config:{visibility:this.config.visibility},get_page_info:this.wrapFn(getPageInfo,"get_page_info"),get_html:this.wrapFn(getHtml,"get_html"),query_dom:this.wrapFn(queryDom,"query_dom"),click_element:this.wrapFn(clickElement$1,"click_element"),fill_input:this.wrapFn(fillInput,"fill_input"),scroll_to:this.wrapFn(scrollTo,"scroll_to"),take_screenshot:this.wrapFn(takeScreenshot,"take_screenshot"),execute_script:this.wrapFn(executeScript,"execute_script"),navigate:this.wrapFn(navigate,"navigate"),get_react_tree:this.wrapFn(getReactTree,"get_react_tree"),get_browser_state:this.wrapFn(getBrowserState,"get_browser_state"),click_element_by_index:this.wrapFn(clickElementByIndex,"click_element_by_index"),input_text:this.wrapFn(inputText,"input_text"),select_option:this.wrapFn(selectOption,"select_option"),scroll:this.wrapFn(scroll,"scroll"),remove_highlights:this.wrapFn(removeHighlights,"remove_highlights"),get_skill_md:this.wrapFn(this.createGetSkillMd(),"get_skill_md")}}createGetSkillMd(){const e=()=>{const e={},t={get_page_info:getPageInfo,get_html:getHtml,query_dom:queryDom,click_element:clickElement$1,fill_input:fillInput,scroll_to:scrollTo,take_screenshot:takeScreenshot,execute_script:executeScript,navigate:navigate,get_react_tree:getReactTree,get_browser_state:getBrowserState,click_element_by_index:clickElementByIndex,input_text:inputText,select_option:selectOption,scroll:scroll,remove_highlights:removeHighlights};for(const[n,r]of Object.entries(t))r.__schema__&&(e[n]=r);return!this.serviceInfo||this.buildServiceUrl(this.serviceInfo.id??this.config.service_id),generateSkillMd(e)};return e.__schema__={name:"getSkillMd",description:"Get the SKILL.md document describing all available debugger functions, their parameters, and usage examples. Follows the agentskills.io specification.",parameters:{type:"object",properties:{}}},e}buildInstructionBlock(e,t){const n=t?' -H "Authorization: Bearer $TOKEN"':"",r=["# Hypha Remote Debugger — Web Page","# A debugger is attached to a live web page.","# You can remotely inspect, interact with, and control this page via the HTTP API below.","#","# RECOMMENDED WORKFLOW (index-based, most reliable):","# 1. get_browser_state → see all interactive elements as [0], [1], [2], ...","# 2. click_element_by_index / input_text / select_option / scroll → act by index","# 3. take_screenshot → verify the result visually","#","# Also available: get_page_info, get_html, query_dom, click_element, fill_input,","# scroll_to, execute_script, navigate, get_react_tree, remove_highlights","#","# POST endpoints accept JSON body with parameter names as keys.","",`SERVICE_URL="${e}"`];return t&&r.push(`TOKEN="${t}"`),r.push("","# 1. Get interactive elements (smart DOM analysis with indexed elements):",`curl "$SERVICE_URL/get_browser_state"${n}`,"","# 2. Click element by index (e.g. click [3]):",`curl -X POST "$SERVICE_URL/click_element_by_index"${n} -H "Content-Type: application/json" -d '{"index": 3}'`,"","# 3. Type into an input by index:",`curl -X POST "$SERVICE_URL/input_text"${n} -H "Content-Type: application/json" -d '{"index": 5, "text": "hello"}'`,"","# Take a screenshot:",`curl "$SERVICE_URL/take_screenshot"${n}`,"","# Execute JavaScript remotely:",`curl -X POST "$SERVICE_URL/execute_script"${n} -H "Content-Type: application/json" -d '{"code": "document.title"}'`,"","# Full API docs:",`curl "$SERVICE_URL/get_skill_md"${n}`),r.join("\n")}wrapFn(e,t){const n=e.__schema__,r=n?.parameters?.properties?Object.keys(n.parameters.properties):[],o=this,i=async n=>{o.overlay?.addLog(`${t}(${o.summarizeArgs(n)})`,"call");try{const r=await e(...n);return r&&"object"==typeof r&&"error"in r?o.overlay?.addLog(`${t}: ${r.error}`,"error"):o.overlay?.addLog(`${t} -> OK`,"result"),r}catch(e){throw o.overlay?.addLog(`${t}: ${e.message}`,"error"),e}};let s;if(0===r.length)s=async(...e)=>i(e);else{const e=r.join(", ");s=new Function("callAndLog",`return async function(${e}) { return callAndLog([${e}]); }`)(i)}return n&&(s.__schema__=n),s}summarizeArgs(e){return 0===e.length?"":e.map(e=>"string"==typeof e?e.length>40?e.slice(0,40)+"...":e:"object"==typeof e&&null!==e?"{...}":String(e)).join(", ")}}async function startDebugger(e){return new HyphaDebugger(e).start()}function autoStart(){if("undefined"==typeof window||"undefined"==typeof document)return;const e=document.querySelectorAll("script[src]");let t=null;for(const n of Array.from(e))if(n.src&&n.src.includes("hypha-debugger")){t=n;break}if(t?.hasAttribute("data-manual"))return;if(window.__HYPHA_DEBUGGER__?.instance)return;const n={server_url:t?.getAttribute("data-server-url")??"https://hypha.aicell.io"};t?.getAttribute("data-workspace")&&(n.workspace=t.getAttribute("data-workspace")),t?.getAttribute("data-token")&&(n.token=t.getAttribute("data-token")),t?.getAttribute("data-service-id")&&(n.service_id=t.getAttribute("data-service-id")),t?.hasAttribute("data-no-ui")&&(n.show_ui=!1),t?.hasAttribute("data-require-token")&&(n.require_token=!0),startDebugger(n).catch(e=>{console.error("[hypha-debugger] Auto-start failed:",e)})}"undefined"!=typeof window&&("loading"===document.readyState?document.addEventListener("DOMContentLoaded",autoStart):autoStart()),exports.HyphaDebugger=HyphaDebugger,exports.startDebugger=startDebugger});
59
59
  //# sourceMappingURL=hypha-debugger.min.js.map